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
15package pkg
16
17import (
18 "iter"
19
20 "cuelang.org/go/cue"
21 "cuelang.org/go/internal/core/adt"
22)
23
24// A Schema represents an arbitrary cue.Value that can hold non-concrete values.
25// By default function arguments are checked to be concrete.
26type Schema = cue.Value
27
28// List represents a CUE list, which can be open or closed.
29type List struct {
30 runtime adt.Runtime
31 node *adt.Vertex
32 isOpen bool
33}
34
35// Elems returns the elements of a list.
36func (l *List) Elems() iter.Seq[*adt.Vertex] {
37 return l.node.Elems()
38}
39
40// IsOpen reports whether a list is open ended.
41func (l *List) IsOpen() bool {
42 return l.isOpen
43}
44
45// Struct represents a CUE struct, which can be open or closed.
46type Struct struct {
47 runtime adt.Runtime
48 node *adt.Vertex
49}
50
51// Arcs returns all arcs of s.
52func (s *Struct) Arcs() []*adt.Vertex {
53 return s.node.Arcs
54}
55
56// Len reports the number of regular string fields of s.
57func (s *Struct) Len() int {
58 count := 0
59 for _, a := range s.Arcs() {
60 if a.Label.IsString() && !s.node.IsOptional(a.Label) {
61 count++
62 }
63 }
64 return count
65}
66
67// IsOpen reports whether s is open or has pattern constraints.
68func (s *Struct) IsOpen() bool {
69 if s.node.IsOpenStruct() {
70 return true
71 }
72 // Check for pattern constraints which indicate openness.
73 if s.node.PatternConstraints != nil && len(s.node.PatternConstraints.Pairs) > 0 {
74 return true
75 }
76 // After removing OptionalTypes, we rely on other checks for openness.
77 return false
78}
79
80// NumConstraintFields reports the number of explicit optional and required
81// fields, excluding pattern constraints.
82func (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.
94type ValidationError struct {
95 B *adt.Bottom
96}
97
98func (v ValidationError) Error() string { return v.B.Err.Error() }