1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package cue
16
17 import (
18 "bytes"
19 "encoding/json"
20 "fmt"
21 "io"
22 "math"
23 "math/big"
24 "strings"
25
26 "github.com/cockroachdb/apd/v3"
27
28 "cuelang.org/go/cue/ast"
29 "cuelang.org/go/cue/build"
30 "cuelang.org/go/cue/errors"
31 "cuelang.org/go/cue/token"
32 "cuelang.org/go/internal"
33 "cuelang.org/go/internal/core/adt"
34 "cuelang.org/go/internal/core/compile"
35 "cuelang.org/go/internal/core/convert"
36 "cuelang.org/go/internal/core/eval"
37 "cuelang.org/go/internal/core/export"
38 "cuelang.org/go/internal/core/runtime"
39 "cuelang.org/go/internal/core/subsume"
40 "cuelang.org/go/internal/core/validate"
41 internaljson "cuelang.org/go/internal/encoding/json"
42 "cuelang.org/go/internal/types"
43 )
44
45
46 type Kind = adt.Kind
47
48 const (
49
50 BottomKind Kind = adt.BottomKind
51
52
53 NullKind Kind = adt.NullKind
54
55
56 BoolKind Kind = adt.BoolKind
57
58
59 IntKind Kind = adt.IntKind
60
61
62
63
64 FloatKind Kind = adt.FloatKind
65
66
67 StringKind Kind = adt.StringKind
68
69
70 BytesKind Kind = adt.BytesKind
71
72
73 StructKind Kind = adt.StructKind
74
75
76 ListKind Kind = adt.ListKind
77
78
79
80
81
82 NumberKind Kind = IntKind | FloatKind
83
84
85 TopKind Kind = adt.TopKind
86 )
87
88
89
90
91 type structValue struct {
92 ctx *adt.OpContext
93 v Value
94 obj *adt.Vertex
95 arcs []*adt.Vertex
96 }
97
98 type hiddenStructValue = structValue
99
100
101 func (o *hiddenStructValue) Len() int {
102 if o.obj == nil {
103 return 0
104 }
105 return len(o.arcs)
106 }
107
108
109 func (o *hiddenStructValue) At(i int) (key string, v Value) {
110 arc := o.arcs[i]
111 return o.v.idx.LabelStr(arc.Label), newChildValue(o, i)
112 }
113
114 func (o *hiddenStructValue) at(i int) *adt.Vertex {
115 return o.arcs[i]
116 }
117
118
119
120 func (o *hiddenStructValue) Lookup(key string) Value {
121 f := o.v.idx.StrLabel(key)
122 i := 0
123 len := o.Len()
124 for ; i < len; i++ {
125 if o.arcs[i].Label == f {
126 break
127 }
128 }
129 if i == len {
130 x := mkErr(o.v.idx, o.obj, 0, "field not found: %v", key)
131 x.NotExists = true
132
133
134
135
136 if o.obj.Accept(o.ctx, f) {
137 x.Code = adt.IncompleteError
138 }
139 return newErrValue(o.v, x)
140 }
141 return newChildValue(o, i)
142 }
143
144
145
146 func (o *structValue) marshalJSON() (b []byte, err errors.Error) {
147 b = append(b, '{')
148 n := o.Len()
149 for i := 0; i < n; i++ {
150 k, v := o.At(i)
151 s, err := internaljson.Marshal(k)
152 if err != nil {
153 return nil, unwrapJSONError(err)
154 }
155 b = append(b, s...)
156 b = append(b, ':')
157 bb, err := internaljson.Marshal(v)
158 if err != nil {
159 return nil, unwrapJSONError(err)
160 }
161 b = append(b, bb...)
162 if i < n-1 {
163 b = append(b, ',')
164 }
165 }
166 b = append(b, '}')
167 return b, nil
168 }
169
170 var _ errors.Error = &marshalError{}
171
172 type marshalError struct {
173 err errors.Error
174 b *adt.Bottom
175 }
176
177 func toMarshalErr(v Value, b *adt.Bottom) error {
178 return &marshalError{v.toErr(b), b}
179 }
180
181 func marshalErrf(v Value, src adt.Node, code adt.ErrorCode, msg string, args ...interface{}) error {
182 arguments := append([]interface{}{code, msg}, args...)
183 b := mkErr(v.idx, src, arguments...)
184 return toMarshalErr(v, b)
185 }
186
187 func (e *marshalError) Error() string {
188 return fmt.Sprintf("cue: marshal error: %v", e.err)
189 }
190
191 func (e *marshalError) Bottom() *adt.Bottom { return e.b }
192 func (e *marshalError) Path() []string { return e.err.Path() }
193 func (e *marshalError) Msg() (string, []interface{}) { return e.err.Msg() }
194 func (e *marshalError) Position() token.Pos { return e.err.Position() }
195 func (e *marshalError) InputPositions() []token.Pos {
196 return e.err.InputPositions()
197 }
198
199 func unwrapJSONError(err error) errors.Error {
200 switch x := err.(type) {
201 case *json.MarshalerError:
202 return unwrapJSONError(x.Err)
203 case *marshalError:
204 return x
205 case errors.Error:
206 return &marshalError{x, nil}
207 default:
208 return &marshalError{errors.Wrapf(err, token.NoPos, "json error"), nil}
209 }
210 }
211
212
213 type Iterator struct {
214 val Value
215 idx *runtime.Runtime
216 ctx *adt.OpContext
217 arcs []*adt.Vertex
218 p int
219 cur Value
220 f adt.Feature
221 arcType adt.ArcType
222 }
223
224 type hiddenIterator = Iterator
225
226
227
228 func (i *Iterator) Next() bool {
229 if i.p >= len(i.arcs) {
230 i.cur = Value{}
231 return false
232 }
233 arc := i.arcs[i.p]
234 arc.Finalize(i.ctx)
235 p := linkParent(i.val.parent_, i.val.v, arc)
236 i.cur = makeValue(i.val.idx, arc, p)
237 i.f = arc.Label
238 i.arcType = arc.ArcType
239 i.p++
240 return true
241 }
242
243
244
245 func (i *Iterator) Value() Value {
246 return i.cur
247 }
248
249
250 func (i *Iterator) Selector() Selector {
251 sel := featureToSel(i.f, i.idx)
252
253 if ctype := fromArcType(i.arcType); ctype != 0 {
254 sel = wrapConstraint(sel, ctype)
255 }
256 return sel
257 }
258
259
260
261
262
263
264 func (i *hiddenIterator) Label() string {
265 if i.f == 0 {
266 return ""
267 }
268 return i.idx.LabelStr(i.f)
269 }
270
271
272
273
274 func (i *hiddenIterator) IsHidden() bool {
275 return i.f.IsHidden()
276 }
277
278
279 func (i *Iterator) IsOptional() bool {
280 return i.arcType == adt.ArcOptional
281 }
282
283
284 func (i *Iterator) FieldType() SelectorType {
285 return featureToSelType(i.f, i.arcType)
286 }
287
288
289
290
291 func (i *hiddenIterator) IsDefinition() bool {
292 return i.f.IsDef()
293 }
294
295
296
297 func marshalList(l *Iterator) (b []byte, err errors.Error) {
298 b = append(b, '[')
299 if l.Next() {
300 for i := 0; ; i++ {
301 x, err := internaljson.Marshal(l.Value())
302 if err != nil {
303 return nil, unwrapJSONError(err)
304 }
305 b = append(b, x...)
306 if !l.Next() {
307 break
308 }
309 b = append(b, ',')
310 }
311 }
312 b = append(b, ']')
313 return b, nil
314 }
315
316 func (v Value) getNum(k adt.Kind) (*adt.Num, errors.Error) {
317 v, _ = v.Default()
318 ctx := v.ctx()
319 if err := v.checkKind(ctx, k); err != nil {
320 return nil, v.toErr(err)
321 }
322 n, _ := v.eval(ctx).(*adt.Num)
323 return n, nil
324 }
325
326
327
328
329
330
331
332
333
334 func (v Value) MantExp(mant *big.Int) (exp int, err error) {
335 n, err := v.getNum(adt.NumKind)
336 if err != nil {
337 return 0, err
338 }
339 if n.X.Form != 0 {
340 return 0, ErrInfinite
341 }
342 if mant != nil {
343 mant.Set(n.X.Coeff.MathBigInt())
344 if n.X.Negative {
345 mant.Neg(mant)
346 }
347 }
348 return int(n.X.Exponent), nil
349 }
350
351
352
353 func (v hiddenValue) Decimal() (d *internal.Decimal, err error) {
354 n, err := v.getNum(adt.NumKind)
355 if err != nil {
356 return nil, err
357 }
358 return &n.X, nil
359 }
360
361
362
363
364 func (v Value) AppendInt(buf []byte, base int) ([]byte, error) {
365 i, err := v.Int(nil)
366 if err != nil {
367 return nil, err
368 }
369 return i.Append(buf, base), nil
370 }
371
372
373
374 func (v Value) AppendFloat(buf []byte, fmt byte, prec int) ([]byte, error) {
375 n, err := v.getNum(adt.NumKind)
376 if err != nil {
377 return nil, err
378 }
379 ctx := internal.BaseContext
380 nd := int(apd.NumDigits(&n.X.Coeff)) + int(n.X.Exponent)
381 if n.X.Form == apd.Infinite {
382 if n.X.Negative {
383 buf = append(buf, '-')
384 }
385 return append(buf, string('∞')...), nil
386 }
387 if fmt == 'f' && nd > 0 {
388 ctx = ctx.WithPrecision(uint32(nd + prec))
389 } else {
390 ctx = ctx.WithPrecision(uint32(prec))
391 }
392 var d apd.Decimal
393 ctx.Round(&d, &n.X)
394 return d.Append(buf, fmt), nil
395 }
396
397 var (
398
399 ErrBelow = errors.New("value was rounded down")
400
401
402 ErrAbove = errors.New("value was rounded up")
403
404
405 ErrInfinite = errors.New("infinite")
406 )
407
408
409
410
411
412 func (v Value) Int(z *big.Int) (*big.Int, error) {
413 n, err := v.getNum(adt.IntKind)
414 if err != nil {
415 return nil, err
416 }
417 if z == nil {
418 z = &big.Int{}
419 }
420 if n.X.Exponent != 0 {
421 panic("cue: exponent should always be nil for integer types")
422 }
423 z.Set(n.X.Coeff.MathBigInt())
424 if n.X.Negative {
425 z.Neg(z)
426 }
427 return z, nil
428 }
429
430
431
432
433
434 func (v Value) Int64() (int64, error) {
435 n, err := v.getNum(adt.IntKind)
436 if err != nil {
437 return 0, err
438 }
439 if !n.X.Coeff.IsInt64() {
440 if n.X.Negative {
441 return math.MinInt64, ErrAbove
442 }
443 return math.MaxInt64, ErrBelow
444 }
445 i := n.X.Coeff.Int64()
446 if n.X.Negative {
447 i = -i
448 }
449 return i, nil
450 }
451
452
453
454
455
456 func (v Value) Uint64() (uint64, error) {
457 n, err := v.getNum(adt.IntKind)
458 if err != nil {
459 return 0, err
460 }
461 if n.X.Negative {
462 return 0, ErrAbove
463 }
464 if !n.X.Coeff.IsUint64() {
465 return math.MaxUint64, ErrBelow
466 }
467 i := n.X.Coeff.Uint64()
468 return i, nil
469 }
470
471
472 func trimZeros(s string) string {
473 n1 := len(s)
474 s2 := strings.TrimRight(s, "0")
475 n2 := len(s2)
476 if p := strings.IndexByte(s2, '.'); p != -1 {
477 if p == n2-1 {
478 return s[:len(s2)+1]
479 }
480 return s2
481 }
482 if n1-n2 <= 4 {
483 return s
484 }
485 return fmt.Sprint(s2, "e+", n1-n2)
486 }
487
488 var (
489 smallestPosFloat64 *apd.Decimal
490 smallestNegFloat64 *apd.Decimal
491 maxPosFloat64 *apd.Decimal
492 maxNegFloat64 *apd.Decimal
493 )
494
495 func init() {
496 const (
497
498 smallest = "4.940656458412465441765687928682213723651e-324"
499
500 max = "1.797693134862315708145274237317043567981e+308"
501 )
502 ctx := internal.BaseContext.WithPrecision(40)
503
504 var err error
505 smallestPosFloat64, _, err = ctx.NewFromString(smallest)
506 if err != nil {
507 panic(err)
508 }
509 smallestNegFloat64, _, err = ctx.NewFromString("-" + smallest)
510 if err != nil {
511 panic(err)
512 }
513 maxPosFloat64, _, err = ctx.NewFromString(max)
514 if err != nil {
515 panic(err)
516 }
517 maxNegFloat64, _, err = ctx.NewFromString("-" + max)
518 if err != nil {
519 panic(err)
520 }
521 }
522
523
524
525
526
527
528
529 func (v Value) Float64() (float64, error) {
530 n, err := v.getNum(adt.NumKind)
531 if err != nil {
532 return 0, err
533 }
534 if n.X.IsZero() {
535 return 0.0, nil
536 }
537 if n.X.Negative {
538 if n.X.Cmp(smallestNegFloat64) == 1 {
539 return -0, ErrAbove
540 }
541 if n.X.Cmp(maxNegFloat64) == -1 {
542 return math.Inf(-1), ErrBelow
543 }
544 } else {
545 if n.X.Cmp(smallestPosFloat64) == -1 {
546 return 0, ErrBelow
547 }
548 if n.X.Cmp(maxPosFloat64) == 1 {
549 return math.Inf(1), ErrAbove
550 }
551 }
552 f, _ := n.X.Float64()
553 return f, nil
554 }
555
556
557
558 type Value struct {
559 idx *runtime.Runtime
560 v *adt.Vertex
561
562
563 parent_ *parent
564 }
565
566
567
568
569 type parent struct {
570 v *adt.Vertex
571 p *parent
572 }
573
574 func (v Value) parent() Value {
575 switch {
576 case v.v == nil:
577 return Value{}
578 case v.parent_ != nil:
579 return Value{v.idx, v.parent_.v, v.parent_.p}
580 default:
581 return Value{v.idx, v.v.Parent, nil}
582 }
583 }
584
585 type valueScope Value
586
587 func (v valueScope) Vertex() *adt.Vertex { return v.v }
588 func (v valueScope) Parent() compile.Scope {
589 p := Value(v).parent()
590 if p.v == nil {
591 return nil
592 }
593 return valueScope(p)
594 }
595
596 type hiddenValue = Value
597
598
599 func (v hiddenValue) Core(x *types.Value) {
600 x.V = v.v
601 x.R = v.idx
602 }
603
604 func newErrValue(v Value, b *adt.Bottom) Value {
605 node := &adt.Vertex{BaseValue: b}
606 if v.v != nil {
607 node.Label = v.v.Label
608 node.Parent = v.v.Parent
609 }
610 node.ForceDone()
611 node.AddConjunct(adt.MakeRootConjunct(nil, b))
612 return makeChildValue(v.parent(), node)
613 }
614
615 func newVertexRoot(idx *runtime.Runtime, ctx *adt.OpContext, x *adt.Vertex) Value {
616 if ctx != nil {
617
618
619 x.Finalize(ctx)
620 } else {
621 x.ForceDone()
622 }
623 return makeValue(idx, x, nil)
624 }
625
626 func newValueRoot(idx *runtime.Runtime, ctx *adt.OpContext, x adt.Expr) Value {
627 if n, ok := x.(*adt.Vertex); ok {
628 return newVertexRoot(idx, ctx, n)
629 }
630 node := &adt.Vertex{}
631 node.AddConjunct(adt.MakeRootConjunct(nil, x))
632 return newVertexRoot(idx, ctx, node)
633 }
634
635 func newChildValue(o *structValue, i int) Value {
636 arc := o.at(i)
637 return makeValue(o.v.idx, arc, linkParent(o.v.parent_, o.v.v, arc))
638 }
639
640
641
642 func Dereference(v Value) Value {
643 n := v.v
644 if n == nil || len(n.Conjuncts) != 1 {
645 return v
646 }
647
648 env, expr := n.Conjuncts[0].EnvExpr()
649
650
651
652 r, _ := expr.(adt.Resolver)
653 if r == nil {
654 return v
655 }
656
657 c := adt.MakeRootConjunct(env, expr)
658
659 ctx := v.ctx()
660 n, b := ctx.Resolve(c, r)
661 if b != nil {
662 return newErrValue(v, b)
663 }
664 n.Finalize(ctx)
665
666
667
668
669
670 return makeValue(v.idx, n, nil)
671 }
672
673 func makeValue(idx *runtime.Runtime, v *adt.Vertex, p *parent) Value {
674 if v.Status() == 0 || v.BaseValue == nil {
675 panic(fmt.Sprintf("not properly initialized (state: %v, value: %T)",
676 v.Status(), v.BaseValue))
677 }
678 return Value{idx, v, p}
679 }
680
681
682
683 func makeChildValue(p Value, arc *adt.Vertex) Value {
684 return makeValue(p.idx, arc, linkParent(p.parent_, p.v, arc))
685 }
686
687
688
689
690
691 func linkParent(p *parent, node, arc *adt.Vertex) *parent {
692 if p == nil && node == arc.Parent {
693 return nil
694 }
695 return &parent{node, p}
696 }
697
698 func remakeValue(base Value, env *adt.Environment, v adt.Expr) Value {
699
700
701 if v, ok := v.(*adt.Vertex); ok && !v.IsUnprocessed() {
702 return Value{base.idx, v, nil}
703 }
704 n := &adt.Vertex{Label: base.v.Label}
705 n.AddConjunct(adt.MakeRootConjunct(env, v))
706 n = manifest(base.ctx(), n)
707 n.Parent = base.v.Parent
708 return makeChildValue(base.parent(), n)
709 }
710
711 func remakeFinal(base Value, env *adt.Environment, v adt.Value) Value {
712 n := &adt.Vertex{Parent: base.v.Parent, Label: base.v.Label, BaseValue: v}
713 n.ForceDone()
714 return makeChildValue(base.parent(), n)
715 }
716
717 func (v Value) ctx() *adt.OpContext {
718 return newContext(v.idx)
719 }
720
721
722
723 func (v Value) Eval() Value {
724 if v.v == nil {
725 return v
726 }
727 x := v.v
728
729
730 x = x.ToDataSingle()
731 return makeValue(v.idx, x, v.parent_)
732
733 }
734
735
736
737 func (v Value) Default() (Value, bool) {
738 if v.v == nil {
739 return v, false
740 }
741
742 d := v.v.Default()
743 if d == v.v {
744 return v, false
745 }
746 return makeValue(v.idx, d, v.parent_), true
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814 }
815
816
817 func hasDisjunction(expr adt.Expr) bool {
818 switch x := expr.(type) {
819 case *adt.DisjunctionExpr:
820 return true
821 case *adt.Conjunction:
822 for _, v := range x.Values {
823 if hasDisjunction(v) {
824 return true
825 }
826 }
827 case *adt.BinaryExpr:
828 switch x.Op {
829 case adt.OrOp:
830 return true
831 case adt.AndOp:
832 return hasDisjunction(x.X) || hasDisjunction(x.Y)
833 }
834 }
835 return false
836 }
837
838
839 func stripNonDefaults(expr adt.Expr) (r adt.Expr, stripped bool) {
840 switch x := expr.(type) {
841 case *adt.DisjunctionExpr:
842 if !x.HasDefaults {
843 return x, false
844 }
845 d := *x
846 d.Values = []adt.Disjunct{}
847 for _, v := range x.Values {
848 if v.Default {
849 d.Values = append(d.Values, v)
850 }
851 }
852 if len(d.Values) == 1 {
853 return d.Values[0].Val, true
854 }
855 return &d, true
856
857 case *adt.BinaryExpr:
858 if x.Op != adt.AndOp {
859 return x, false
860 }
861 a, sa := stripNonDefaults(x.X)
862 b, sb := stripNonDefaults(x.Y)
863 if sa || sb {
864 bin := *x
865 bin.X = a
866 bin.Y = b
867 return &bin, true
868 }
869 return x, false
870
871 default:
872 return x, false
873 }
874 }
875
876
877
878
879
880 func (v hiddenValue) Label() (string, bool) {
881 if v.v == nil || v.v.Label == 0 {
882 return "", false
883 }
884 return v.idx.LabelStr(v.v.Label), true
885 }
886
887
888
889
890 func (v Value) Kind() Kind {
891 if v.v == nil {
892 return BottomKind
893 }
894 c := v.v.BaseValue
895 if !v.v.IsConcrete() {
896 return BottomKind
897 }
898
899 if v.IncompleteKind() == adt.ListKind && !v.v.IsClosedList() {
900 return BottomKind
901 }
902 return c.Kind()
903 }
904
905
906 func (v Value) IncompleteKind() Kind {
907 if v.v == nil {
908 return BottomKind
909 }
910 return v.v.Kind()
911 }
912
913
914 func (v Value) MarshalJSON() (b []byte, err error) {
915 b, err = v.marshalJSON()
916 if err != nil {
917 return nil, unwrapJSONError(err)
918 }
919 return b, nil
920 }
921
922 func (v Value) marshalJSON() (b []byte, err error) {
923 v, _ = v.Default()
924 if v.v == nil {
925 return internaljson.Marshal(nil)
926 }
927 ctx := newContext(v.idx)
928 x := v.eval(ctx)
929
930 if _, ok := x.(adt.Resolver); ok {
931 return nil, marshalErrf(v, x, adt.IncompleteError, "value %q contains unresolved references", str(ctx, x))
932 }
933 if !adt.IsConcrete(x) {
934 return nil, marshalErrf(v, x, adt.IncompleteError, "cannot convert incomplete value %q to JSON", str(ctx, x))
935 }
936
937
938 switch k := x.Kind(); k {
939 case adt.NullKind:
940 return internaljson.Marshal(nil)
941 case adt.BoolKind:
942 return internaljson.Marshal(x.(*adt.Bool).B)
943 case adt.IntKind, adt.FloatKind, adt.NumKind:
944 b, err := x.(*adt.Num).X.MarshalText()
945 b = bytes.TrimLeft(b, "+")
946 return b, err
947 case adt.StringKind:
948 return internaljson.Marshal(x.(*adt.String).Str)
949 case adt.BytesKind:
950 return internaljson.Marshal(x.(*adt.Bytes).B)
951 case adt.ListKind:
952 i, _ := v.List()
953 return marshalList(&i)
954 case adt.StructKind:
955 obj, err := v.structValData(ctx)
956 if err != nil {
957 return nil, toMarshalErr(v, err)
958 }
959 return obj.marshalJSON()
960 case adt.BottomKind:
961 return nil, toMarshalErr(v, x.(*adt.Bottom))
962 default:
963 return nil, marshalErrf(v, x, 0, "cannot convert value %q of type %T to JSON", str(ctx, x), x)
964 }
965 }
966
967
968
969 func (v Value) Syntax(opts ...Option) ast.Node {
970
971
972
973 if v.v == nil {
974 return nil
975 }
976 var o options = getOptions(opts)
977
978
979 p := export.Profile{
980 Simplify: !o.raw,
981 TakeDefaults: o.final,
982 ShowOptional: !o.omitOptional && !o.concrete,
983 ShowDefinitions: !o.omitDefinitions && !o.concrete,
984 ShowHidden: !o.omitHidden && !o.concrete,
985 ShowAttributes: !o.omitAttrs,
986 ShowDocs: o.docs,
987 ShowErrors: o.showErrors,
988 InlineImports: o.inlineImports,
989 }
990
991 pkgID := v.instance().ID()
992
993 bad := func(name string, err error) ast.Node {
994 const format = `"%s: internal error
995 Error: %s
996
997 Profile:
998 %#v
999
1000 Value:
1001 %v
1002
1003 You could file a bug with the above information at:
1004 https://cuelang.org/issues/new?assignees=&labels=NeedsInvestigation&template=bug_report.md&title=.
1005 `
1006 cg := &ast.CommentGroup{Doc: true}
1007 msg := fmt.Sprintf(format, name, err, p, v)
1008 for _, line := range strings.Split(msg, "\n") {
1009 cg.List = append(cg.List, &ast.Comment{Text: "// " + line})
1010 }
1011 x := &ast.BadExpr{}
1012 ast.AddComment(x, cg)
1013 return x
1014 }
1015
1016
1017 var err error
1018 var f *ast.File
1019 if o.concrete || o.final || o.resolveReferences {
1020 f, err = p.Vertex(v.idx, pkgID, v.v)
1021 if err != nil {
1022 return bad(`"cuelang.org/go/internal/core/export".Vertex`, err)
1023 }
1024 } else {
1025 p.AddPackage = true
1026 f, err = p.Def(v.idx, pkgID, v.v)
1027 if err != nil {
1028 return bad(`"cuelang.org/go/internal/core/export".Def`, err)
1029 }
1030 }
1031
1032 outer:
1033 for _, d := range f.Decls {
1034 switch d.(type) {
1035 case *ast.Package, *ast.ImportDecl:
1036 return f
1037 case *ast.CommentGroup, *ast.Attribute:
1038 default:
1039 break outer
1040 }
1041 }
1042
1043 if len(f.Decls) == 1 {
1044 if e, ok := f.Decls[0].(*ast.EmbedDecl); ok {
1045 return e.Expr
1046 }
1047 }
1048 return &ast.StructLit{
1049 Elts: f.Decls,
1050 }
1051 }
1052
1053
1054
1055 func (v Value) Doc() []*ast.CommentGroup {
1056 if v.v == nil {
1057 return nil
1058 }
1059 return export.ExtractDoc(v.v)
1060 }
1061
1062
1063
1064
1065
1066
1067
1068
1069 func (v hiddenValue) Split() []Value {
1070 if v.v == nil {
1071 return nil
1072 }
1073 a := []Value{}
1074 for _, x := range v.v.Conjuncts {
1075 env, expr := x.EnvExpr()
1076 a = append(a, remakeValue(v, env, expr))
1077 }
1078 return a
1079 }
1080
1081
1082
1083
1084
1085 func (v Value) Source() ast.Node {
1086 if v.v == nil {
1087 return nil
1088 }
1089 if len(v.v.Conjuncts) == 1 {
1090 return v.v.Conjuncts[0].Source()
1091 }
1092 return v.v.Value().Source()
1093 }
1094
1095
1096
1097
1098
1099
1100 func (v Value) BuildInstance() *build.Instance {
1101 if v.idx == nil {
1102 return nil
1103 }
1104 return v.idx.GetInstanceFromNode(v.v)
1105 }
1106
1107
1108 func (v Value) Err() error {
1109 if err := v.checkKind(v.ctx(), adt.BottomKind); err != nil {
1110 return v.toErr(err)
1111 }
1112 return nil
1113 }
1114
1115
1116
1117
1118 func (v Value) Pos() token.Pos {
1119 if v.v == nil {
1120 return token.NoPos
1121 }
1122
1123 if src := v.Source(); src != nil {
1124 if pos := src.Pos(); pos != token.NoPos {
1125 return pos
1126 }
1127 }
1128
1129 var p token.Pos
1130 for _, c := range v.v.Conjuncts {
1131 x := c.Elem()
1132 pp := pos(x)
1133 if pp == token.NoPos {
1134 continue
1135 }
1136 p = pp
1137
1138 if s, ok := x.(*adt.StructLit); ok && len(s.Fields) > 0 {
1139 break
1140 }
1141 }
1142 return p
1143 }
1144
1145
1146
1147
1148
1149
1150
1151 func (v hiddenValue) IsClosed() bool {
1152 if v.v == nil {
1153 return false
1154 }
1155 switch v.Kind() {
1156 case ListKind:
1157 return v.v.IsClosedList()
1158 case StructKind:
1159 return !v.Allows(AnyString)
1160 }
1161 return false
1162 }
1163
1164
1165
1166
1167
1168 func (v Value) Allows(sel Selector) bool {
1169 c := v.ctx()
1170 f := sel.sel.feature(c)
1171 return v.v.Accept(c, f)
1172 }
1173
1174
1175
1176
1177
1178 func (v Value) IsConcrete() bool {
1179 if v.v == nil {
1180 return false
1181 }
1182 if b, ok := v.v.BaseValue.(*adt.Bottom); ok {
1183 return !b.IsIncomplete()
1184 }
1185 if !adt.IsConcrete(v.v) {
1186 return false
1187 }
1188 if v.IncompleteKind() == adt.ListKind && !v.v.IsClosedList() {
1189 return false
1190 }
1191 return true
1192 }
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203 func (v Value) Exists() bool {
1204 if v.v == nil {
1205 return false
1206 }
1207 if err, ok := v.v.BaseValue.(*adt.Bottom); ok {
1208 return !err.NotExists
1209 }
1210 return true
1211 }
1212
1213 func (v Value) checkKind(ctx *adt.OpContext, want adt.Kind) *adt.Bottom {
1214 if v.v == nil {
1215 return errNotExists
1216 }
1217
1218 x := v.eval(ctx)
1219 if b, ok := x.(*adt.Bottom); ok {
1220 return b
1221 }
1222 k := x.Kind()
1223 if want != adt.BottomKind {
1224 if k&want == adt.BottomKind {
1225 return mkErr(v.idx, x, "cannot use value %v (type %s) as %s",
1226 ctx.Str(x), k, want)
1227 }
1228 if !adt.IsConcrete(x) {
1229 return mkErr(v.idx, x, adt.IncompleteError, "non-concrete value %v", k)
1230 }
1231 }
1232 return nil
1233 }
1234
1235 func makeInt(v Value, x int64) Value {
1236 n := &adt.Num{K: adt.IntKind}
1237 n.X.SetInt64(int64(x))
1238 return remakeFinal(v, nil, n)
1239 }
1240
1241
1242
1243
1244 func (v Value) Len() Value {
1245 if v.v != nil {
1246 switch x := v.eval(v.ctx()).(type) {
1247 case *adt.Vertex:
1248 if x.IsList() {
1249 n := &adt.Num{K: adt.IntKind}
1250 n.X.SetInt64(int64(len(x.Elems())))
1251 if x.IsClosedList() {
1252 return remakeFinal(v, nil, n)
1253 }
1254
1255
1256
1257
1258 c := &adt.Conjunction{Values: []adt.Value{
1259 &adt.BasicType{K: adt.IntKind},
1260 &adt.BoundValue{Op: adt.GreaterEqualOp, Value: n},
1261 }}
1262 return remakeFinal(v, nil, c)
1263
1264 }
1265 case *adt.Bytes:
1266 return makeInt(v, int64(len(x.B)))
1267 case *adt.String:
1268 return makeInt(v, int64(len([]rune(x.Str))))
1269 }
1270 }
1271 const msg = "len not supported for type %v"
1272 return remakeValue(v, nil, mkErr(v.idx, v.v, msg, v.Kind()))
1273
1274 }
1275
1276
1277
1278
1279 func (v hiddenValue) Elem() (Value, bool) {
1280 sel := AnyString
1281 if v.v.IsList() {
1282 sel = AnyIndex
1283 }
1284 x := v.LookupPath(MakePath(sel))
1285 return x, x.Exists()
1286 }
1287
1288
1289
1290 func (v Value) List() (Iterator, error) {
1291 v, _ = v.Default()
1292 ctx := v.ctx()
1293 if err := v.checkKind(ctx, adt.ListKind); err != nil {
1294 return Iterator{idx: v.idx, ctx: ctx}, v.toErr(err)
1295 }
1296 arcs := []*adt.Vertex{}
1297 for _, a := range v.v.Elems() {
1298 if a.Label.IsInt() {
1299 arcs = append(arcs, a)
1300 }
1301 }
1302 return Iterator{idx: v.idx, ctx: ctx, val: v, arcs: arcs}, nil
1303 }
1304
1305
1306 func (v Value) Null() error {
1307 v, _ = v.Default()
1308 if err := v.checkKind(v.ctx(), adt.NullKind); err != nil {
1309 return v.toErr(err)
1310 }
1311 return nil
1312 }
1313
1314
1315
1316
1317
1318
1319
1320 func (v Value) Bool() (bool, error) {
1321 v, _ = v.Default()
1322 ctx := v.ctx()
1323 if err := v.checkKind(ctx, adt.BoolKind); err != nil {
1324 return false, v.toErr(err)
1325 }
1326 return v.eval(ctx).(*adt.Bool).B, nil
1327 }
1328
1329
1330 func (v Value) String() (string, error) {
1331 v, _ = v.Default()
1332 ctx := v.ctx()
1333 if err := v.checkKind(ctx, adt.StringKind); err != nil {
1334 return "", v.toErr(err)
1335 }
1336 return v.eval(ctx).(*adt.String).Str, nil
1337 }
1338
1339
1340
1341 func (v Value) Bytes() ([]byte, error) {
1342 v, _ = v.Default()
1343 ctx := v.ctx()
1344 switch x := v.eval(ctx).(type) {
1345 case *adt.Bytes:
1346 return bytes.Clone(x.B), nil
1347 case *adt.String:
1348 return []byte(x.Str), nil
1349 }
1350 return nil, v.toErr(v.checkKind(ctx, adt.BytesKind|adt.StringKind))
1351 }
1352
1353
1354
1355 func (v hiddenValue) Reader() (io.Reader, error) {
1356 v, _ = v.Default()
1357 ctx := v.ctx()
1358 switch x := v.eval(ctx).(type) {
1359 case *adt.Bytes:
1360 return bytes.NewReader(x.B), nil
1361 case *adt.String:
1362 return strings.NewReader(x.Str), nil
1363 }
1364 return nil, v.toErr(v.checkKind(ctx, adt.StringKind|adt.BytesKind))
1365 }
1366
1367
1368
1369
1370
1371
1372 func (v Value) structValData(ctx *adt.OpContext) (structValue, *adt.Bottom) {
1373 return v.structValOpts(ctx, options{
1374 omitHidden: true,
1375 omitDefinitions: true,
1376 omitOptional: true,
1377 })
1378 }
1379
1380
1381 func (v Value) structValOpts(ctx *adt.OpContext, o options) (s structValue, err *adt.Bottom) {
1382 v, _ = v.Default()
1383
1384 obj := v.v
1385
1386 switch b, ok := v.v.BaseValue.(*adt.Bottom); {
1387 case ok && b.IsIncomplete() && !o.concrete && !o.final:
1388
1389
1390 case !o.omitHidden, !o.omitDefinitions:
1391 default:
1392 obj, err = v.getStruct()
1393 if err != nil {
1394 return structValue{}, err
1395 }
1396 }
1397
1398
1399
1400 features := export.VertexFeatures(ctx, obj)
1401
1402 arcs := make([]*adt.Vertex, 0, len(obj.Arcs))
1403
1404 for _, f := range features {
1405 if f.IsLet() {
1406 continue
1407 }
1408 if f.IsDef() && (o.omitDefinitions || o.concrete) {
1409 continue
1410 }
1411 if f.IsHidden() && o.omitHidden {
1412 continue
1413 }
1414 arc := obj.Lookup(f)
1415 if arc == nil {
1416 continue
1417 }
1418 switch arc.ArcType {
1419 case adt.ArcOptional:
1420 if o.omitOptional {
1421 continue
1422 }
1423 case adt.ArcRequired:
1424
1425
1426
1427 if o.omitOptional || o.concrete || o.final {
1428 arc = &adt.Vertex{
1429 Label: arc.Label,
1430 Parent: arc.Parent,
1431 Conjuncts: arc.Conjuncts,
1432 BaseValue: adt.NewRequiredNotPresentError(ctx, arc),
1433 }
1434 arc.ForceDone()
1435 }
1436 }
1437 arcs = append(arcs, arc)
1438 }
1439 return structValue{ctx, v, obj, arcs}, nil
1440 }
1441
1442
1443
1444
1445
1446 func (v hiddenValue) Struct() (*Struct, error) {
1447 ctx := v.ctx()
1448 obj, err := v.structValOpts(ctx, options{})
1449 if err != nil {
1450 return nil, v.toErr(err)
1451 }
1452 return &Struct{obj}, nil
1453 }
1454
1455 func (v Value) getStruct() (*adt.Vertex, *adt.Bottom) {
1456 ctx := v.ctx()
1457 if err := v.checkKind(ctx, adt.StructKind); err != nil {
1458 if !err.ChildError {
1459 return nil, err
1460 }
1461 }
1462 return v.v, nil
1463 }
1464
1465
1466 type Struct struct {
1467 structValue
1468 }
1469
1470 type hiddenStruct = Struct
1471
1472
1473
1474
1475 type FieldInfo struct {
1476 Selector string
1477 Name string
1478 Pos int
1479 Value Value
1480
1481 SelectorType SelectorType
1482
1483 IsDefinition bool
1484 IsOptional bool
1485 IsHidden bool
1486 }
1487
1488 func (s *hiddenStruct) Len() int {
1489 return s.structValue.Len()
1490 }
1491
1492
1493 func (s *hiddenStruct) Field(i int) FieldInfo {
1494 a := s.at(i)
1495 opt := a.ArcType == adt.ArcOptional
1496 selType := featureToSelType(a.Label, a.ArcType)
1497 ctx := s.v.ctx()
1498
1499 v := makeChildValue(s.v, a)
1500 name := s.v.idx.LabelStr(a.Label)
1501 str := a.Label.SelectorString(ctx)
1502 return FieldInfo{str, name, i, v, selType, a.Label.IsDef(), opt, a.Label.IsHidden()}
1503 }
1504
1505
1506
1507
1508 func (s *hiddenStruct) FieldByName(name string, isIdent bool) (FieldInfo, error) {
1509 f := s.v.idx.Label(name, isIdent)
1510 for i, a := range s.arcs {
1511 if a.Label == f {
1512 return s.Field(i), nil
1513 }
1514 }
1515 return FieldInfo{}, errNotFound
1516 }
1517
1518
1519 func (s *hiddenStruct) Fields(opts ...Option) *Iterator {
1520 iter, _ := s.v.Fields(opts...)
1521 return iter
1522 }
1523
1524
1525
1526 func (v Value) Fields(opts ...Option) (*Iterator, error) {
1527 o := options{omitDefinitions: true, omitHidden: true, omitOptional: true}
1528 o.updateOptions(opts)
1529 ctx := v.ctx()
1530 obj, err := v.structValOpts(ctx, o)
1531 if err != nil {
1532 return &Iterator{idx: v.idx, ctx: ctx}, v.toErr(err)
1533 }
1534
1535 return &Iterator{idx: v.idx, ctx: ctx, val: v, arcs: obj.arcs}, nil
1536 }
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546 func (v hiddenValue) Lookup(path ...string) Value {
1547 ctx := v.ctx()
1548 for _, k := range path {
1549
1550
1551 obj, err := v.structValData(ctx)
1552 if err != nil {
1553
1554 return newErrValue(v, err)
1555 }
1556 v = obj.Lookup(k)
1557 }
1558 return v
1559 }
1560
1561
1562
1563
1564
1565
1566 func (v Value) Path() Path {
1567 if v.v == nil {
1568 return Path{}
1569 }
1570 return Path{path: appendPath(nil, v)}
1571 }
1572
1573
1574
1575 func appendPath(a []Selector, v Value) []Selector {
1576 if p := v.parent(); p.v != nil {
1577 a = appendPath(a, p)
1578 }
1579
1580 if v.v.Label == 0 {
1581
1582 return a
1583 }
1584
1585 f := v.v.Label
1586 if index := f.Index(); index == adt.MaxIndex {
1587 return append(a, Selector{anySelector(f)})
1588 }
1589
1590 var sel selector
1591 switch t := f.Typ(); t {
1592 case adt.IntLabel:
1593 sel = indexSelector(f)
1594 case adt.DefinitionLabel:
1595 sel = definitionSelector(f.SelectorString(v.idx))
1596
1597 case adt.HiddenDefinitionLabel, adt.HiddenLabel:
1598 sel = scopedSelector{
1599 name: f.IdentString(v.idx),
1600 pkg: f.PkgID(v.idx),
1601 }
1602
1603 case adt.StringLabel:
1604 sel = stringSelector(f.StringValue(v.idx))
1605
1606 default:
1607 panic(fmt.Sprintf("unsupported label type %v", t))
1608 }
1609 return append(a, Selector{sel})
1610 }
1611
1612
1613
1614
1615 func (v hiddenValue) LookupDef(name string) Value {
1616 return v.LookupPath(MakePath(Def(name)))
1617 }
1618
1619 var errNotFound = errors.Newf(token.NoPos, "field not found")
1620
1621
1622
1623
1624
1625
1626 func (v hiddenValue) FieldByName(name string, isIdent bool) (f FieldInfo, err error) {
1627 s, err := v.Struct()
1628 if err != nil {
1629 return f, err
1630 }
1631 return s.FieldByName(name, isIdent)
1632 }
1633
1634
1635
1636
1637 func (v hiddenValue) LookupField(name string) (FieldInfo, error) {
1638 s, err := v.Struct()
1639 if err != nil {
1640
1641 return FieldInfo{}, err
1642 }
1643 f, err := s.FieldByName(name, true)
1644 if err != nil {
1645 return f, err
1646 }
1647 if f.IsHidden {
1648 return f, errNotFound
1649 }
1650 return f, err
1651 }
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675 func (v hiddenValue) Fill(x interface{}, path ...string) Value {
1676 if v.v == nil {
1677 return v
1678 }
1679 selectors := make([]Selector, len(path))
1680 for i, p := range path {
1681 selectors[i] = Str(p)
1682 }
1683 return v.FillPath(MakePath(selectors...), x)
1684 }
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701 func (v Value) FillPath(p Path, x interface{}) Value {
1702 if v.v == nil {
1703
1704 return v
1705 }
1706 ctx := v.ctx()
1707 if err := p.Err(); err != nil {
1708 return newErrValue(v, mkErr(v.idx, nil, 0, "invalid path: %v", err))
1709 }
1710 var expr adt.Expr
1711 switch x := x.(type) {
1712 case Value:
1713 if v.idx != x.idx {
1714 panic("values are not from the same runtime")
1715 }
1716 expr = x.v
1717 case ast.Expr:
1718 n := getScopePrefix(v, p)
1719
1720 expr = resolveExpr(ctx, n, x)
1721 default:
1722 expr = convert.GoValueToValue(ctx, x, true)
1723 }
1724 for i := len(p.path) - 1; i >= 0; i-- {
1725 switch sel := p.path[i]; sel.Type() {
1726 case StringLabel | PatternConstraint:
1727 expr = &adt.StructLit{Decls: []adt.Decl{
1728 &adt.BulkOptionalField{
1729 Filter: &adt.BasicType{K: adt.StringKind},
1730 Value: expr,
1731 },
1732 }}
1733
1734 case IndexLabel | PatternConstraint:
1735 expr = &adt.ListLit{Elems: []adt.Elem{
1736 &adt.Ellipsis{Value: expr},
1737 }}
1738
1739 case IndexLabel:
1740 i := sel.Index()
1741 list := &adt.ListLit{}
1742 any := &adt.Top{}
1743
1744 for k := 0; k < i; k++ {
1745 list.Elems = append(list.Elems, any)
1746 }
1747 list.Elems = append(list.Elems, expr, &adt.Ellipsis{})
1748 expr = list
1749
1750 default:
1751 f := &adt.Field{
1752 Label: sel.sel.feature(v.idx),
1753 Value: expr,
1754 ArcType: adt.ArcMember,
1755 }
1756 switch sel.ConstraintType() {
1757 case OptionalConstraint:
1758 f.ArcType = adt.ArcOptional
1759 case RequiredConstraint:
1760 f.ArcType = adt.ArcRequired
1761 }
1762
1763 expr = &adt.StructLit{Decls: []adt.Decl{f}}
1764 }
1765 }
1766 n := &adt.Vertex{}
1767 n.AddConjunct(adt.MakeRootConjunct(nil, expr))
1768 n.Finalize(ctx)
1769 w := makeValue(v.idx, n, v.parent_)
1770 return v.Unify(w)
1771 }
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781 func (v hiddenValue) Template() func(label string) Value {
1782 if v.v == nil {
1783 return nil
1784 }
1785
1786 types := v.v.OptionalTypes()
1787 if types&(adt.HasAdditional|adt.HasPattern) == 0 {
1788 return nil
1789 }
1790
1791 return func(label string) Value {
1792 return v.LookupPath(MakePath(Str(label).Optional()))
1793 }
1794 }
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809 func (v Value) Subsume(w Value, opts ...Option) error {
1810 o := getOptions(opts)
1811 p := subsume.CUE
1812 switch {
1813 case o.final && o.ignoreClosedness:
1814 p = subsume.FinalOpen
1815 case o.final:
1816 p = subsume.Final
1817 case o.ignoreClosedness:
1818 p = subsume.API
1819 }
1820 if !o.raw {
1821 p.Defaults = true
1822 }
1823 ctx := v.ctx()
1824 return p.Value(ctx, v.v, w.v)
1825 }
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837 func (v hiddenValue) Subsumes(w Value) bool {
1838 ctx := v.ctx()
1839 p := subsume.Profile{Defaults: true}
1840 return p.Check(ctx, v.v, w.v)
1841 }
1842
1843 func allowed(ctx *adt.OpContext, parent, n *adt.Vertex) *adt.Bottom {
1844 if !parent.IsClosedList() && !parent.IsClosedStruct() {
1845 return nil
1846 }
1847
1848 for _, a := range n.Arcs {
1849 if !parent.Accept(ctx, a.Label) {
1850 defer ctx.PopArc(ctx.PushArc(parent))
1851 label := a.Label.SelectorString(ctx)
1852 parent.Accept(ctx, a.Label)
1853 return ctx.NewErrf("field not allowed: %s", label)
1854 }
1855 }
1856 return nil
1857 }
1858
1859 func addConjuncts(dst, src *adt.Vertex) {
1860 c := adt.MakeRootConjunct(nil, src)
1861 if src.Closed {
1862 var root adt.CloseInfo
1863 c.CloseInfo = root.SpawnRef(src, src.Closed, nil)
1864 }
1865 dst.AddConjunct(c)
1866 }
1867
1868
1869
1870
1871
1872 func (v Value) Unify(w Value) Value {
1873 if v.v == nil {
1874 return w
1875 }
1876 if w.v == nil || w.v == v.v {
1877 return v
1878 }
1879
1880 n := &adt.Vertex{}
1881 addConjuncts(n, v.v)
1882 addConjuncts(n, w.v)
1883
1884 ctx := newContext(v.idx)
1885 n.Finalize(ctx)
1886
1887 n.Parent = v.v.Parent
1888 n.Label = v.v.Label
1889 n.Closed = v.v.Closed || w.v.Closed
1890
1891 if err := n.Err(ctx); err != nil {
1892 return makeValue(v.idx, n, v.parent_)
1893 }
1894 if err := allowed(ctx, v.v, n); err != nil {
1895 return newErrValue(w, err)
1896 }
1897 if err := allowed(ctx, w.v, n); err != nil {
1898 return newErrValue(v, err)
1899 }
1900
1901 return makeValue(v.idx, n, v.parent_)
1902 }
1903
1904
1905
1906
1907
1908
1909 func (v Value) UnifyAccept(w Value, accept Value) Value {
1910 if v.v == nil {
1911 return w
1912 }
1913 if w.v == nil {
1914 return v
1915 }
1916 if accept.v == nil {
1917 panic("accept must exist")
1918 }
1919
1920 n := &adt.Vertex{}
1921 n.AddConjunct(adt.MakeRootConjunct(nil, v.v))
1922 n.AddConjunct(adt.MakeRootConjunct(nil, w.v))
1923
1924 ctx := newContext(v.idx)
1925 n.Finalize(ctx)
1926
1927 n.Parent = v.v.Parent
1928 n.Label = v.v.Label
1929
1930 if err := n.Err(ctx); err != nil {
1931 return makeValue(v.idx, n, v.parent_)
1932 }
1933 if err := allowed(ctx, accept.v, n); err != nil {
1934 return newErrValue(accept, err)
1935 }
1936
1937 return makeValue(v.idx, n, v.parent_)
1938 }
1939
1940
1941
1942 func (v Value) Equals(other Value) bool {
1943 if v.v == nil || other.v == nil {
1944 return false
1945 }
1946 return adt.Equal(v.ctx(), v.v, other.v, 0)
1947 }
1948
1949 func (v Value) instance() *Instance {
1950 if v.v == nil {
1951 return nil
1952 }
1953 return getImportFromNode(v.idx, v.v)
1954 }
1955
1956
1957
1958
1959
1960
1961
1962 func (v hiddenValue) Reference() (inst *Instance, path []string) {
1963 root, p := v.ReferencePath()
1964 if !root.Exists() {
1965 return nil, nil
1966 }
1967
1968 inst = getImportFromNode(v.idx, root.v)
1969 for _, sel := range p.Selectors() {
1970 switch x := sel.sel.(type) {
1971 case stringSelector:
1972 path = append(path, string(x))
1973 default:
1974 path = append(path, sel.String())
1975 }
1976 }
1977
1978 return inst, path
1979 }
1980
1981
1982
1983
1984 func (v Value) ReferencePath() (root Value, p Path) {
1985
1986 if v.v == nil || len(v.v.Conjuncts) != 1 {
1987 return Value{}, Path{}
1988 }
1989 ctx := v.ctx()
1990 c := v.v.Conjuncts[0]
1991
1992 env, expr := c.EnvExpr()
1993
1994 x, path := reference(v.idx, ctx, env, expr)
1995 if x == nil {
1996 return Value{}, Path{}
1997 }
1998
1999
2000
2001
2002
2003 return makeValue(v.idx, x, nil), Path{path: path}
2004 }
2005
2006 func reference(rt *runtime.Runtime, c *adt.OpContext, env *adt.Environment, r adt.Expr) (inst *adt.Vertex, path []Selector) {
2007 ctx := c
2008 defer ctx.PopState(ctx.PushState(env, r.Source()))
2009
2010 switch x := r.(type) {
2011
2012
2013
2014 case *adt.NodeLink:
2015
2016 inst, path = mkPath(rt, nil, x.Node)
2017
2018 case *adt.FieldReference:
2019 env := ctx.Env(x.UpCount)
2020 inst, path = mkPath(rt, nil, env.Vertex)
2021 path = appendSelector(path, featureToSel(x.Label, rt))
2022
2023 case *adt.LabelReference:
2024 env := ctx.Env(x.UpCount)
2025 return mkPath(rt, nil, env.Vertex)
2026
2027 case *adt.DynamicReference:
2028 env := ctx.Env(x.UpCount)
2029 inst, path = mkPath(rt, nil, env.Vertex)
2030 v, _ := ctx.Evaluate(env, x.Label)
2031 path = appendSelector(path, valueToSel(v))
2032
2033 case *adt.ImportReference:
2034 inst = rt.LoadImport(rt.LabelStr(x.ImportPath))
2035
2036 case *adt.SelectorExpr:
2037 inst, path = reference(rt, c, env, x.X)
2038 path = appendSelector(path, featureToSel(x.Sel, rt))
2039
2040 case *adt.IndexExpr:
2041 inst, path = reference(rt, c, env, x.X)
2042 v, _ := ctx.Evaluate(env, x.Index)
2043 path = appendSelector(path, valueToSel(v))
2044 }
2045 if inst == nil {
2046 return nil, nil
2047 }
2048 return inst, path
2049 }
2050
2051 func mkPath(r *runtime.Runtime, a []Selector, v *adt.Vertex) (root *adt.Vertex, path []Selector) {
2052 if v.Parent == nil {
2053 return v, a
2054 }
2055 root, path = mkPath(r, a, v.Parent)
2056 path = appendSelector(path, featureToSel(v.Label, r))
2057 return root, path
2058 }
2059
2060 type options struct {
2061 concrete bool
2062 raw bool
2063 hasHidden bool
2064 omitHidden bool
2065 omitDefinitions bool
2066 omitOptional bool
2067 omitAttrs bool
2068 inlineImports bool
2069 resolveReferences bool
2070 showErrors bool
2071 final bool
2072 ignoreClosedness bool
2073 docs bool
2074 disallowCycles bool
2075 }
2076
2077
2078 type Option option
2079
2080 type option func(p *options)
2081
2082
2083
2084 func Final() Option {
2085 return func(o *options) {
2086 o.final = true
2087 o.omitDefinitions = true
2088 o.omitOptional = true
2089 o.omitHidden = true
2090 }
2091 }
2092
2093
2094 func Schema() Option {
2095 return func(o *options) {
2096 o.ignoreClosedness = true
2097 }
2098 }
2099
2100
2101
2102
2103
2104 func Concrete(concrete bool) Option {
2105 return func(p *options) {
2106 if concrete {
2107 p.concrete = true
2108 p.final = true
2109 if !p.hasHidden {
2110 p.omitHidden = true
2111 p.omitDefinitions = true
2112 }
2113 }
2114 }
2115 }
2116
2117
2118
2119 func InlineImports(expand bool) Option {
2120 return func(p *options) { p.inlineImports = expand }
2121 }
2122
2123
2124
2125 func DisallowCycles(disallow bool) Option {
2126 return func(p *options) { p.disallowCycles = disallow }
2127 }
2128
2129
2130
2131
2132
2133
2134
2135 func ResolveReferences(resolve bool) Option {
2136 return func(p *options) {
2137 p.resolveReferences = resolve
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148 p.showErrors = true
2149 }
2150 }
2151
2152
2153
2154
2155
2156 func ErrorsAsValues(show bool) Option {
2157 return func(p *options) { p.showErrors = show }
2158 }
2159
2160
2161 func Raw() Option {
2162 return func(p *options) { p.raw = true }
2163 }
2164
2165
2166
2167 func All() Option {
2168 return func(p *options) {
2169 p.omitAttrs = false
2170 p.omitHidden = false
2171 p.omitDefinitions = false
2172 p.omitOptional = false
2173 }
2174 }
2175
2176
2177 func Docs(include bool) Option {
2178 return func(p *options) { p.docs = true }
2179 }
2180
2181
2182
2183
2184
2185 func Definitions(include bool) Option {
2186 return func(p *options) {
2187 p.hasHidden = true
2188 p.omitDefinitions = !include
2189 }
2190 }
2191
2192
2193 func Hidden(include bool) Option {
2194 return func(p *options) {
2195 p.hasHidden = true
2196 p.omitHidden = !include
2197 p.omitDefinitions = !include
2198 }
2199 }
2200
2201
2202 func Optional(include bool) Option {
2203 return func(p *options) { p.omitOptional = !include }
2204 }
2205
2206
2207 func Attributes(include bool) Option {
2208 return func(p *options) { p.omitAttrs = !include }
2209 }
2210
2211 func getOptions(opts []Option) (o options) {
2212 o.updateOptions(opts)
2213 return
2214 }
2215
2216 func (o *options) updateOptions(opts []Option) {
2217 for _, fn := range opts {
2218 fn(o)
2219 }
2220 }
2221
2222
2223
2224
2225
2226
2227
2228
2229 func (v Value) Validate(opts ...Option) error {
2230 o := options{}
2231 o.updateOptions(opts)
2232
2233 cfg := &validate.Config{
2234 Concrete: o.concrete,
2235 Final: o.final,
2236 DisallowCycles: o.disallowCycles,
2237 AllErrors: true,
2238 }
2239
2240 b := validate.Validate(v.ctx(), v.v, cfg)
2241 if b != nil {
2242 return v.toErr(b)
2243 }
2244 return nil
2245 }
2246
2247
2248
2249
2250
2251 func (v Value) Walk(before func(Value) bool, after func(Value)) {
2252 ctx := v.ctx()
2253 switch v.Kind() {
2254 case StructKind:
2255 if before != nil && !before(v) {
2256 return
2257 }
2258 obj, _ := v.structValOpts(ctx, options{
2259 omitHidden: true,
2260 omitDefinitions: true,
2261 })
2262 for i := 0; i < obj.Len(); i++ {
2263 _, v := obj.At(i)
2264
2265
2266 if v.v.ArcType != adt.ArcMember {
2267 continue
2268 }
2269 v.Walk(before, after)
2270 }
2271 case ListKind:
2272 if before != nil && !before(v) {
2273 return
2274 }
2275 list, _ := v.List()
2276 for list.Next() {
2277 list.Value().Walk(before, after)
2278 }
2279 default:
2280 if before != nil {
2281 before(v)
2282 }
2283 }
2284 if after != nil {
2285 after(v)
2286 }
2287 }
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307 func (v Value) Expr() (Op, []Value) {
2308
2309 if v.v == nil {
2310 return NoOp, nil
2311 }
2312
2313 var expr adt.Expr
2314 var env *adt.Environment
2315
2316 if v.v.IsData() {
2317 expr = v.v.Value()
2318
2319 } else {
2320 switch len(v.v.Conjuncts) {
2321 case 0:
2322 if v.v.BaseValue == nil {
2323 return NoOp, []Value{makeValue(v.idx, v.v, v.parent_)}
2324 }
2325 expr = v.v.Value()
2326
2327 case 1:
2328
2329 c := v.v.Conjuncts[0]
2330 env, expr = c.EnvExpr()
2331 if w, ok := expr.(*adt.Vertex); ok {
2332 return Value{v.idx, w, v.parent_}.Expr()
2333 }
2334
2335 default:
2336 a := []Value{}
2337 ctx := v.ctx()
2338 for _, c := range v.v.Conjuncts {
2339
2340
2341 n := &adt.Vertex{
2342 Parent: v.v.Parent,
2343 Label: v.v.Label,
2344 }
2345 n.AddConjunct(c)
2346 n.Finalize(ctx)
2347 a = append(a, makeValue(v.idx, n, v.parent_))
2348 }
2349 return adt.AndOp, a
2350 }
2351 }
2352
2353
2354 a := []Value{}
2355 op := NoOp
2356 switch x := expr.(type) {
2357 case *adt.BinaryExpr:
2358 a = append(a, remakeValue(v, env, x.X))
2359 a = append(a, remakeValue(v, env, x.Y))
2360 op = x.Op
2361 case *adt.UnaryExpr:
2362 a = append(a, remakeValue(v, env, x.X))
2363 op = x.Op
2364 case *adt.BoundExpr:
2365 a = append(a, remakeValue(v, env, x.Expr))
2366 op = x.Op
2367 case *adt.BoundValue:
2368 a = append(a, remakeValue(v, env, x.Value))
2369 op = x.Op
2370 case *adt.Conjunction:
2371
2372 for _, conjunct := range x.Values {
2373 a = append(a, remakeValue(v, env, conjunct))
2374 }
2375 op = AndOp
2376 case *adt.Disjunction:
2377 count := 0
2378 outer:
2379 for i, disjunct := range x.Values {
2380 if i < x.NumDefaults {
2381 for _, n := range x.Values[x.NumDefaults:] {
2382 if subsume.Simplify.Value(v.ctx(), n, disjunct) == nil {
2383 continue outer
2384 }
2385 }
2386 }
2387 count++
2388 a = append(a, remakeValue(v, env, disjunct))
2389 }
2390 if count > 1 {
2391 op = OrOp
2392 }
2393
2394 case *adt.DisjunctionExpr:
2395
2396 count := 0
2397 outerExpr:
2398 for _, disjunct := range x.Values {
2399 if disjunct.Default {
2400 for _, n := range x.Values {
2401 a := adt.Vertex{
2402 Label: v.v.Label,
2403 }
2404 b := a
2405 a.AddConjunct(adt.MakeRootConjunct(env, n.Val))
2406 b.AddConjunct(adt.MakeRootConjunct(env, disjunct.Val))
2407
2408 ctx := eval.NewContext(v.idx, nil)
2409 a.Finalize(ctx)
2410 b.Finalize(ctx)
2411 if allowed(ctx, v.v, &b) != nil {
2412
2413 continue outerExpr
2414 }
2415 if allowed(ctx, v.v, &a) != nil {
2416
2417 continue
2418 }
2419 a.Parent = v.v.Parent
2420 if !n.Default && subsume.Simplify.Value(ctx, &a, &b) == nil {
2421 continue outerExpr
2422 }
2423 }
2424 }
2425 count++
2426 a = append(a, remakeValue(v, env, disjunct.Val))
2427 }
2428 if count > 1 {
2429 op = adt.OrOp
2430 }
2431
2432 case *adt.Interpolation:
2433 for _, p := range x.Parts {
2434 a = append(a, remakeValue(v, env, p))
2435 }
2436 op = InterpolationOp
2437
2438 case *adt.FieldReference:
2439
2440 ctx := v.ctx()
2441 f := ctx.PushState(env, x.Src)
2442 env := ctx.Env(x.UpCount)
2443 a = append(a, remakeValue(v, nil, &adt.NodeLink{Node: env.Vertex}))
2444 a = append(a, remakeValue(v, nil, ctx.NewString(x.Label.SelectorString(ctx))))
2445 _ = ctx.PopState(f)
2446 op = SelectorOp
2447
2448 case *adt.SelectorExpr:
2449 a = append(a, remakeValue(v, env, x.X))
2450
2451 a = append(a, remakeValue(v, env, &adt.String{
2452 Str: x.Sel.SelectorString(v.idx),
2453 }))
2454 op = SelectorOp
2455
2456 case *adt.IndexExpr:
2457 a = append(a, remakeValue(v, env, x.X))
2458 a = append(a, remakeValue(v, env, x.Index))
2459 op = IndexOp
2460 case *adt.SliceExpr:
2461 a = append(a, remakeValue(v, env, x.X))
2462 a = append(a, remakeValue(v, env, x.Lo))
2463 a = append(a, remakeValue(v, env, x.Hi))
2464 op = SliceOp
2465 case *adt.CallExpr:
2466
2467 if fn, ok := x.Fun.(*adt.Builtin); ok && len(x.Args) == 1 &&
2468 (fn.Name == "or" || fn.Name == "and") {
2469
2470 iter, _ := remakeValue(v, env, x.Args[0]).List()
2471 for iter.Next() {
2472 a = append(a, iter.Value())
2473 }
2474
2475 op = OrOp
2476 if fn.Name == "and" {
2477 op = AndOp
2478 }
2479
2480 if len(a) == 0 {
2481
2482 switch op {
2483 case AndOp:
2484 a = append(a, remakeValue(v, env, &adt.Top{}))
2485 case OrOp:
2486 a = append(a, remakeValue(v, env, &adt.Bottom{
2487 Code: adt.IncompleteError,
2488 Err: errors.Newf(x.Src.Fun.Pos(), "empty list in call to or"),
2489 }))
2490 }
2491 op = NoOp
2492 }
2493 break
2494 }
2495 a = append(a, remakeValue(v, env, x.Fun))
2496 for _, arg := range x.Args {
2497 a = append(a, remakeValue(v, env, arg))
2498 }
2499 op = CallOp
2500 case *adt.BuiltinValidator:
2501 a = append(a, remakeValue(v, env, x.Builtin))
2502 for _, arg := range x.Args {
2503 a = append(a, remakeValue(v, env, arg))
2504 }
2505 op = CallOp
2506
2507 case *adt.StructLit:
2508 hasEmbed := false
2509 fields := []adt.Decl{}
2510 for _, d := range x.Decls {
2511 switch d.(type) {
2512 default:
2513 fields = append(fields, d)
2514 case adt.Value:
2515 fields = append(fields, d)
2516 case adt.Expr:
2517 hasEmbed = true
2518 }
2519 }
2520
2521 if !hasEmbed {
2522 a = append(a, v)
2523 break
2524 }
2525
2526 ctx := v.ctx()
2527
2528 n := v.v
2529
2530 if len(fields) > 0 {
2531 n = &adt.Vertex{
2532 Parent: v.v.Parent,
2533 Label: v.v.Label,
2534 }
2535
2536 s := &adt.StructLit{}
2537 if k := v.v.Kind(); k != adt.StructKind && k != BottomKind {
2538
2539
2540
2541
2542 s.Decls = append(s.Decls, &adt.BasicType{K: k})
2543 }
2544 s.Decls = append(s.Decls, fields...)
2545 c := adt.MakeRootConjunct(env, s)
2546 n.AddConjunct(c)
2547 n.Finalize(ctx)
2548 n.Parent = v.v.Parent
2549 }
2550
2551
2552 envEmbed := &adt.Environment{
2553 Up: env,
2554 Vertex: n,
2555 }
2556
2557 for _, d := range x.Decls {
2558 switch x := d.(type) {
2559 case adt.Value:
2560 case adt.Expr:
2561
2562 n := &adt.Vertex{Label: v.v.Label}
2563 c := adt.MakeRootConjunct(envEmbed, x)
2564 n.AddConjunct(c)
2565 n.Finalize(ctx)
2566 n.Parent = v.v.Parent
2567 a = append(a, makeValue(v.idx, n, v.parent_))
2568 }
2569 }
2570
2571
2572 if len(fields) > 0 {
2573 a = append(a, makeValue(v.idx, n, v.parent_))
2574 }
2575
2576 if len(a) == 1 {
2577 return a[0].Expr()
2578 }
2579 op = adt.AndOp
2580
2581 default:
2582 a = append(a, v)
2583 }
2584 return op, a
2585 }
2586
View as plain text