cuelang.org/go@v0.13.0/internal/pkg/types.go (about) 1 // Copyright 2022 CUE Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package pkg 16 17 import ( 18 "cuelang.org/go/cue" 19 "cuelang.org/go/internal/core/adt" 20 ) 21 22 // A Schema represents an arbitrary cue.Value that can hold non-concrete values. 23 // By default function arguments are checked to be concrete. 24 type Schema = cue.Value 25 26 // List represents a CUE list, which can be open or closed. 27 type List struct { 28 runtime adt.Runtime 29 node *adt.Vertex 30 isOpen bool 31 } 32 33 // Elems returns the elements of a list. 34 func (l *List) Elems() []*adt.Vertex { 35 return l.node.Elems() 36 } 37 38 // IsOpen reports whether a list is open ended. 39 func (l *List) IsOpen() bool { 40 return l.isOpen 41 } 42 43 // Struct represents a CUE struct, which can be open or closed. 44 type Struct struct { 45 runtime adt.Runtime 46 node *adt.Vertex 47 } 48 49 // Arcs returns all arcs of s. 50 func (s *Struct) Arcs() []*adt.Vertex { 51 return s.node.Arcs 52 } 53 54 // Len reports the number of regular string fields of s. 55 func (s *Struct) Len() int { 56 count := 0 57 for _, a := range s.Arcs() { 58 if a.Label.IsString() && !s.node.IsOptional(a.Label) { 59 count++ 60 } 61 } 62 return count 63 } 64 65 // IsOpen reports whether s is open or has pattern constraints. 66 func (s *Struct) IsOpen() bool { 67 if !s.node.IsClosedStruct() { 68 return true 69 } 70 // Technically this is not correct, but it is in the context of where 71 // it is used. 72 if s.node.PatternConstraints != nil && len(s.node.PatternConstraints.Pairs) > 0 { 73 return true 74 } 75 // The equivalent code for the old implementation. 76 ot := s.node.OptionalTypes() 77 return ot&^adt.HasDynamic != 0 78 } 79 80 // NumConstraintFields reports the number of explicit optional and required 81 // fields, excluding pattern constraints. 82 func (s Struct) NumConstraintFields() (count int) { 83 // If we have any optional arcs, we allow more fields. 84 for _, a := range s.node.Arcs { 85 if a.ArcType != adt.ArcMember && a.Label.IsRegular() { 86 count++ 87 } 88 } 89 return count 90 } 91 92 // A ValidationError indicates an error that is only valid if a builtin is used 93 // as a validator. 94 type ValidationError struct { 95 B *adt.Bottom 96 } 97 98 func (v ValidationError) Error() string { return v.B.Err.Error() }