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