-
Notifications
You must be signed in to change notification settings - Fork 276
/
types.go
2585 lines (2310 loc) · 66.2 KB
/
types.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2018 The CUE Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cue
import (
"bytes"
"encoding/json"
"fmt"
"io"
"math"
"math/big"
"strings"
"github.com/cockroachdb/apd/v3"
"cuelang.org/go/cue/ast"
"cuelang.org/go/cue/build"
"cuelang.org/go/cue/errors"
"cuelang.org/go/cue/token"
"cuelang.org/go/internal"
"cuelang.org/go/internal/core/adt"
"cuelang.org/go/internal/core/compile"
"cuelang.org/go/internal/core/convert"
"cuelang.org/go/internal/core/eval"
"cuelang.org/go/internal/core/export"
"cuelang.org/go/internal/core/runtime"
"cuelang.org/go/internal/core/subsume"
"cuelang.org/go/internal/core/validate"
internaljson "cuelang.org/go/internal/encoding/json"
"cuelang.org/go/internal/types"
)
// Kind determines the underlying type of a Value.
type Kind = adt.Kind
const (
// BottomKind represents the bottom value.
BottomKind Kind = adt.BottomKind
// NullKind indicates a null value.
NullKind Kind = adt.NullKind
// BoolKind indicates a boolean value.
BoolKind Kind = adt.BoolKind
// IntKind represents an integral number.
IntKind Kind = adt.IntKind
// FloatKind represents a decimal float point number that cannot be
// converted to an integer. The underlying number may still be integral,
// but resulting from an operation that enforces the float type.
FloatKind Kind = adt.FloatKind
// StringKind indicates any kind of string.
StringKind Kind = adt.StringKind
// BytesKind is a blob of data.
BytesKind Kind = adt.BytesKind
// StructKind is a kev-value map.
StructKind Kind = adt.StructKind
// ListKind indicates a list of values.
ListKind Kind = adt.ListKind
// _numberKind is used as a implementation detail inside
// Kind.String to indicate NumberKind.
// NumberKind represents any kind of number.
NumberKind Kind = IntKind | FloatKind
// TopKind represents the top value.
TopKind Kind = adt.TopKind
)
// An structValue represents a JSON object.
//
// TODO: remove
type structValue struct {
ctx *adt.OpContext
v Value
obj *adt.Vertex
arcs []*adt.Vertex
}
type hiddenStructValue = structValue
// Len reports the number of fields in this struct.
func (o *hiddenStructValue) Len() int {
if o.obj == nil {
return 0
}
return len(o.arcs)
}
// At reports the key and value of the ith field, i < o.Len().
func (o *hiddenStructValue) At(i int) (key string, v Value) {
arc := o.arcs[i]
return o.v.idx.LabelStr(arc.Label), newChildValue(o, i)
}
func (o *hiddenStructValue) at(i int) *adt.Vertex {
return o.arcs[i]
}
// Lookup reports the field for the given key. The returned Value is invalid
// if it does not exist.
func (o *hiddenStructValue) Lookup(key string) Value {
f := o.v.idx.StrLabel(key)
i := 0
len := o.Len()
for ; i < len; i++ {
if o.arcs[i].Label == f {
break
}
}
if i == len {
x := mkErr(o.v.idx, o.obj, 0, "field not found: %v", key)
x.NotExists = true
// TODO: more specifically we should test whether the values that
// are addressable from the root of the configuration can support the
// looked up value. This will avoid false positives such as when
// an open literal struct is passed to a builtin.
if o.obj.Accept(o.ctx, f) {
x.Code = adt.IncompleteError
}
return newErrValue(o.v, x)
}
return newChildValue(o, i)
}
// MarshalJSON returns a valid JSON encoding or reports an error if any of the
// fields is invalid.
func (o *structValue) marshalJSON() (b []byte, err errors.Error) {
b = append(b, '{')
n := o.Len()
for i := 0; i < n; i++ {
k, v := o.At(i)
s, err := internaljson.Marshal(k)
if err != nil {
return nil, unwrapJSONError(err)
}
b = append(b, s...)
b = append(b, ':')
bb, err := internaljson.Marshal(v)
if err != nil {
return nil, unwrapJSONError(err)
}
b = append(b, bb...)
if i < n-1 {
b = append(b, ',')
}
}
b = append(b, '}')
return b, nil
}
var _ errors.Error = &marshalError{}
type marshalError struct {
err errors.Error
b *adt.Bottom
}
func toMarshalErr(v Value, b *adt.Bottom) error {
return &marshalError{v.toErr(b), b}
}
func marshalErrf(v Value, src adt.Node, code adt.ErrorCode, msg string, args ...interface{}) error {
arguments := append([]interface{}{code, msg}, args...)
b := mkErr(v.idx, src, arguments...)
return toMarshalErr(v, b)
}
func (e *marshalError) Error() string {
return fmt.Sprintf("cue: marshal error: %v", e.err)
}
func (e *marshalError) Bottom() *adt.Bottom { return e.b }
func (e *marshalError) Path() []string { return e.err.Path() }
func (e *marshalError) Msg() (string, []interface{}) { return e.err.Msg() }
func (e *marshalError) Position() token.Pos { return e.err.Position() }
func (e *marshalError) InputPositions() []token.Pos {
return e.err.InputPositions()
}
func unwrapJSONError(err error) errors.Error {
switch x := err.(type) {
case *json.MarshalerError:
return unwrapJSONError(x.Err)
case *marshalError:
return x
case errors.Error:
return &marshalError{x, nil}
default:
return &marshalError{errors.Wrapf(err, token.NoPos, "json error"), nil}
}
}
// An Iterator iterates over values.
type Iterator struct {
val Value
idx *runtime.Runtime
ctx *adt.OpContext
arcs []*adt.Vertex
p int
cur Value
f adt.Feature
arcType adt.ArcType
}
type hiddenIterator = Iterator
// Next advances the iterator to the next value and reports whether there was
// any. It must be called before the first call to Value or Key.
func (i *Iterator) Next() bool {
if i.p >= len(i.arcs) {
i.cur = Value{}
return false
}
arc := i.arcs[i.p]
arc.Finalize(i.ctx)
p := linkParent(i.val.parent_, i.val.v, arc)
i.cur = makeValue(i.val.idx, arc, p)
i.f = arc.Label
i.arcType = arc.ArcType
i.p++
return true
}
// Value returns the current value in the list. It will panic if Next advanced
// past the last entry.
func (i *Iterator) Value() Value {
return i.cur
}
// Selector reports the field label of this iteration.
func (i *Iterator) Selector() Selector {
sel := featureToSel(i.f, i.idx)
// Only call wrapConstraint if there is any constraint type to wrap with.
if ctype := fromArcType(i.arcType); ctype != 0 {
sel = wrapConstraint(sel, ctype)
}
return sel
}
// Label reports the label of the value if i iterates over struct fields and ""
// otherwise.
//
// Slated to be deprecated: use i.Selector().String(). Note that this will give
// more accurate string representations.
func (i *hiddenIterator) Label() string {
if i.f == 0 {
return ""
}
return i.idx.LabelStr(i.f)
}
// IsHidden reports if a field is hidden from the data model.
//
// Deprecated: use i.Selector().PkgPath() != ""
func (i *hiddenIterator) IsHidden() bool {
return i.f.IsHidden()
}
// IsOptional reports if a field is optional.
func (i *Iterator) IsOptional() bool {
return i.arcType == adt.ArcOptional
}
// FieldType reports the type of the field.
func (i *Iterator) FieldType() SelectorType {
return featureToSelType(i.f, i.arcType)
}
// IsDefinition reports if a field is a definition.
//
// Deprecated: use i.Selector().IsDefinition()
func (i *hiddenIterator) IsDefinition() bool {
return i.f.IsDef()
}
// marshalJSON iterates over the list and generates JSON output. HasNext
// will return false after this operation.
func marshalList(l *Iterator) (b []byte, err errors.Error) {
b = append(b, '[')
if l.Next() {
for i := 0; ; i++ {
x, err := internaljson.Marshal(l.Value())
if err != nil {
return nil, unwrapJSONError(err)
}
b = append(b, x...)
if !l.Next() {
break
}
b = append(b, ',')
}
}
b = append(b, ']')
return b, nil
}
func (v Value) getNum(k adt.Kind) (*adt.Num, errors.Error) {
v, _ = v.Default()
ctx := v.ctx()
if err := v.checkKind(ctx, k); err != nil {
return nil, v.toErr(err)
}
n, _ := v.eval(ctx).(*adt.Num)
return n, nil
}
// MantExp breaks x into its mantissa and exponent components and returns the
// exponent. If a non-nil mant argument is provided its value is set to the
// mantissa of x. The components satisfy x == mant × 10**exp. It returns an
// error if v is not a number.
//
// The components are not normalized. For instance, 2.00 is represented mant ==
// 200 and exp == -2. Calling MantExp with a nil argument is an efficient way to
// get the exponent of the receiver.
func (v Value) MantExp(mant *big.Int) (exp int, err error) {
n, err := v.getNum(adt.NumKind)
if err != nil {
return 0, err
}
if n.X.Form != 0 {
return 0, ErrInfinite
}
if mant != nil {
mant.Set(n.X.Coeff.MathBigInt())
if n.X.Negative {
mant.Neg(mant)
}
}
return int(n.X.Exponent), nil
}
// Decimal is for internal use only. The Decimal type that is returned is
// subject to change.
func (v hiddenValue) Decimal() (d *internal.Decimal, err error) {
n, err := v.getNum(adt.NumKind)
if err != nil {
return nil, err
}
return &n.X, nil
}
// AppendInt appends the string representation of x in the given base to buf and
// returns the extended buffer, or an error if the underlying number was not
// an integer.
func (v Value) AppendInt(buf []byte, base int) ([]byte, error) {
i, err := v.Int(nil)
if err != nil {
return nil, err
}
return i.Append(buf, base), nil
}
// AppendFloat appends to buf the string form of the floating-point number x.
// It returns an error if v is not a number.
func (v Value) AppendFloat(buf []byte, fmt byte, prec int) ([]byte, error) {
n, err := v.getNum(adt.NumKind)
if err != nil {
return nil, err
}
ctx := internal.BaseContext
nd := int(apd.NumDigits(&n.X.Coeff)) + int(n.X.Exponent)
if n.X.Form == apd.Infinite {
if n.X.Negative {
buf = append(buf, '-')
}
return append(buf, string('∞')...), nil
}
if fmt == 'f' && nd > 0 {
ctx = ctx.WithPrecision(uint32(nd + prec))
} else {
ctx = ctx.WithPrecision(uint32(prec))
}
var d apd.Decimal
ctx.Round(&d, &n.X)
return d.Append(buf, fmt), nil
}
var (
// ErrBelow indicates that a value was rounded down in a conversion.
ErrBelow = errors.New("value was rounded down")
// ErrAbove indicates that a value was rounded up in a conversion.
ErrAbove = errors.New("value was rounded up")
// ErrInfinite indicates that a value is infinite.
ErrInfinite = errors.New("infinite")
)
// Int converts the underlying integral number to an big.Int. It reports an
// error if the underlying value is not an integer type. If a non-nil *Int
// argument z is provided, Int stores the result in z instead of allocating a
// new Int.
func (v Value) Int(z *big.Int) (*big.Int, error) {
n, err := v.getNum(adt.IntKind)
if err != nil {
return nil, err
}
if z == nil {
z = &big.Int{}
}
if n.X.Exponent != 0 {
panic("cue: exponent should always be nil for integer types")
}
z.Set(n.X.Coeff.MathBigInt())
if n.X.Negative {
z.Neg(z)
}
return z, nil
}
// Int64 converts the underlying integral number to int64. It reports an
// error if the underlying value is not an integer type or cannot be represented
// as an int64. The result is (math.MinInt64, ErrAbove) for x < math.MinInt64,
// and (math.MaxInt64, ErrBelow) for x > math.MaxInt64.
func (v Value) Int64() (int64, error) {
n, err := v.getNum(adt.IntKind)
if err != nil {
return 0, err
}
if !n.X.Coeff.IsInt64() {
if n.X.Negative {
return math.MinInt64, ErrAbove
}
return math.MaxInt64, ErrBelow
}
i := n.X.Coeff.Int64()
if n.X.Negative {
i = -i
}
return i, nil
}
// Uint64 converts the underlying integral number to uint64. It reports an
// error if the underlying value is not an integer type or cannot be represented
// as a uint64. The result is (0, ErrAbove) for x < 0, and
// (math.MaxUint64, ErrBelow) for x > math.MaxUint64.
func (v Value) Uint64() (uint64, error) {
n, err := v.getNum(adt.IntKind)
if err != nil {
return 0, err
}
if n.X.Negative {
return 0, ErrAbove
}
if !n.X.Coeff.IsUint64() {
return math.MaxUint64, ErrBelow
}
i := n.X.Coeff.Uint64()
return i, nil
}
// trimZeros trims 0's for better JSON representations.
func trimZeros(s string) string {
n1 := len(s)
s2 := strings.TrimRight(s, "0")
n2 := len(s2)
if p := strings.IndexByte(s2, '.'); p != -1 {
if p == n2-1 {
return s[:len(s2)+1]
}
return s2
}
if n1-n2 <= 4 {
return s
}
return fmt.Sprint(s2, "e+", n1-n2)
}
var (
smallestPosFloat64 *apd.Decimal
smallestNegFloat64 *apd.Decimal
maxPosFloat64 *apd.Decimal
maxNegFloat64 *apd.Decimal
)
func init() {
const (
// math.SmallestNonzeroFloat64: 1 / 2**(1023 - 1 + 52)
smallest = "4.940656458412465441765687928682213723651e-324"
// math.MaxFloat64: 2**1023 * (2**53 - 1) / 2**52
max = "1.797693134862315708145274237317043567981e+308"
)
ctx := internal.BaseContext.WithPrecision(40)
var err error
smallestPosFloat64, _, err = ctx.NewFromString(smallest)
if err != nil {
panic(err)
}
smallestNegFloat64, _, err = ctx.NewFromString("-" + smallest)
if err != nil {
panic(err)
}
maxPosFloat64, _, err = ctx.NewFromString(max)
if err != nil {
panic(err)
}
maxNegFloat64, _, err = ctx.NewFromString("-" + max)
if err != nil {
panic(err)
}
}
// Float64 returns the float64 value nearest to x. It reports an error if v is
// not a number. If x is too small to be represented by a float64 (|x| <
// math.SmallestNonzeroFloat64), the result is (0, ErrBelow) or (-0, ErrAbove),
// respectively, depending on the sign of x. If x is too large to be represented
// by a float64 (|x| > math.MaxFloat64), the result is (+Inf, ErrAbove) or
// (-Inf, ErrBelow), depending on the sign of x.
func (v Value) Float64() (float64, error) {
n, err := v.getNum(adt.NumKind)
if err != nil {
return 0, err
}
if n.X.IsZero() {
return 0.0, nil
}
if n.X.Negative {
if n.X.Cmp(smallestNegFloat64) == 1 {
return -0, ErrAbove
}
if n.X.Cmp(maxNegFloat64) == -1 {
return math.Inf(-1), ErrBelow
}
} else {
if n.X.Cmp(smallestPosFloat64) == -1 {
return 0, ErrBelow
}
if n.X.Cmp(maxPosFloat64) == 1 {
return math.Inf(1), ErrAbove
}
}
f, _ := n.X.Float64()
return f, nil
}
// Value holds any value, which may be a Boolean, Error, List, Null, Number,
// Struct, or String.
type Value struct {
idx *runtime.Runtime
v *adt.Vertex
// Parent keeps track of the parent if the value corresponding to v.Parent
// differs, recursively.
parent_ *parent
}
// parent is a distinct type from Value to ensure more type safety: Value
// is typically used by value, so taking a pointer to it has a high risk
// or globbering the contents.
type parent struct {
v *adt.Vertex
p *parent
}
func (v Value) parent() Value {
switch {
case v.v == nil:
return Value{}
case v.parent_ != nil:
return Value{v.idx, v.parent_.v, v.parent_.p}
default:
return Value{v.idx, v.v.Parent, nil}
}
}
type valueScope Value
func (v valueScope) Vertex() *adt.Vertex { return v.v }
func (v valueScope) Parent() compile.Scope {
p := Value(v).parent()
if p.v == nil {
return nil
}
return valueScope(p)
}
type hiddenValue = Value
// Core is for internal use only.
func (v hiddenValue) Core(x *types.Value) {
x.V = v.v
x.R = v.idx
}
func newErrValue(v Value, b *adt.Bottom) Value {
node := &adt.Vertex{BaseValue: b}
if v.v != nil {
node.Label = v.v.Label
node.Parent = v.v.Parent
}
node.ForceDone()
node.AddConjunct(adt.MakeRootConjunct(nil, b))
return makeChildValue(v.parent(), node)
}
func newVertexRoot(idx *runtime.Runtime, ctx *adt.OpContext, x *adt.Vertex) Value {
if ctx != nil {
// This is indicative of an zero Value. In some cases this is called
// with an error value.
x.Finalize(ctx)
} else {
x.ForceDone()
}
return makeValue(idx, x, nil)
}
func newValueRoot(idx *runtime.Runtime, ctx *adt.OpContext, x adt.Expr) Value {
if n, ok := x.(*adt.Vertex); ok {
return newVertexRoot(idx, ctx, n)
}
node := &adt.Vertex{}
node.AddConjunct(adt.MakeRootConjunct(nil, x))
return newVertexRoot(idx, ctx, node)
}
func newChildValue(o *structValue, i int) Value {
arc := o.at(i)
return makeValue(o.v.idx, arc, linkParent(o.v.parent_, o.v.v, arc))
}
// Dereference reports the value v refers to if v is a reference or v itself
// otherwise.
func Dereference(v Value) Value {
n := v.v
if n == nil || len(n.Conjuncts) != 1 {
return v
}
env, expr := n.Conjuncts[0].EnvExpr()
// TODO: consider supporting unwrapping of structs or comprehensions around
// a single embedded reference.
r, _ := expr.(adt.Resolver)
if r == nil {
return v
}
c := adt.MakeRootConjunct(env, expr)
ctx := v.ctx()
n, b := ctx.Resolve(c, r)
if b != nil {
return newErrValue(v, b)
}
n.Finalize(ctx)
// NOTE: due to structure sharing, the path of the referred node may end
// up different from the one explicitly pointed to. The value will be the
// same, but the scope may differ.
// TODO(structureshare): see if we can construct the original path. This
// only has to be done if structures are being shared.
return makeValue(v.idx, n, nil)
}
func makeValue(idx *runtime.Runtime, v *adt.Vertex, p *parent) Value {
if v.Status() == 0 || v.BaseValue == nil {
panic(fmt.Sprintf("not properly initialized (state: %v, value: %T)",
v.Status(), v.BaseValue))
}
return Value{idx, v, p}
}
// makeChildValue makes a new value, of which p is the parent, and links the
// parent pointer to p if necessary.
func makeChildValue(p Value, arc *adt.Vertex) Value {
return makeValue(p.idx, arc, linkParent(p.parent_, p.v, arc))
}
// linkParent creates the parent struct for an arc, if necessary.
//
// The parent struct is necessary if the parent struct also has a parent struct,
// or if arc is (structurally) shared and does not have node as a parent.
func linkParent(p *parent, node, arc *adt.Vertex) *parent {
if p == nil && node == arc.Parent {
return nil
}
return &parent{node, p}
}
func remakeValue(base Value, env *adt.Environment, v adt.Expr) Value {
// TODO: right now this is necessary because disjunctions do not have
// populated conjuncts.
if v, ok := v.(*adt.Vertex); ok && !v.IsUnprocessed() {
return Value{base.idx, v, nil}
}
n := &adt.Vertex{Label: base.v.Label}
n.AddConjunct(adt.MakeRootConjunct(env, v))
n = manifest(base.ctx(), n)
n.Parent = base.v.Parent
return makeChildValue(base.parent(), n)
}
func remakeFinal(base Value, env *adt.Environment, v adt.Value) Value {
n := &adt.Vertex{Parent: base.v.Parent, Label: base.v.Label, BaseValue: v}
n.ForceDone()
return makeChildValue(base.parent(), n)
}
func (v Value) ctx() *adt.OpContext {
return newContext(v.idx)
}
// Eval resolves the references of a value and returns the result.
// This method is not necessary to obtain concrete values.
func (v Value) Eval() Value {
if v.v == nil {
return v
}
x := v.v
// x = eval.FinalizeValue(v.idx.Runtime, v.v)
// x.Finalize(v.ctx())
x = x.ToDataSingle()
return makeValue(v.idx, x, v.parent_)
// return remakeValue(v, nil, ctx.value(x))
}
// Default reports the default value and whether it existed. It returns the
// normal value if there is no default.
func (v Value) Default() (Value, bool) {
if v.v == nil {
return v, false
}
d := v.v.Default()
if d == v.v {
return v, false
}
return makeValue(v.idx, d, v.parent_), true
// d, ok := v.v.Value.(*adt.Disjunction)
// if !ok {
// return v, false
// }
// var w *adt.Vertex
// switch d.NumDefaults {
// case 0:
// return v, false
// case 1:
// w = d.Values[0]
// default:
// x := *v.v
// x.Value = &adt.Disjunction{
// Src: d.Src,
// Values: d.Values[:d.NumDefaults],
// NumDefaults: 0,
// }
// w = &x
// }
// w.Conjuncts = nil
// for _, c := range v.v.Conjuncts {
// // TODO: preserve field information.
// expr, _ := stripNonDefaults(c.Expr())
// w.AddConjunct(adt.MakeConjunct(c.Env, expr))
// }
// return makeValue(v.idx, w), true
// if !stripped {
// return v, false
// }
// n := *v.v
// n.Conjuncts = conjuncts
// return Value{v.idx, &n}, true
// isDefault := false
// for _, c := range v.v.Conjuncts {
// if hasDisjunction(c.Expr()) {
// isDefault = true
// break
// }
// }
// if !isDefault {
// return v, false
// }
// TODO: record expanded disjunctions in output.
// - Rename Disjunction to DisjunctionExpr
// - Introduce Disjuncts with Values.
// - In Expr introduce Star
// - Don't pick default by default?
// Evaluate the value.
// x := eval.FinalizeValue(v.idx.Runtime, v.v)
// if b, _ := x.Value.(*adt.Bottom); b != nil { // && b.IsIncomplete() {
// return v, false
// }
// // Finalize and return here.
// return Value{v.idx, x}, isDefault
}
// TODO: this should go: record preexpanded disjunctions in Vertex.
func hasDisjunction(expr adt.Expr) bool {
switch x := expr.(type) {
case *adt.DisjunctionExpr:
return true
case *adt.Conjunction:
for _, v := range x.Values {
if hasDisjunction(v) {
return true
}
}
case *adt.BinaryExpr:
switch x.Op {
case adt.OrOp:
return true
case adt.AndOp:
return hasDisjunction(x.X) || hasDisjunction(x.Y)
}
}
return false
}
// TODO: this should go: record preexpanded disjunctions in Vertex.
func stripNonDefaults(expr adt.Expr) (r adt.Expr, stripped bool) {
switch x := expr.(type) {
case *adt.DisjunctionExpr:
if !x.HasDefaults {
return x, false
}
d := *x
d.Values = []adt.Disjunct{}
for _, v := range x.Values {
if v.Default {
d.Values = append(d.Values, v)
}
}
if len(d.Values) == 1 {
return d.Values[0].Val, true
}
return &d, true
case *adt.BinaryExpr:
if x.Op != adt.AndOp {
return x, false
}
a, sa := stripNonDefaults(x.X)
b, sb := stripNonDefaults(x.Y)
if sa || sb {
bin := *x
bin.X = a
bin.Y = b
return &bin, true
}
return x, false
default:
return x, false
}
}
// Label reports he label used to obtain this value from the enclosing struct.
//
// TODO: get rid of this somehow. Probably by including a FieldInfo struct
// or the like.
func (v hiddenValue) Label() (string, bool) {
if v.v == nil || v.v.Label == 0 {
return "", false
}
return v.idx.LabelStr(v.v.Label), true
}
// Kind returns the kind of value. It returns BottomKind for atomic values that
// are not concrete. For instance, it will return BottomKind for the bounds
// >=0.
func (v Value) Kind() Kind {
if v.v == nil {
return BottomKind
}
c := v.v.BaseValue
if !v.v.IsConcrete() {
return BottomKind
}
// TODO: perhaps we should not consider open lists as "incomplete".
if v.IncompleteKind() == adt.ListKind && !v.v.IsClosedList() {
return BottomKind
}
return c.Kind()
}
// IncompleteKind returns a mask of all kinds that this value may be.
func (v Value) IncompleteKind() Kind {
if v.v == nil {
return BottomKind
}
return v.v.Kind()
}
// MarshalJSON marshalls this value into valid JSON.
func (v Value) MarshalJSON() (b []byte, err error) {
b, err = v.marshalJSON()
if err != nil {
return nil, unwrapJSONError(err)
}
return b, nil
}
func (v Value) marshalJSON() (b []byte, err error) {
v, _ = v.Default()
if v.v == nil {
return internaljson.Marshal(nil)
}
ctx := newContext(v.idx)
x := v.eval(ctx)
if _, ok := x.(adt.Resolver); ok {
return nil, marshalErrf(v, x, adt.IncompleteError, "value %q contains unresolved references", str(ctx, x))
}
if !adt.IsConcrete(x) {
return nil, marshalErrf(v, x, adt.IncompleteError, "cannot convert incomplete value %q to JSON", str(ctx, x))
}
// TODO: implement marshalles in value.
switch k := x.Kind(); k {
case adt.NullKind:
return internaljson.Marshal(nil)
case adt.BoolKind:
return internaljson.Marshal(x.(*adt.Bool).B)
case adt.IntKind, adt.FloatKind, adt.NumKind:
b, err := x.(*adt.Num).X.MarshalText()
b = bytes.TrimLeft(b, "+")
return b, err
case adt.StringKind:
return internaljson.Marshal(x.(*adt.String).Str)
case adt.BytesKind:
return internaljson.Marshal(x.(*adt.Bytes).B)
case adt.ListKind:
i, _ := v.List()
return marshalList(&i)
case adt.StructKind:
obj, err := v.structValData(ctx)
if err != nil {
return nil, toMarshalErr(v, err)
}
return obj.marshalJSON()
case adt.BottomKind:
return nil, toMarshalErr(v, x.(*adt.Bottom))
default:
return nil, marshalErrf(v, x, 0, "cannot convert value %q of type %T to JSON", str(ctx, x), x)
}
}
// Syntax converts the possibly partially evaluated value into syntax. This
// can use used to print the value with package format.
func (v Value) Syntax(opts ...Option) ast.Node {
// TODO: the default should ideally be simplified representation that
// exactly represents the value. The latter can currently only be
// ensured with Raw().
if v.v == nil {
return nil
}
var o options = getOptions(opts)
// var inst *Instance
p := export.Profile{
Simplify: !o.raw,
TakeDefaults: o.final,
ShowOptional: !o.omitOptional && !o.concrete,
ShowDefinitions: !o.omitDefinitions && !o.concrete,
ShowHidden: !o.omitHidden && !o.concrete,
ShowAttributes: !o.omitAttrs,
ShowDocs: o.docs,
ShowErrors: o.showErrors,
InlineImports: o.inlineImports,
}
pkgID := v.instance().ID()
bad := func(name string, err error) ast.Node {
const format = `"%s: internal error
Error: %s
Profile:
%#v
Value: