forked from cuelang/cue
/
eval.go
2155 lines (1847 loc) · 53.4 KB
/
eval.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 2021 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 eval contains the high level CUE evaluation strategy.
//
// CUE allows for a significant amount of freedom in order of evaluation due to
// the commutativity of the unification operation. This package implements one
// of the possible strategies.
package adt
// TODO:
// - result should be nodeContext: this allows optionals info to be extracted
// and computed.
//
import (
"fmt"
"html/template"
"strings"
"cuelang.org/go/cue/ast"
"cuelang.org/go/cue/errors"
"cuelang.org/go/cue/token"
)
// TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO
//
// - Reuse work from previous cycles. For instance, if we can guarantee that a
// value is always correct for partial results, we can just process the arcs
// going from Partial to Finalized, without having to reevaluate the value.
//
// - Test closedness far more thoroughly.
//
type Stats struct {
DisjunctCount int
UnifyCount int
Freed int
Retained int
Reused int
Allocs int
}
// Leaks reports the number of nodeContext structs leaked. These are typically
// benign, as they will just be garbage collected, as long as the pointer from
// the original nodes has been eliminated or the original nodes are also not
// referred to. But Leaks may have notable impact on performance, and thus
// should be avoided.
func (s *Stats) Leaks() int {
return s.Allocs + s.Reused - s.Freed
}
var stats = template.Must(template.New("stats").Parse(`{{"" -}}
Leaks: {{.Leaks}}
Freed: {{.Freed}}
Reused: {{.Reused}}
Allocs: {{.Allocs}}
Retain: {{.Retained}}
Unifications: {{.UnifyCount}}
Disjuncts: {{.DisjunctCount}}`))
func (s *Stats) String() string {
buf := &strings.Builder{}
_ = stats.Execute(buf, s)
return buf.String()
}
func (c *OpContext) Stats() *Stats {
return &c.stats
}
// TODO: Note: NewContext takes essentially a cue.Value. By making this
// type more central, we can perhaps avoid context creation.
// func NewContext(r Runtime, v *Vertex) *OpContext {
// e := NewUnifier(r)
// return e.NewContext(v)
// }
var structSentinel = &StructMarker{}
var incompleteSentinel = &Bottom{
Code: IncompleteError,
Err: errors.Newf(token.NoPos, "incomplete"),
}
// evaluate returns the evaluated value associated with v. It may return a
// partial result. That is, if v was not yet unified, it may return a
// concrete value that must be the result assuming the configuration has no
// errors.
//
// This semantics allows CUE to break reference cycles in a straightforward
// manner.
//
// Vertex v must still be evaluated at some point to catch the underlying
// error.
//
// TODO: return *Vertex
func (c *OpContext) evaluate(v *Vertex, state VertexStatus) Value {
if v.isUndefined() {
// Use node itself to allow for cycle detection.
c.Unify(v, state)
}
if n := v.state; n != nil {
if n.errs != nil && !n.errs.IsIncomplete() {
return n.errs
}
if n.scalar != nil && isCyclePlaceholder(v.BaseValue) {
return n.scalar
}
}
switch x := v.BaseValue.(type) {
case *Bottom:
if x.IsIncomplete() {
c.AddBottom(x)
return nil
}
return x
case nil:
if v.state != nil {
switch x := v.state.getValidators().(type) {
case Value:
return x
default:
w := *v
w.BaseValue = x
return &w
}
}
Assertf(false, "no BaseValue: state: %v; requested: %v", v.status, state)
}
if v.status < Finalized && v.state != nil {
// TODO: errors are slightly better if we always add addNotify, but
// in this case it is less likely to cause a performance penalty.
// See https://github.com/cuelang/cue/issues/661. It may be possible to
// relax this again once we have proper tests to prevent regressions of
// that issue.
if !v.state.done() || v.state.errs != nil {
v.state.addNotify(c.vertex)
}
}
return v
}
// Unify fully unifies all values of a Vertex to completion and stores
// the result in the Vertex. If unify was called on v before it returns
// the cached results.
func (c *OpContext) Unify(v *Vertex, state VertexStatus) {
// defer c.PopVertex(c.PushVertex(v))
// Ensure a node will always have a nodeContext after calling Unify if it is
// not yet Finalized.
n := v.getNodeContext(c)
defer v.freeNode(n)
if state <= v.Status() {
if v.Status() != Partial && state != Partial {
return
}
}
switch v.Status() {
case Evaluating:
n.insertConjuncts()
return
case EvaluatingArcs:
Assertf(v.status > 0, "unexpected status %d", v.status)
return
case 0:
if v.Label.IsDef() {
v.Closed = true
}
if v.Parent != nil {
if v.Parent.Closed {
v.Closed = true
}
}
// TODO(perf): ideally we should always perform a closedness check if
// state is Finalized. This is currently not possible when computing a
// partial disjunction as the closedness information is not yet
// complete, possibly leading to a disjunct to be rejected prematurely.
// It is probably possible to fix this if we could add StructInfo
// structures demarked per conjunct.
//
// In practice this should not be a problem: when disjuncts originate
// from the same disjunct, they will have the same StructInfos, and thus
// Equal is able to equate them even in the precense of optional field.
// In general, combining any limited set of disjuncts will soon reach
// a fixed point where duplicate elements can be eliminated this way.
//
// Note that not checking closedness is irrelevant for disjunctions of
// scalars. This means it also doesn't hurt performance where structs
// have a discriminator field (e.g. Kubernetes). We should take care,
// though, that any potential performance issues are eliminated for
// Protobuf-like oneOf fields.
ignore := state != Finalized || n.skipNonMonotonicChecks()
if !v.Label.IsInt() && v.Parent != nil && !ignore {
// Visit arcs recursively to validate and compute error.
if _, err := verifyArc2(c, v.Label, v, v.Closed); err != nil {
// Record error in child node to allow recording multiple
// conflicts at the appropriate place, to allow valid fields to
// be represented normally and, most importantly, to avoid
// recursive processing of a disallowed field.
v.SetValue(c, Finalized, err)
return
}
}
defer c.PopArc(c.PushArc(v))
c.stats.UnifyCount++
// Clear any remaining error.
if err := c.Err(); err != nil {
panic("uncaught error")
}
// Set the cache to a cycle error to ensure a cyclic reference will result
// in an error if applicable. A cyclic error may be ignored for
// non-expression references. The cycle error may also be removed as soon
// as there is evidence what a correct value must be, but before all
// validation has taken place.
//
// TODO(cycle): having a more recursive algorithm would make this
// special cycle handling unnecessary.
v.BaseValue = cycle
v.UpdateStatus(Evaluating)
n.conjuncts = v.Conjuncts
n.insertConjuncts()
fallthrough
case Partial:
defer c.PopArc(c.PushArc(v))
v.status = Evaluating
// Use maybeSetCache for cycle breaking
for n.maybeSetCache(); n.expandOne(); n.maybeSetCache() {
}
n.doNotify()
if !n.done() {
switch {
case len(n.disjunctions) > 0 && isCyclePlaceholder(v.BaseValue):
// We disallow entering computations of disjunctions with
// incomplete data.
if state == Finalized {
b := c.NewErrf("incomplete cause disjunction")
b.Code = IncompleteError
n.errs = CombineErrors(nil, n.errs, b)
v.SetValue(n.ctx, Finalized, b)
} else {
n.node.UpdateStatus(Partial)
}
return
case state <= AllArcs:
n.node.UpdateStatus(Partial)
return
}
}
if s := v.Status(); state <= s {
// We have found a partial result. There may still be errors
// down the line which may result from further evaluating this
// field, but that will be caught when evaluating this field
// for real.
// This also covers the case where a recursive evaluation triggered
// this field to become finalized in the mean time. In that case
// we can avoid running another expandDisjuncts.
return
}
// Disjunctions should always be finalized. If there are nested
// disjunctions the last one should be finalized.
disState := state
if len(n.disjunctions) > 0 && disState != Finalized {
disState = Finalized
}
n.expandDisjuncts(disState, n, maybeDefault, false, true)
n.finalizeDisjuncts()
switch len(n.disjuncts) {
case 0:
case 1:
x := n.disjuncts[0].result
x.state = nil
*v = x
default:
d := n.createDisjunct()
v.BaseValue = d
// The conjuncts will have too much information. Better have no
// information than incorrect information.
for _, d := range d.Values {
// We clear the conjuncts for now. As these disjuncts are for API
// use only, we will fill them out when necessary (using Defaults).
d.Conjuncts = nil
// TODO: use a more principled form of dereferencing. For instance,
// disjuncts could already be assumed to be the given Vertex, and
// the the main vertex could be dereferenced during evaluation.
for _, a := range d.Arcs {
for _, x := range a.Conjuncts {
// All the environments for embedded structs need to be
// dereferenced.
for env := x.Env; env != nil && env.Vertex == v; env = env.Up {
env.Vertex = d
}
}
}
}
v.Arcs = nil
// v.Structs = nil // TODO: should we keep or discard the Structs?
// TODO: how to represent closedness information? Do we need it?
}
// If the state has changed, it is because a disjunct has been run, or
// because a single disjunct has replaced it. Restore the old state as
// to not confuse memory management.
v.state = n
// We don't do this in postDisjuncts, as it should only be done after
// completing all disjunctions.
if !n.done() {
if err := n.incompleteErrors(); err != nil {
b, _ := n.node.BaseValue.(*Bottom)
if b != err {
err = CombineErrors(n.ctx.src, b, err)
}
n.node.BaseValue = err
}
}
if state != Finalized {
return
}
if v.BaseValue == nil {
v.BaseValue = n.getValidators()
}
// Free memory here?
v.UpdateStatus(Finalized)
case AllArcs:
defer c.PopArc(c.PushArc(v))
n.completeArcs(state)
case Finalized:
}
}
// insertConjuncts inserts conjuncts previously uninserted.
func (n *nodeContext) insertConjuncts() {
for len(n.conjuncts) > 0 {
nInfos := len(n.node.Structs)
p := &n.conjuncts[0]
n.conjuncts = n.conjuncts[1:]
n.addExprConjunct(*p)
// Record the OptionalTypes for all structs that were inferred by this
// Conjunct. This information can be used by algorithms such as trim.
for i := nInfos; i < len(n.node.Structs); i++ {
p.CloseInfo.FieldTypes |= n.node.Structs[i].types
}
}
}
// finalizeDisjuncts: incomplete errors are kept around and not removed early.
// This call filters the incomplete errors and removes them
//
// This also collects all errors of empty disjunctions. These cannot be
// collected during the finalization state of individual disjuncts. Care should
// be taken to only call this after all disjuncts have been finalized.
func (n *nodeContext) finalizeDisjuncts() {
a := n.disjuncts
if len(a) == 0 {
return
}
k := 0
for i, d := range a {
switch d.finalDone() {
case true:
a[k], a[i] = d, a[k]
k++
default:
if err := d.incompleteErrors(); err != nil {
n.disjunctErrs = append(n.disjunctErrs, err)
}
}
d.free()
}
if k == 0 {
n.makeError()
}
n.disjuncts = a[:k]
}
func (n *nodeContext) doNotify() {
if n.errs == nil || len(n.notify) == 0 {
return
}
for _, v := range n.notify {
if v.state == nil {
if b, ok := v.BaseValue.(*Bottom); ok {
v.BaseValue = CombineErrors(nil, b, n.errs)
} else {
v.BaseValue = n.errs
}
} else {
v.state.addBottom(n.errs)
}
}
n.notify = n.notify[:0]
}
func (n *nodeContext) postDisjunct(state VertexStatus) {
ctx := n.ctx
for {
// Use maybeSetCache for cycle breaking
for n.maybeSetCache(); n.expandOne(); n.maybeSetCache() {
}
if aList, id := n.addLists(); aList != nil {
n.updateNodeType(ListKind, aList, id)
} else {
break
}
}
if n.aStruct != nil {
n.updateNodeType(StructKind, n.aStruct, n.aStructID)
}
switch err := n.getErr(); {
case err != nil:
n.node.BaseValue = err
n.errs = nil
default:
if isCyclePlaceholder(n.node.BaseValue) {
if !n.done() {
n.node.BaseValue = n.incompleteErrors()
} else {
n.node.BaseValue = nil
}
}
// TODO: this ideally should be done here. However, doing so causes
// a somewhat more aggressive cutoff in disjunction cycles, which cause
// some incompatibilities. Fix in another CL.
//
// else if !n.done() {
// n.expandOne()
// if err := n.incompleteErrors(); err != nil {
// n.node.BaseValue = err
// }
// }
// We are no longer evaluating.
// n.node.UpdateStatus(Partial)
n.node.UpdateStatus(Evaluating)
// Either set to Conjunction or error.
// TODO: verify and simplify the below code to determine whether
// something is a struct.
markStruct := false
if n.aStruct != nil {
markStruct = true
} else if len(n.node.Structs) > 0 {
markStruct = n.kind&StructKind != 0 && !n.hasTop
}
v := n.node.Value()
if n.node.BaseValue == nil && markStruct {
n.node.BaseValue = &StructMarker{}
v = n.node
}
if v != nil && IsConcrete(v) {
// Also check when we already have errors as we may find more
// serious errors and would like to know about all errors anyway.
if n.lowerBound != nil {
if b := ctx.Validate(n.lowerBound, v); b != nil {
// TODO(errors): make Validate return boolean and generate
// optimized conflict message. Also track and inject IDs
// to determine origin location.s
if e, _ := b.Err.(*ValueError); e != nil {
e.AddPosition(n.lowerBound)
e.AddPosition(v)
}
n.addBottom(b)
}
}
if n.upperBound != nil {
if b := ctx.Validate(n.upperBound, v); b != nil {
// TODO(errors): make Validate return boolean and generate
// optimized conflict message. Also track and inject IDs
// to determine origin location.s
if e, _ := b.Err.(*ValueError); e != nil {
e.AddPosition(n.upperBound)
e.AddPosition(v)
}
n.addBottom(b)
}
}
// MOVE BELOW
// TODO(perf): only delay processing of actual non-monotonic checks.
skip := n.skipNonMonotonicChecks()
if v := n.node.Value(); v != nil && IsConcrete(v) && !skip {
for _, v := range n.checks {
// TODO(errors): make Validate return bottom and generate
// optimized conflict message. Also track and inject IDs
// to determine origin location.s
if b := ctx.Validate(v, n.node); b != nil {
n.addBottom(b)
}
}
}
} else if state == Finalized {
n.node.BaseValue = n.getValidators()
}
if v == nil {
break
}
switch {
case v.Kind() == ListKind:
for _, a := range n.node.Arcs {
if a.Label.Typ() == StringLabel {
n.addErr(ctx.Newf("list may not have regular fields"))
// TODO(errors): add positions for list and arc definitions.
}
}
// case !isStruct(n.node) && v.Kind() != BottomKind:
// for _, a := range n.node.Arcs {
// if a.Label.IsRegular() {
// n.addErr(errors.Newf(token.NoPos,
// // TODO(errors): add positions of non-struct values and arcs.
// "cannot combine scalar values with arcs"))
// }
// }
}
}
if err := n.getErr(); err != nil {
if b, _ := n.node.BaseValue.(*Bottom); b != nil {
err = CombineErrors(nil, b, err)
}
n.node.BaseValue = err
// TODO: add return: if evaluation of arcs is important it can be done
// later. Logically we're done.
}
n.completeArcs(state)
}
func (n *nodeContext) incompleteErrors() *Bottom {
// collect incomplete errors.
var err *Bottom // n.incomplete
for _, d := range n.dynamicFields {
err = CombineErrors(nil, err, d.err)
}
for _, c := range n.forClauses {
err = CombineErrors(nil, err, c.err)
}
for _, c := range n.ifClauses {
err = CombineErrors(nil, err, c.err)
}
for _, x := range n.exprs {
err = CombineErrors(nil, err, x.err)
}
if err == nil {
// safeguard.
err = incompleteSentinel
}
return err
}
func (n *nodeContext) completeArcs(state VertexStatus) {
if state <= AllArcs {
n.node.UpdateStatus(AllArcs)
return
}
n.node.UpdateStatus(EvaluatingArcs)
ctx := n.ctx
if cyclic := n.hasCycle && !n.hasNonCycle; cyclic {
n.node.BaseValue = CombineErrors(nil,
n.node.Value(),
&Bottom{
Code: StructuralCycleError,
Err: ctx.Newf("structural cycle"),
Value: n.node.Value(),
// TODO: probably, this should have the referenced arc.
})
// Don't process Arcs. This is mostly to ensure that no Arcs with
// an Unprocessed status remain in the output.
n.node.Arcs = nil
} else {
// Visit arcs recursively to validate and compute error.
for _, a := range n.node.Arcs {
if a.nonMonotonicInsertGen >= a.nonMonotonicLookupGen && a.nonMonotonicLookupGen > 0 {
err := ctx.Newf(
"cycle: new field %s inserted by if clause that was previously evaluated by another if clause", a.Label.SelectorString(ctx))
err.AddPosition(n.node)
n.node.BaseValue = &Bottom{Err: err}
} else if a.nonMonotonicReject {
err := ctx.Newf(
"cycle: field %s was added after an if clause evaluated it",
a.Label.SelectorString(ctx))
err.AddPosition(n.node)
n.node.BaseValue = &Bottom{Err: err}
}
// Call UpdateStatus here to be absolutely sure the status is set
// correctly and that we are not regressing.
n.node.UpdateStatus(EvaluatingArcs)
ctx.Unify(a, state)
// Don't set the state to Finalized if the child arcs are not done.
if state == Finalized && a.status < Finalized {
state = AllArcs
}
if err, _ := a.BaseValue.(*Bottom); err != nil {
n.node.AddChildError(err)
}
}
}
n.node.UpdateStatus(state)
}
// TODO: this is now a sentinel. Use a user-facing error that traces where
// the cycle originates.
var cycle = &Bottom{
Err: errors.Newf(token.NoPos, "cycle error"),
Code: CycleError,
}
func isCyclePlaceholder(v BaseValue) bool {
return v == cycle
}
func (n *nodeContext) createDisjunct() *Disjunction {
a := make([]*Vertex, len(n.disjuncts))
p := 0
hasDefaults := false
for i, x := range n.disjuncts {
v := new(Vertex)
*v = x.result
v.state = nil
switch x.defaultMode {
case isDefault:
a[i] = a[p]
a[p] = v
p++
hasDefaults = true
case notDefault:
hasDefaults = true
fallthrough
case maybeDefault:
a[i] = v
}
}
// TODO: disambiguate based on concrete values.
// TODO: consider not storing defaults.
// if p > 0 {
// a = a[:p]
// }
return &Disjunction{
Values: a,
NumDefaults: p,
HasDefaults: hasDefaults,
}
}
type arcKey struct {
arc *Vertex
id CloseInfo
}
// A nodeContext is used to collate all conjuncts of a value to facilitate
// unification. Conceptually order of unification does not matter. However,
// order has relevance when performing checks of non-monotic properities. Such
// checks should only be performed once the full value is known.
type nodeContext struct {
nextFree *nodeContext
refCount int
ctx *OpContext
node *Vertex
// usedArcs is a list of arcs that were looked up during non-monotonic operations, but do not exist yet.
usedArcs []*Vertex
// TODO: (this is CL is first step)
// filter *Vertex a subset of composite with concrete fields for
// bloom-like filtering of disjuncts. We should first verify, however,
// whether some breath-first search gives sufficient performance, as this
// should already ensure a quick-fail for struct disjunctions with
// discriminators.
arcMap []arcKey
// snapshot holds the last value of the vertex before calling postDisjunct.
snapshot Vertex
// Result holds the last evaluated value of the vertex after calling
// postDisjunct.
result Vertex
// Current value (may be under construction)
scalar Value // TODO: use Value in node.
scalarID CloseInfo
// Concrete conjuncts
kind Kind
kindExpr Expr // expr that adjust last value (for error reporting)
kindID CloseInfo // for error tracing
lowerBound *BoundValue // > or >=
upperBound *BoundValue // < or <=
checks []Validator // BuiltinValidator, other bound values.
errs *Bottom
// Conjuncts holds a reference to the Vertex Arcs that still need
// processing. It does NOT need to be copied.
conjuncts []Conjunct
// notify is used to communicate errors in cyclic dependencies.
// TODO: also use this to communicate increasingly more concrete values.
notify []*Vertex
// Struct information
dynamicFields []envDynamic
ifClauses []envYield
forClauses []envYield
aStruct Expr
aStructID CloseInfo
// Expression conjuncts
lists []envList
vLists []*Vertex
exprs []envExpr
hasTop bool
hasCycle bool // has conjunct with structural cycle
hasNonCycle bool // has conjunct without structural cycle
// Disjunction handling
disjunctions []envDisjunct
// usedDefault indicates the for each of possibly multiple parent
// disjunctions whether it is unified with a default disjunct or not.
// This is then later used to determine whether a disjunction should
// be treated as a marked disjunction.
usedDefault []defaultInfo
defaultMode defaultMode
disjuncts []*nodeContext
buffer []*nodeContext
disjunctErrs []*Bottom
}
type defaultInfo struct {
// parentMode indicates whether this values was used as a default value,
// based on the parent mode.
parentMode defaultMode
// The result of default evaluation for a nested disjunction.
nestedMode defaultMode
origMode defaultMode
}
func (n *nodeContext) addNotify(v *Vertex) {
if v != nil {
n.notify = append(n.notify, v)
}
}
func (n *nodeContext) clone() *nodeContext {
d := n.ctx.newNodeContext(n.node)
d.refCount++
d.ctx = n.ctx
d.node = n.node
d.scalar = n.scalar
d.scalarID = n.scalarID
d.kind = n.kind
d.kindExpr = n.kindExpr
d.kindID = n.kindID
d.aStruct = n.aStruct
d.aStructID = n.aStructID
d.hasTop = n.hasTop
d.lowerBound = n.lowerBound
d.upperBound = n.upperBound
d.errs = n.errs
d.hasTop = n.hasTop
d.hasCycle = n.hasCycle
d.hasNonCycle = n.hasNonCycle
// d.arcMap = append(d.arcMap, n.arcMap...) // XXX add?
// d.usedArcs = append(d.usedArcs, n.usedArcs...) // XXX: add?
d.notify = append(d.notify, n.notify...)
d.checks = append(d.checks, n.checks...)
d.dynamicFields = append(d.dynamicFields, n.dynamicFields...)
d.ifClauses = append(d.ifClauses, n.ifClauses...)
d.forClauses = append(d.forClauses, n.forClauses...)
d.lists = append(d.lists, n.lists...)
d.vLists = append(d.vLists, n.vLists...)
d.exprs = append(d.exprs, n.exprs...)
d.usedDefault = append(d.usedDefault, n.usedDefault...)
// No need to clone d.disjunctions
return d
}
func (c *OpContext) newNodeContext(node *Vertex) *nodeContext {
if n := c.freeListNode; n != nil {
c.stats.Reused++
c.freeListNode = n.nextFree
*n = nodeContext{
ctx: c,
node: node,
kind: TopKind,
usedArcs: n.usedArcs[:0],
arcMap: n.arcMap[:0],
notify: n.notify[:0],
checks: n.checks[:0],
dynamicFields: n.dynamicFields[:0],
ifClauses: n.ifClauses[:0],
forClauses: n.forClauses[:0],
lists: n.lists[:0],
vLists: n.vLists[:0],
exprs: n.exprs[:0],
disjunctions: n.disjunctions[:0],
usedDefault: n.usedDefault[:0],
disjunctErrs: n.disjunctErrs[:0],
disjuncts: n.disjuncts[:0],
buffer: n.buffer[:0],
}
return n
}
c.stats.Allocs++
return &nodeContext{
ctx: c,
node: node,
kind: TopKind,
}
}
func (v *Vertex) getNodeContext(c *OpContext) *nodeContext {
if v.state == nil {
if v.status == Finalized {
return nil
}
v.state = c.newNodeContext(v)
} else if v.state.node != v {
panic("getNodeContext: nodeContext out of sync")
}
v.state.refCount++
return v.state
}
func (v *Vertex) freeNode(n *nodeContext) {
if n == nil {
return
}
if n.node != v {
panic("freeNode: unpaired free")
}
if v.state != nil && v.state != n {
panic("freeNode: nodeContext out of sync")
}
if n.refCount--; n.refCount == 0 {
if v.status == Finalized {
v.freeNodeState()
} else {
n.ctx.stats.Retained++
}
}
}
func (v *Vertex) freeNodeState() {
if v.state == nil {
return
}
state := v.state
v.state = nil
state.ctx.freeNodeContext(state)
}
func (n *nodeContext) free() {
if n.refCount--; n.refCount == 0 {
n.ctx.freeNodeContext(n)
}
}
func (c *OpContext) freeNodeContext(n *nodeContext) {
c.stats.Freed++
n.nextFree = c.freeListNode
c.freeListNode = n
n.node = nil
n.refCount = 0
}
// TODO(perf): return a dedicated ConflictError that can track original
// positions on demand.
func (n *nodeContext) addConflict(
v1, v2 Node,
k1, k2 Kind,
id1, id2 CloseInfo) {
ctx := n.ctx
var err *ValueError
if k1 == k2 {
err = ctx.NewPosf(token.NoPos,
"conflicting values %s and %s", ctx.Str(v1), ctx.Str(v2))
} else {
err = ctx.NewPosf(token.NoPos,
"conflicting values %s and %s (mismatched types %s and %s)",
ctx.Str(v1), ctx.Str(v2), k1, k2)
}
err.AddPosition(v1)
err.AddPosition(v2)
err.AddClosedPositions(id1)
err.AddClosedPositions(id2)
n.addErr(err)
}
func (n *nodeContext) updateNodeType(k Kind, v Expr, id CloseInfo) bool {
ctx := n.ctx
kind := n.kind & k
switch {
case n.kind == BottomKind,
k == BottomKind:
return false
case kind == BottomKind:
if n.kindExpr != nil {
n.addConflict(n.kindExpr, v, n.kind, k, n.kindID, id)
} else {
n.addErr(ctx.Newf(
"conflicting value %s (mismatched types %s and %s)",
ctx.Str(v), n.kind, k))
}
}
if n.kind != kind || n.kindExpr == nil {
n.kindExpr = v