...

Source file src/cuelang.org/go/cue/types.go

Documentation: cuelang.org/go/cue

     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  
    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  // Kind determines the underlying type of a Value.
    46  type Kind = adt.Kind
    47  
    48  const (
    49  	// BottomKind represents the bottom value.
    50  	BottomKind Kind = adt.BottomKind
    51  
    52  	// NullKind indicates a null value.
    53  	NullKind Kind = adt.NullKind
    54  
    55  	// BoolKind indicates a boolean value.
    56  	BoolKind Kind = adt.BoolKind
    57  
    58  	// IntKind represents an integral number.
    59  	IntKind Kind = adt.IntKind
    60  
    61  	// FloatKind represents a decimal float point number that cannot be
    62  	// converted to an integer. The underlying number may still be integral,
    63  	// but resulting from an operation that enforces the float type.
    64  	FloatKind Kind = adt.FloatKind
    65  
    66  	// StringKind indicates any kind of string.
    67  	StringKind Kind = adt.StringKind
    68  
    69  	// BytesKind is a blob of data.
    70  	BytesKind Kind = adt.BytesKind
    71  
    72  	// StructKind is a kev-value map.
    73  	StructKind Kind = adt.StructKind
    74  
    75  	// ListKind indicates a list of values.
    76  	ListKind Kind = adt.ListKind
    77  
    78  	// _numberKind is used as a implementation detail inside
    79  	// Kind.String to indicate NumberKind.
    80  
    81  	// NumberKind represents any kind of number.
    82  	NumberKind Kind = IntKind | FloatKind
    83  
    84  	// TopKind represents the top value.
    85  	TopKind Kind = adt.TopKind
    86  )
    87  
    88  // An structValue represents a JSON object.
    89  //
    90  // TODO: remove
    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  // Len reports the number of fields in this struct.
   101  func (o *hiddenStructValue) Len() int {
   102  	if o.obj == nil {
   103  		return 0
   104  	}
   105  	return len(o.arcs)
   106  }
   107  
   108  // At reports the key and value of the ith field, i < o.Len().
   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  // Lookup reports the field for the given key. The returned Value is invalid
   119  // if it does not exist.
   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  		// TODO: more specifically we should test whether the values that
   133  		// are addressable from the root of the configuration can support the
   134  		// looked up value. This will avoid false positives such as when
   135  		// an open literal struct is passed to a builtin.
   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  // MarshalJSON returns a valid JSON encoding or reports an error if any of the
   145  // fields is invalid.
   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  // An Iterator iterates over values.
   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  // Next advances the iterator to the next value and reports whether there was
   227  // any. It must be called before the first call to Value or Key.
   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  // Value returns the current value in the list. It will panic if Next advanced
   244  // past the last entry.
   245  func (i *Iterator) Value() Value {
   246  	return i.cur
   247  }
   248  
   249  // Selector reports the field label of this iteration.
   250  func (i *Iterator) Selector() Selector {
   251  	sel := featureToSel(i.f, i.idx)
   252  	// Only call wrapConstraint if there is any constraint type to wrap with.
   253  	if ctype := fromArcType(i.arcType); ctype != 0 {
   254  		sel = wrapConstraint(sel, ctype)
   255  	}
   256  	return sel
   257  }
   258  
   259  // Label reports the label of the value if i iterates over struct fields and ""
   260  // otherwise.
   261  //
   262  // Slated to be deprecated: use i.Selector().String(). Note that this will give
   263  // more accurate string representations.
   264  func (i *hiddenIterator) Label() string {
   265  	if i.f == 0 {
   266  		return ""
   267  	}
   268  	return i.idx.LabelStr(i.f)
   269  }
   270  
   271  // IsHidden reports if a field is hidden from the data model.
   272  //
   273  // Deprecated: use i.Selector().PkgPath() != ""
   274  func (i *hiddenIterator) IsHidden() bool {
   275  	return i.f.IsHidden()
   276  }
   277  
   278  // IsOptional reports if a field is optional.
   279  func (i *Iterator) IsOptional() bool {
   280  	return i.arcType == adt.ArcOptional
   281  }
   282  
   283  // FieldType reports the type of the field.
   284  func (i *Iterator) FieldType() SelectorType {
   285  	return featureToSelType(i.f, i.arcType)
   286  }
   287  
   288  // IsDefinition reports if a field is a definition.
   289  //
   290  // Deprecated: use i.Selector().IsDefinition()
   291  func (i *hiddenIterator) IsDefinition() bool {
   292  	return i.f.IsDef()
   293  }
   294  
   295  // marshalJSON iterates over the list and generates JSON output. HasNext
   296  // will return false after this operation.
   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  // MantExp breaks x into its mantissa and exponent components and returns the
   327  // exponent. If a non-nil mant argument is provided its value is set to the
   328  // mantissa of x. The components satisfy x == mant × 10**exp. It returns an
   329  // error if v is not a number.
   330  //
   331  // The components are not normalized. For instance, 2.00 is represented mant ==
   332  // 200 and exp == -2. Calling MantExp with a nil argument is an efficient way to
   333  // get the exponent of the receiver.
   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  // Decimal is for internal use only. The Decimal type that is returned is
   352  // subject to change.
   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  // AppendInt appends the string representation of x in the given base to buf and
   362  // returns the extended buffer, or an error if the underlying number was not
   363  // an integer.
   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  // AppendFloat appends to buf the string form of the floating-point number x.
   373  // It returns an error if v is not a number.
   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  	// ErrBelow indicates that a value was rounded down in a conversion.
   399  	ErrBelow = errors.New("value was rounded down")
   400  
   401  	// ErrAbove indicates that a value was rounded up in a conversion.
   402  	ErrAbove = errors.New("value was rounded up")
   403  
   404  	// ErrInfinite indicates that a value is infinite.
   405  	ErrInfinite = errors.New("infinite")
   406  )
   407  
   408  // Int converts the underlying integral number to an big.Int. It reports an
   409  // error if the underlying value is not an integer type. If a non-nil *Int
   410  // argument z is provided, Int stores the result in z instead of allocating a
   411  // new Int.
   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  // Int64 converts the underlying integral number to int64. It reports an
   431  // error if the underlying value is not an integer type or cannot be represented
   432  // as an int64. The result is (math.MinInt64, ErrAbove) for x < math.MinInt64,
   433  // and (math.MaxInt64, ErrBelow) for x > math.MaxInt64.
   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  // Uint64 converts the underlying integral number to uint64. It reports an
   453  // error if the underlying value is not an integer type or cannot be represented
   454  // as a uint64. The result is (0, ErrAbove) for x < 0, and
   455  // (math.MaxUint64, ErrBelow) for x > math.MaxUint64.
   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  // trimZeros trims 0's for better JSON representations.
   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  		// math.SmallestNonzeroFloat64: 1 / 2**(1023 - 1 + 52)
   498  		smallest = "4.940656458412465441765687928682213723651e-324"
   499  		// math.MaxFloat64: 2**1023 * (2**53 - 1) / 2**52
   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  // Float64 returns the float64 value nearest to x. It reports an error if v is
   524  // not a number. If x is too small to be represented by a float64 (|x| <
   525  // math.SmallestNonzeroFloat64), the result is (0, ErrBelow) or (-0, ErrAbove),
   526  // respectively, depending on the sign of x. If x is too large to be represented
   527  // by a float64 (|x| > math.MaxFloat64), the result is (+Inf, ErrAbove) or
   528  // (-Inf, ErrBelow), depending on the sign of x.
   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  // Value holds any value, which may be a Boolean, Error, List, Null, Number,
   557  // Struct, or String.
   558  type Value struct {
   559  	idx *runtime.Runtime
   560  	v   *adt.Vertex
   561  	// Parent keeps track of the parent if the value corresponding to v.Parent
   562  	// differs, recursively.
   563  	parent_ *parent
   564  }
   565  
   566  // parent is a distinct type from Value to ensure more type safety: Value
   567  // is typically used by value, so taking a pointer to it has a high risk
   568  // or globbering the contents.
   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  // Core is for internal use only.
   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  		// This is indicative of an zero Value. In some cases this is called
   618  		// with an error value.
   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  // Dereference reports the value v refers to if v is a reference or v itself
   641  // otherwise.
   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  	// TODO: consider supporting unwrapping of structs or comprehensions around
   651  	// a single embedded reference.
   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  	// NOTE: due to structure sharing, the path of the referred node may end
   666  	// up different from the one explicitly pointed to. The value will be the
   667  	// same, but the scope may differ.
   668  	// TODO(structureshare): see if we can construct the original path. This
   669  	// only has to be done if structures are being shared.
   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  // makeChildValue makes a new value, of which p is the parent, and links the
   682  // parent pointer to p if necessary.
   683  func makeChildValue(p Value, arc *adt.Vertex) Value {
   684  	return makeValue(p.idx, arc, linkParent(p.parent_, p.v, arc))
   685  }
   686  
   687  // linkParent creates the parent struct for an arc, if necessary.
   688  //
   689  // The parent struct is necessary if the parent struct also has a parent struct,
   690  // or if arc is (structurally) shared and does not have node as a parent.
   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  	// TODO: right now this is necessary because disjunctions do not have
   700  	// populated conjuncts.
   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  // Eval resolves the references of a value and returns the result.
   722  // This method is not necessary to obtain concrete values.
   723  func (v Value) Eval() Value {
   724  	if v.v == nil {
   725  		return v
   726  	}
   727  	x := v.v
   728  	// x = eval.FinalizeValue(v.idx.Runtime, v.v)
   729  	// x.Finalize(v.ctx())
   730  	x = x.ToDataSingle()
   731  	return makeValue(v.idx, x, v.parent_)
   732  	// return remakeValue(v, nil, ctx.value(x))
   733  }
   734  
   735  // Default reports the default value and whether it existed. It returns the
   736  // normal value if there is no default.
   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  	// d, ok := v.v.Value.(*adt.Disjunction)
   749  	// if !ok {
   750  	// 	return v, false
   751  	// }
   752  
   753  	// var w *adt.Vertex
   754  
   755  	// switch d.NumDefaults {
   756  	// case 0:
   757  	// 	return v, false
   758  
   759  	// case 1:
   760  	// 	w = d.Values[0]
   761  
   762  	// default:
   763  	// 	x := *v.v
   764  	// 	x.Value = &adt.Disjunction{
   765  	// 		Src:         d.Src,
   766  	// 		Values:      d.Values[:d.NumDefaults],
   767  	// 		NumDefaults: 0,
   768  	// 	}
   769  	// 	w = &x
   770  	// }
   771  
   772  	// w.Conjuncts = nil
   773  	// for _, c := range v.v.Conjuncts {
   774  	// 	// TODO: preserve field information.
   775  	// 	expr, _ := stripNonDefaults(c.Expr())
   776  	// 	w.AddConjunct(adt.MakeConjunct(c.Env, expr))
   777  	// }
   778  
   779  	// return makeValue(v.idx, w), true
   780  
   781  	// if !stripped {
   782  	// 	return v, false
   783  	// }
   784  
   785  	// n := *v.v
   786  	// n.Conjuncts = conjuncts
   787  	// return Value{v.idx, &n}, true
   788  
   789  	// isDefault := false
   790  	// for _, c := range v.v.Conjuncts {
   791  	// 	if hasDisjunction(c.Expr()) {
   792  	// 		isDefault = true
   793  	// 		break
   794  	// 	}
   795  	// }
   796  
   797  	// if !isDefault {
   798  	// 	return v, false
   799  	// }
   800  
   801  	// TODO: record expanded disjunctions in output.
   802  	// - Rename Disjunction to DisjunctionExpr
   803  	// - Introduce Disjuncts with Values.
   804  	// - In Expr introduce Star
   805  	// - Don't pick default by default?
   806  
   807  	// Evaluate the value.
   808  	// 	x := eval.FinalizeValue(v.idx.Runtime, v.v)
   809  	// 	if b, _ := x.Value.(*adt.Bottom); b != nil { // && b.IsIncomplete() {
   810  	// 		return v, false
   811  	// 	}
   812  	// 	// Finalize and return here.
   813  	// 	return Value{v.idx, x}, isDefault
   814  }
   815  
   816  // TODO: this should go: record preexpanded disjunctions in Vertex.
   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  // TODO: this should go: record preexpanded disjunctions in Vertex.
   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  // Label reports he label used to obtain this value from the enclosing struct.
   877  //
   878  // TODO: get rid of this somehow. Probably by including a FieldInfo struct
   879  // or the like.
   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  // Kind returns the kind of value. It returns BottomKind for atomic values that
   888  // are not concrete. For instance, it will return BottomKind for the bounds
   889  // >=0.
   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  	// TODO: perhaps we should not consider open lists as "incomplete".
   899  	if v.IncompleteKind() == adt.ListKind && !v.v.IsClosedList() {
   900  		return BottomKind
   901  	}
   902  	return c.Kind()
   903  }
   904  
   905  // IncompleteKind returns a mask of all kinds that this value may be.
   906  func (v Value) IncompleteKind() Kind {
   907  	if v.v == nil {
   908  		return BottomKind
   909  	}
   910  	return v.v.Kind()
   911  }
   912  
   913  // MarshalJSON marshalls this value into valid JSON.
   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  	// TODO: implement marshalles in value.
   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  // Syntax converts the possibly partially evaluated value into syntax. This
   968  // can use used to print the value with package format.
   969  func (v Value) Syntax(opts ...Option) ast.Node {
   970  	// TODO: the default should ideally be simplified representation that
   971  	// exactly represents the value. The latter can currently only be
   972  	// ensured with Raw().
   973  	if v.v == nil {
   974  		return nil
   975  	}
   976  	var o options = getOptions(opts)
   977  	// var inst *Instance
   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  	// var expr ast.Expr
  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  // Doc returns all documentation comments associated with the field from which
  1054  // the current value originates.
  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  // Split returns a list of values from which v originated such that
  1063  // the unification of all these values equals v and for all returned values.
  1064  // It will also split unchecked unifications (embeddings), so unifying the
  1065  // split values may fail if actually unified.
  1066  // Source returns a non-nil value.
  1067  //
  1068  // Deprecated: use [Value.Expr].
  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  // Source returns the original node for this value. The return value may not
  1082  // be an [ast.Expr]. For instance, a struct kind may be represented by a
  1083  // struct literal, a field comprehension, or a file. It returns nil for
  1084  // computed nodes. Use [Value.Expr] to get all source values that apply to a field.
  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  // If v exactly represents a package, BuildInstance returns
  1096  // the build instance corresponding to the value; otherwise it returns nil.
  1097  //
  1098  // The value returned by Value.ReferencePath will commonly represent
  1099  // a package.
  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  // Err returns the error represented by v or nil v is not an error.
  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  // Pos returns position information.
  1116  //
  1117  // Use v.Expr to get positions for all conjuncts and disjuncts.
  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  	// Pick the most-concrete field.
  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  		// Prefer struct conjuncts with actual fields.
  1138  		if s, ok := x.(*adt.StructLit); ok && len(s.Fields) > 0 {
  1139  			break
  1140  		}
  1141  	}
  1142  	return p
  1143  }
  1144  
  1145  // TODO: IsFinal: this value can never be changed.
  1146  
  1147  // IsClosed reports whether a list of struct is closed. It reports false when
  1148  // the value is not a list or struct.
  1149  //
  1150  // Deprecated: use Allows(AnyString) and Allows(AnyIndex) or Kind/IncompleteKind.
  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  // Allows reports whether a field with the given selector could be added to v.
  1165  //
  1166  // Allows does not take into account validators like list.MaxItems(4). This may
  1167  // change in the future.
  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  // IsConcrete reports whether the current value is a concrete scalar value
  1175  // (not relying on default values), a terminal error, a list, or a struct.
  1176  // It does not verify that values of lists or structs are concrete themselves.
  1177  // To check whether there is a concrete default, use this method on [Value.Default].
  1178  func (v Value) IsConcrete() bool {
  1179  	if v.v == nil {
  1180  		return false // any is neither concrete, not a list or struct.
  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  // // Deprecated: IsIncomplete
  1195  // //
  1196  // // It indicates that the value cannot be fully evaluated due to
  1197  // // insufficient information.
  1198  // func (v Value) IsIncomplete() bool {
  1199  // 	panic("deprecated")
  1200  // }
  1201  
  1202  // Exists reports whether this value existed in the configuration.
  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  	// TODO: use checkKind
  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  // Len returns the number of items of the underlying value.
  1242  // For lists it reports the capacity of the list. For structs it indicates the
  1243  // number of fields, for bytes the number of bytes.
  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  				// Note: this HAS to be a Conjunction value and cannot be
  1255  				// an adt.BinaryExpr, as the expressions would be considered
  1256  				// to be self-contained and unresolvable when evaluated
  1257  				// (can never become concrete).
  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  // Elem returns the value of undefined element types of lists and structs.
  1277  //
  1278  // Deprecated: use LookupPath in combination with "AnyString" or "AnyIndex".
  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  // List creates an iterator over the values of a list or reports an error if
  1289  // v is not a list.
  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  // Null reports an error if v is not null.
  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  // // IsNull reports whether v is null.
  1315  // func (v Value) IsNull() bool {
  1316  // 	return v.Null() == nil
  1317  // }
  1318  
  1319  // Bool returns the bool value of v or false and an error if v is not a boolean.
  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  // String returns the string value if v is a string or an error otherwise.
  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  // Bytes returns a byte slice if v represents a list of bytes or an error
  1340  // otherwise.
  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  // Reader returns a new Reader if v is a string or bytes type and an error
  1354  // otherwise.
  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  // TODO: distinguish between optional, hidden, etc. Probably the best approach
  1368  // is to mark options in context and have a single function for creating
  1369  // a structVal.
  1370  
  1371  // structVal returns an structVal or an error if v is not a struct.
  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  // structVal returns an structVal or an error if v is not a struct.
  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  	// Allow scalar values if hidden or definition fields are requested.
  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  	// features are topologically sorted.
  1399  	// TODO(sort): make sort order part of the evaluator and eliminate this.
  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  			// We report an error for required fields if the configuration is
  1425  			// final or concrete. We also do so if omitOptional is true, as
  1426  			// it avoids hiding errors in required fields.
  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  // Struct returns the underlying struct of a value or an error if the value
  1443  // is not a struct.
  1444  //
  1445  // Deprecated: use Fields.
  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  // Struct represents a CUE struct value.
  1466  type Struct struct {
  1467  	structValue
  1468  }
  1469  
  1470  type hiddenStruct = Struct
  1471  
  1472  // FieldInfo contains information about a struct field.
  1473  //
  1474  // Deprecated: only used by deprecated functions.
  1475  type FieldInfo struct {
  1476  	Selector string
  1477  	Name     string // Deprecated: use Selector
  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  // field reports information about the ith field, i < o.Len().
  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  // FieldByName looks up a field for the given name. If isIdent is true, it will
  1506  // look up a definition or hidden field (starting with `_` or `_#`). Otherwise
  1507  // it interprets name as an arbitrary string for a regular field.
  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  // Fields creates an iterator over the Struct's fields.
  1519  func (s *hiddenStruct) Fields(opts ...Option) *Iterator {
  1520  	iter, _ := s.v.Fields(opts...)
  1521  	return iter
  1522  }
  1523  
  1524  // Fields creates an iterator over v's fields if v is a struct or an error
  1525  // otherwise.
  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  // Lookup reports the value at a path starting from v. The empty path returns v
  1539  // itself.
  1540  //
  1541  // [Value.Exists] can be used to verify if the returned value existed.
  1542  // Lookup cannot be used to look up hidden or optional fields or definitions.
  1543  //
  1544  // Deprecated: use [Value.LookupPath]. At some point before v1.0.0, this method will
  1545  // be removed to be reused eventually for looking up a selector.
  1546  func (v hiddenValue) Lookup(path ...string) Value {
  1547  	ctx := v.ctx()
  1548  	for _, k := range path {
  1549  		// TODO(eval) TODO(error): always search in full data and change error
  1550  		// message if a field is found but is of the incorrect type.
  1551  		obj, err := v.structValData(ctx)
  1552  		if err != nil {
  1553  			// TODO: return a Value at the same location and a new error?
  1554  			return newErrValue(v, err)
  1555  		}
  1556  		v = obj.Lookup(k)
  1557  	}
  1558  	return v
  1559  }
  1560  
  1561  // Path returns the path to this value from the root of an Instance.
  1562  //
  1563  // This is currently only defined for values that have a fixed path within
  1564  // a configuration, and thus not those that are derived from Elem, Template,
  1565  // or programmatically generated values such as those returned by Unify.
  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  // Path computes the sequence of Features leading from the root to of the
  1574  // instance to this Vertex.
  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  		// A Label may be 0 for programmatically inserted nodes.
  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  // LookupDef is equal to LookupPath(MakePath(Def(name))).
  1613  //
  1614  // Deprecated: use LookupPath.
  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  // FieldByName looks up a field for the given name. If isIdent is true, it will
  1622  // look up a definition or hidden field (starting with `_` or `_#`). Otherwise
  1623  // it interprets name as an arbitrary string for a regular field.
  1624  //
  1625  // Deprecated: use LookupPath.
  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  // LookupField reports information about a field of v.
  1635  //
  1636  // Deprecated: use LookupPath
  1637  func (v hiddenValue) LookupField(name string) (FieldInfo, error) {
  1638  	s, err := v.Struct()
  1639  	if err != nil {
  1640  		// TODO: return a Value at the same location and a new error?
  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  // TODO: expose this API?
  1654  //
  1655  // // EvalExpr evaluates an expression within the scope of v, which must be
  1656  // // a struct.
  1657  // //
  1658  // // Expressions may refer to builtin packages if they can be uniquely identified.
  1659  // func (v Value) EvalExpr(expr ast.Expr) Value {
  1660  // 	ctx := v.ctx()
  1661  // 	result := evalExpr(ctx, v.eval(ctx), expr)
  1662  // 	return newValueRoot(ctx, result)
  1663  // }
  1664  
  1665  // Fill creates a new value by unifying v with the value of x at the given path.
  1666  //
  1667  // Values may be any Go value that can be converted to CUE, an ast.Expr or
  1668  // a Value. In the latter case, it will panic if the Value is not from the same
  1669  // Runtime.
  1670  //
  1671  // Any reference in v referring to the value at the given path will resolve
  1672  // to x in the newly created value. The resulting value is not validated.
  1673  //
  1674  // Deprecated: use FillPath.
  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  // FillPath creates a new value by unifying v with the value of x at the given
  1687  // path.
  1688  //
  1689  // If x is an cue/ast.Expr, it will be evaluated within the context of the
  1690  // given path: identifiers that are not resolved within the expression are
  1691  // resolved as if they were defined at the path position.
  1692  //
  1693  // If x is a Value, it will be used as is. It panics if x is not created
  1694  // from the same Runtime as v.
  1695  //
  1696  // Otherwise, the given Go value will be converted to CUE using the same rules
  1697  // as Context.Encode.
  1698  //
  1699  // Any reference in v referring to the value at the given path will resolve to x
  1700  // in the newly created value. The resulting value is not validated.
  1701  func (v Value) FillPath(p Path, x interface{}) Value {
  1702  	if v.v == nil {
  1703  		// TODO: panic here?
  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  		// TODO: inject import path of current package?
  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  			// TODO(perf): make this a constant thing. This will be possible with the query extension.
  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  // Template returns a function that represents the template definition for a
  1774  // struct in a configuration file. It returns nil if v is not a struct kind or
  1775  // if there is no template associated with the struct.
  1776  //
  1777  // The returned function returns the value that would be unified with field
  1778  // given its name.
  1779  //
  1780  // Deprecated: use LookupPath in combination with using optional selectors.
  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  // Subsume reports nil when w is an instance of v or an error otherwise.
  1797  //
  1798  // Without options, the entire value is considered for assumption, which means
  1799  // Subsume tests whether  v is a backwards compatible (newer) API version of w.
  1800  //
  1801  // Use the [Final] option to check subsumption if a w is known to be final, and
  1802  // should assumed to be closed.
  1803  //
  1804  // Use the [Raw] option to do a low-level subsumption, taking defaults into
  1805  // account.
  1806  //
  1807  // Value v and w must be obtained from the same build. TODO: remove this
  1808  // requirement.
  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  // Deprecated: use [Value.Subsume].
  1828  //
  1829  // Subsumes reports whether w is an instance of v.
  1830  //
  1831  // Without options, Subsumes checks whether v is a backwards compatible schema
  1832  // of w.
  1833  //
  1834  // By default, Subsumes tests whether two values are compatible
  1835  // Value v and w must be obtained from the same build.
  1836  // TODO: remove this requirement.
  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  // Unify reports the greatest lower bound of v and w.
  1869  //
  1870  // Value v and w must be obtained from the same build.
  1871  // TODO: remove this requirement.
  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  // UnifyAccept is as v.Unify(w), but will disregard the closedness rules for
  1905  // v and w, and will, instead, only allow fields that are present in accept.
  1906  //
  1907  // UnifyAccept is used to piecemeal unify individual conjuncts obtained from
  1908  // accept without violating closedness rules.
  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  // Equals reports whether two values are equal, ignoring optional fields.
  1941  // The result is undefined for incomplete values.
  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  // Reference returns the instance and path referred to by this value such that
  1957  // inst.Lookup(path) resolves to the same value, or no path if this value is not
  1958  // a reference. If a reference contains index selection (foo[bar]), it will
  1959  // only return a reference if the index resolves to a concrete value.
  1960  //
  1961  // Deprecated: use [Value.ReferencePath]
  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  // ReferencePath returns the value and path referred to by this value such that
  1982  // value.LookupPath(path) resolves to the same value, or no path if this value
  1983  // is not a reference.
  1984  func (v Value) ReferencePath() (root Value, p Path) {
  1985  	// TODO: don't include references to hidden fields.
  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  	// NOTE: due to structure sharing, the path of the referred node may end
  1999  	// up different from the one explicitly pointed to. The value will be the
  2000  	// same, but the scope may differ.
  2001  	// TODO(structureshare): see if we can construct the original path. This
  2002  	// only has to be done if structures are being shared.
  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  	// TODO: do we need to handle Vertex as well, in case this is hard-wired?
  2012  	// Probably not, as this results from dynamic content.
  2013  
  2014  	case *adt.NodeLink:
  2015  		// TODO: consider getting rid of NodeLink.
  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 // enforce that values are concrete
  2062  	raw               bool // show original values
  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 // used for comparing APIs
  2073  	docs              bool
  2074  	disallowCycles    bool // implied by concrete
  2075  }
  2076  
  2077  // An Option defines modes of evaluation.
  2078  type Option option
  2079  
  2080  type option func(p *options)
  2081  
  2082  // Final indicates a value is final. It implicitly closes all structs and lists
  2083  // in a value and selects defaults.
  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  // Schema specifies the input is a Schema. Used by Subsume.
  2094  func Schema() Option {
  2095  	return func(o *options) {
  2096  		o.ignoreClosedness = true
  2097  	}
  2098  }
  2099  
  2100  // Concrete ensures that all values are concrete.
  2101  //
  2102  // For Validate this means it returns an error if this is not the case.
  2103  // In other cases a non-concrete value will be replaced with an error.
  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  // InlineImports causes references to values within imported packages to be
  2118  // inlined. References to builtin packages are not inlined.
  2119  func InlineImports(expand bool) Option {
  2120  	return func(p *options) { p.inlineImports = expand }
  2121  }
  2122  
  2123  // DisallowCycles forces validation in the presence of cycles, even if
  2124  // non-concrete values are allowed. This is implied by [Concrete].
  2125  func DisallowCycles(disallow bool) Option {
  2126  	return func(p *options) { p.disallowCycles = disallow }
  2127  }
  2128  
  2129  // ResolveReferences forces the evaluation of references when outputting.
  2130  //
  2131  // Deprecated: Syntax will now always attempt to resolve dangling references and
  2132  // make the output self-contained. When [Final] or [Concrete] are used,
  2133  // it will already attempt to resolve all references.
  2134  // See also [InlineImports].
  2135  func ResolveReferences(resolve bool) Option {
  2136  	return func(p *options) {
  2137  		p.resolveReferences = resolve
  2138  
  2139  		// ResolveReferences is implemented as a Value printer, rather than
  2140  		// a definition printer, even though it should be more like the latter.
  2141  		// To reflect this we convert incomplete errors to their original
  2142  		// expression.
  2143  		//
  2144  		// TODO: ShowErrors mostly shows incomplete errors, even though this is
  2145  		// just an approximation. There seems to be some inconsistencies as to
  2146  		// when child errors are marked as such, making the conversion somewhat
  2147  		// inconsistent. This option is conservative, though.
  2148  		p.showErrors = true
  2149  	}
  2150  }
  2151  
  2152  // ErrorsAsValues treats errors as a regular value, including them at the
  2153  // location in the tree where they occur, instead of interpreting them as a
  2154  // configuration-wide failure that is returned instead of root value.
  2155  // Used by Syntax.
  2156  func ErrorsAsValues(show bool) Option {
  2157  	return func(p *options) { p.showErrors = show }
  2158  }
  2159  
  2160  // Raw tells Syntax to generate the value as is without any simplifications.
  2161  func Raw() Option {
  2162  	return func(p *options) { p.raw = true }
  2163  }
  2164  
  2165  // All indicates that all fields and values should be included in processing
  2166  // even if they can be elided or omitted.
  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  // Docs indicates whether docs should be included.
  2177  func Docs(include bool) Option {
  2178  	return func(p *options) { p.docs = true }
  2179  }
  2180  
  2181  // Definitions indicates whether definitions should be included.
  2182  //
  2183  // Definitions may still be included for certain functions if they are referred
  2184  // to by other values.
  2185  func Definitions(include bool) Option {
  2186  	return func(p *options) {
  2187  		p.hasHidden = true
  2188  		p.omitDefinitions = !include
  2189  	}
  2190  }
  2191  
  2192  // Hidden indicates that definitions and hidden fields should be included.
  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  // Optional indicates that optional fields should be included.
  2202  func Optional(include bool) Option {
  2203  	return func(p *options) { p.omitOptional = !include }
  2204  }
  2205  
  2206  // Attributes indicates that attributes should be included.
  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  // Validate reports any errors, recursively. The returned error may represent
  2223  // more than one error, retrievable with errors.Errors, if more than one
  2224  // exists.
  2225  //
  2226  // Note that by default not all errors are reported, unless options like
  2227  // [Concrete] are used. The [Final] option can be used to check for missing
  2228  // required fields.
  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  // Walk descends into all values of v, calling f. If f returns false, Walk
  2248  // will not descent further. It only visits values that are part of the data
  2249  // model, so this excludes definitions and optional, required, and hidden
  2250  // fields.
  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  			// TODO: should we error on required fields, or visit them anyway?
  2265  			// Walk is not designed to error at this moment, though.
  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  // Expr reports the operation of the underlying expression and the values it
  2290  // operates on.
  2291  //
  2292  // For unary expressions, it returns the single value of the expression.
  2293  //
  2294  // For binary expressions it returns first the left and right value, in that
  2295  // order. For associative operations however, (for instance '&' and '|'), it may
  2296  // return more than two values, where the operation is to be applied in
  2297  // sequence.
  2298  //
  2299  // For selector and index expressions it returns the subject and then the index.
  2300  // For selectors, the index is the string value of the identifier.
  2301  //
  2302  // For interpolations it returns a sequence of values to be concatenated, some
  2303  // of which will be literal strings and some unevaluated expressions.
  2304  //
  2305  // A builtin call expression returns the value of the builtin followed by the
  2306  // args of the call.
  2307  func (v Value) Expr() (Op, []Value) {
  2308  	// TODO: return v if this is complete? Yes for now
  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_)} // TODO: v?
  2324  			}
  2325  			expr = v.v.Value()
  2326  
  2327  		case 1:
  2328  			// the default case, processed below.
  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  				// Keep parent here. TODO: do we need remove the requirement
  2340  				// from other conjuncts?
  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  	// TODO: replace appends with []Value{}. For not leave.
  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  		// pre-expanded unification
  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  		// Filter defaults that are subsumed by another value.
  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  						// Everything subsumed bottom
  2413  						continue outerExpr
  2414  					}
  2415  					if allowed(ctx, v.v, &a) != nil {
  2416  						// An error doesn't subsume anything except another error.
  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  		// TODO: allow hard link
  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  		// A string selector is quoted.
  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  		// Interpret "and" and "or" builtin semantically.
  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  				// Mimic semantics of builtin.
  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  				// TODO: we should also add such a declaration for embeddings
  2539  				// of structs with definitions. However, this is currently
  2540  				// also not supported at the CUE level. If we do, it may be
  2541  				// best handled with a special mode of unification.
  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  		// Simulate old embeddings.
  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  				// embedding
  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  		// Could be done earlier, but keep struct with fields at end.
  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