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