/
composite.go
1214 lines (1062 loc) · 32.3 KB
/
composite.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 2020 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 adt
import (
"fmt"
"cuelang.org/go/cue/ast"
"cuelang.org/go/cue/errors"
"cuelang.org/go/cue/token"
)
// TODO: unanswered questions about structural cycles:
//
// 1. When detecting a structural cycle, should we consider this as:
// a) an unevaluated value,
// b) an incomplete error (which does not affect parent validity), or
// c) a special value.
//
// Making it an error is the simplest way to ensure reentrancy is disallowed:
// without an error it would require an additional mechanism to stop reentrancy
// from continuing to process. Even worse, in some cases it may only partially
// evaluate, resulting in unexpected results. For this reason, we are taking
// approach `b` for now.
//
// This has some consequences of how disjunctions are treated though. Consider
//
// list: {
// head: _
// tail: list | null
// }
//
// When making it an error, evaluating the above will result in
//
// list: {
// head: _
// tail: null
// }
//
// because list will result in a structural cycle, and thus an error, it will be
// stripped from the disjunction. This may or may not be a desirable property. A
// nice thing is that it is not required to write `list | *null`. A disadvantage
// is that this is perhaps somewhat inexplicit.
//
// When not making it an error (and simply cease evaluating child arcs upon
// cycle detection), the result would be:
//
// list: {
// head: _
// tail: list | null
// }
//
// In other words, an evaluation would result in a cycle and thus an error.
// Implementations can recognize such cases by having unevaluated arcs. An
// explicit structure cycle marker would probably be less error prone.
//
// Note that in both cases, a reference to list will still use the original
// conjuncts, so the result will be the same for either method in this case.
//
//
// 2. Structural cycle allowance.
//
// Structural cycle detection disallows reentrancy as well. This means one
// cannot use structs for recursive computation. This will probably preclude
// evaluation of some configuration. Given that there is no real alternative
// yet, we could allow structural cycle detection to be optionally disabled.
// An Environment links the parent scopes for identifier lookup to a composite
// node. Each conjunct that make up node in the tree can be associated with
// a different environment (although some conjuncts may share an Environment).
type Environment struct {
Up *Environment
Vertex *Vertex
// DynamicLabel is only set when instantiating a field from a pattern
// constraint. It is used to resolve label references.
DynamicLabel Feature
// TODO(perf): make the following public fields a shareable struct as it
// mostly is going to be the same for child nodes.
// TODO: This can probably move into the nodeContext, making it a map from
// conjunct to Value.
cache map[cacheKey]Value
}
type cacheKey struct {
Expr Expr
Arc *Vertex
}
func (e *Environment) up(ctx *OpContext, count int32) *Environment {
for ; count > 0; count-- {
e = e.Up
ctx.Assertf(ctx.Pos(), e.Vertex != nil, "Environment.up encountered a nil vertex")
}
return e
}
type ID int32
// evalCached is used to look up dynamic field pattern constraint expressions.
func (e *Environment) evalCached(c *OpContext, x Expr) Value {
if v, ok := x.(Value); ok {
return v
}
key := cacheKey{x, nil}
v, ok := e.cache[key]
if !ok {
if e.cache == nil {
e.cache = map[cacheKey]Value{}
}
env, src := c.e, c.src
c.e, c.src = e, x.Source()
// Save and restore errors to ensure that only relevant errors are
// associated with the cash.
err := c.errs
v = c.evalState(x, require(partial, allKnown)) // TODO: should this be finalized?
c.e, c.src = env, src
c.errs = err
if b, ok := v.(*Bottom); !ok || !b.IsIncomplete() {
e.cache[key] = v
}
}
return v
}
// A Vertex is a node in the value tree. It may be a leaf or internal node.
// It may have arcs to represent elements of a fully evaluated struct or list.
//
// For structs, it only contains definitions and concrete fields.
// optional fields are dropped.
//
// It maintains source information such as a list of conjuncts that contributed
// to the value.
type Vertex struct {
// Parent links to a parent Vertex. This parent should only be used to
// access the parent's Label field to find the relative location within a
// tree.
Parent *Vertex
// State:
// eval: nil, BaseValue: nil -- unevaluated
// eval: *, BaseValue: nil -- evaluating
// eval: *, BaseValue: * -- finalized
//
state *nodeContext
// cc manages the closedness logic for this Vertex. It is created
// by rootCloseContext.
// TODO: move back to nodeContext, but be sure not to clone it.
cc *closeContext
// Label is the feature leading to this vertex.
Label Feature
// TODO: move the following fields to nodeContext.
// status indicates the evaluation progress of this vertex.
status vertexStatus
// hasAllConjuncts indicates that the set of conjuncts is complete.
// This is the case if the conjuncts of all its ancestors have been
// processed.
hasAllConjuncts bool
// isData indicates that this Vertex is to be interpreted as data: pattern
// and additional constraints, as well as optional fields, should be
// ignored.
isData bool
// Closed indicates whether this Vertex is recursively closed. This is the
// case, for instance, if it is a node in a definition or if one of the
// conjuncts, or ancestor conjuncts, is a definition.
Closed bool
// MultiLet indicates whether multiple let fields were added from
// different sources. If true, a LetReference must be resolved using
// the per-Environment value cache.
MultiLet bool
// After this is set, no more arcs may be added during evaluation. This is
// set, for instance, after a Vertex is used as a source for comprehensions,
// or any other operation that relies on the set of arcs being constant.
LockArcs bool
// IsDynamic signifies whether this struct is computed as part of an
// expression and not part of the static evaluation tree.
// Used for cycle detection.
IsDynamic bool
nonRooted bool // indicates that there is no path from the root of the tree.
// hasPendingArc is set if this Vertex has a void arc (e.g. for comprehensions)
hasPendingArc bool
// ArcType indicates the level of optionality of this arc.
ArcType ArcType
// cyclicReferences is a linked list of internal references pointing to this
// Vertex. This is used to shorten the path of some structural cycles.
cyclicReferences *RefNode
// BaseValue is the value associated with this vertex. For lists and structs
// this is a sentinel value indicating its kind.
BaseValue BaseValue
// ChildErrors is the collection of all errors of children.
ChildErrors *Bottom
// The parent of nodes can be followed to determine the path within the
// configuration of this node.
// Value Value
Arcs []*Vertex // arcs are sorted in display order.
// PatternConstraints are additional constraints that match more nodes.
// Constraints that match existing Arcs already have their conjuncts
// mixed in.
// TODO: either put in StructMarker/ListMarker or integrate with Arcs
// so that this pointer is unnecessary.
PatternConstraints *Constraints
// Conjuncts lists the structs that ultimately formed this Composite value.
// This includes all selected disjuncts.
//
// This value may be nil, in which case the Arcs are considered to define
// the final value of this Vertex.
Conjuncts []Conjunct
// Structs is a slice of struct literals that contributed to this value.
// This information is used to compute the topological sort of arcs.
Structs []*StructInfo
}
// rootCloseContext creates a closeContext for this Vertex or returns the
// existing one.
func (v *Vertex) rootCloseContext() *closeContext {
if v.cc == nil {
v.cc = &closeContext{
group: &ConjunctGroup{},
parent: nil,
src: v,
parentConjuncts: v,
}
v.cc.incDependent(ROOT, nil) // matched in REF(decrement:nodeDone)
}
return v.cc
}
// newInlineVertex creates a Vertex that is needed for computation, but for
// which there is no CUE path defined from the root Vertex.
func (ctx *OpContext) newInlineVertex(parent *Vertex, v BaseValue, a ...Conjunct) *Vertex {
return &Vertex{
Parent: parent,
BaseValue: v,
IsDynamic: true,
ArcType: ArcMember,
Conjuncts: a,
}
}
// updateArcType updates v.ArcType if t is more restrictive.
func (v *Vertex) updateArcType(t ArcType) {
if t >= v.ArcType {
return
}
if v.ArcType == ArcNotPresent {
return
}
if s := v.state; s != nil && s.ctx.isDevVersion() {
c := s.ctx
if s.scheduler.frozen.meets(arcTypeKnown) {
parent := v.Parent
parent.reportFieldCycleError(c, c.Source().Pos(), v.Label)
return
}
}
v.ArcType = t
}
// isDefined indicates whether this arc is a "value" field, and not a constraint
// or void arc.
func (v *Vertex) isDefined() bool {
return v.ArcType == ArcMember
}
// IsConstraint reports whether the Vertex is an optional or required field.
func (v *Vertex) IsConstraint() bool {
return v.ArcType == ArcOptional || v.ArcType == ArcRequired
}
// IsDefined indicates whether this arc is defined meaning it is not a
// required or optional constraint and not a "void" arc.
// It will evaluate the arc, and thus evaluate any comprehension, to make this
// determination.
func (v *Vertex) IsDefined(c *OpContext) bool {
if v.isDefined() {
return true
}
v.Finalize(c)
return v.isDefined()
}
// Rooted reports whether there is a path from the root of the tree to this
// Vertex.
func (v *Vertex) Rooted() bool {
return !v.nonRooted && !v.Label.IsLet() && !v.IsDynamic
}
type ArcType uint8
const (
// ArcMember means that this arc is a normal non-optional field
// (including regular, hidden, and definition fields).
ArcMember ArcType = iota
// ArcRequired is like optional, but requires that a field be specified.
// Fields are of the form foo!.
ArcRequired
// ArcOptional represents fields of the form foo? and defines constraints
// for foo in case it is defined.
ArcOptional
// ArcPending means that it is not known yet whether an arc exists and that
// its conjuncts need to be processed to find out. This happens when an arc
// is provisionally added as part of a comprehension, but when this
// comprehension has not yet yielded any results.
ArcPending
// ArcNotPresent indicates that this arc is not present and, unlike
// ArcPending, needs no further processing.
ArcNotPresent
// TODO: define a type for optional arcs. This will be needed for pulling
// in optional fields into the Vertex, which, in turn, is needed for
// structure sharing, among other things.
// We could also define types for required fields and potentially lets.
)
func (a ArcType) String() string {
switch a {
case ArcMember:
return "Member"
case ArcOptional:
return "Optional"
case ArcRequired:
return "Required"
case ArcPending:
return "Pending"
case ArcNotPresent:
return "NotPresent"
}
return fmt.Sprintf("ArcType(%d)", a)
}
// definitelyExists reports whether an arc is a constraint or member arc.
// TODO: we should check that users of this call ensure there are no
// ArcPendings.
func (v *Vertex) definitelyExists() bool {
return v.ArcType < ArcPending
}
// ConstraintFromToken converts a given AST constraint token to the
// corresponding ArcType.
func ConstraintFromToken(t token.Token) ArcType {
switch t {
case token.OPTION:
return ArcOptional
case token.NOT:
return ArcRequired
}
return ArcMember
}
// Token reports the token corresponding to the constraint represented by a,
// or token.ILLEGAL otherwise.
func (a ArcType) Token() (t token.Token) {
switch a {
case ArcOptional:
t = token.OPTION
case ArcRequired:
t = token.NOT
}
return t
}
// Suffix reports the field suffix for the given ArcType if it is a
// constraint or the empty string otherwise.
func (a ArcType) Suffix() string {
switch a {
case ArcOptional:
return "?"
case ArcRequired:
return "!"
// For debugging internal state. This is not CUE syntax.
case ArcPending:
return "*"
case ArcNotPresent:
return "-"
}
return ""
}
func (v *Vertex) Clone() *Vertex {
c := *v
c.state = nil
return &c
}
type StructInfo struct {
*StructLit
Env *Environment
CloseInfo
// Embed indicates the struct in which this struct is embedded (originally),
// or nil if this is a root structure.
// Embed *StructInfo
// Context *RefInfo // the location from which this struct originates.
Disable bool
Embedding bool
}
// TODO(perf): this could be much more aggressive for eliminating structs that
// are immaterial for closing.
func (s *StructInfo) useForAccept() bool {
if c := s.closeInfo; c != nil {
return !c.noCheck
}
return true
}
// vertexStatus indicates the evaluation progress of a Vertex.
type vertexStatus int8
const (
// unprocessed indicates a Vertex has not been processed before.
// Value must be nil.
unprocessed vertexStatus = iota
// evaluating means that the current Vertex is being evaluated. If this is
// encountered it indicates a reference cycle. Value must be nil.
evaluating
// partial indicates that the result was only partially evaluated. It will
// need to be fully evaluated to get a complete results.
//
// TODO: this currently requires a renewed computation. Cache the
// nodeContext to allow reusing the computations done so far.
partial
// conjuncts is the state reached when all conjuncts have been evaluated,
// but without recursively processing arcs.
conjuncts
// evaluatingArcs indicates that the arcs of the Vertex are currently being
// evaluated. If this is encountered it indicates a structural cycle.
// Value does not have to be nil
evaluatingArcs
// finalized means that this node is fully evaluated and that the results
// are save to use without further consideration.
finalized
)
func (s vertexStatus) String() string {
switch s {
case unprocessed:
return "unprocessed"
case evaluating:
return "evaluating"
case partial:
return "partial"
case conjuncts:
return "conjuncts"
case evaluatingArcs:
return "evaluatingArcs"
case finalized:
return "finalized"
default:
return "unknown"
}
}
func (v *Vertex) Status() vertexStatus {
return v.status
}
// ForceDone prevents v from being evaluated.
func (v *Vertex) ForceDone() {
v.updateStatus(finalized)
}
// IsUnprocessed reports whether v is unprocessed.
func (v *Vertex) IsUnprocessed() bool {
return v.status == unprocessed
}
func (v *Vertex) updateStatus(s vertexStatus) {
Assertf(v.status <= s+1, "attempt to regress status from %d to %d", v.Status(), s)
if s == finalized && v.BaseValue == nil {
// TODO: for debugging.
// panic("not finalized")
}
v.status = s
}
// setParentDone signals v that the conjuncts of all ancestors have been
// processed.
// If all conjuncts of this node have been set, all arcs will be notified
// of this parent being done.
//
// Note: once a vertex has started evaluation (state != nil), insertField will
// cause all conjuncts to be immediately processed. This means that if all
// ancestors of this node processed their conjuncts, and if this node has
// processed all its conjuncts as well, all nodes that it embedded will have
// received all their conjuncts as well, after which this node will have been
// notified of these conjuncts.
func (v *Vertex) setParentDone() {
v.hasAllConjuncts = true
// Could set "Conjuncts" flag of arc at this point.
if n := v.state; n != nil && len(n.conjuncts) == n.conjunctsPos {
for _, a := range v.Arcs {
a.setParentDone()
}
}
}
// Value returns the Value of v without definitions if it is a scalar
// or itself otherwise.
func (v *Vertex) Value() Value {
switch x := v.BaseValue.(type) {
case nil:
return nil
case *StructMarker, *ListMarker:
return v
case Value:
// TODO: recursively descend into Vertex?
return x
default:
panic(fmt.Sprintf("unexpected type %T", v.BaseValue))
}
}
// isUndefined reports whether a vertex does not have a useable BaseValue yet.
func (v *Vertex) isUndefined() bool {
if !v.isDefined() {
return true
}
switch v.BaseValue {
case nil, cycle:
return true
}
return false
}
func (x *Vertex) IsConcrete() bool {
return x.Concreteness() <= Concrete
}
// IsData reports whether v should be interpreted in data mode. In other words,
// it tells whether optional field matching and non-regular fields, like
// definitions and hidden fields, should be ignored.
func (v *Vertex) IsData() bool {
return v.isData || len(v.Conjuncts) == 0
}
// ToDataSingle creates a new Vertex that represents just the regular fields
// of this vertex. Arcs are left untouched.
// It is used by cue.Eval to convert nodes to data on per-node basis.
func (v *Vertex) ToDataSingle() *Vertex {
w := *v
w.isData = true
w.state = nil
w.status = finalized
return &w
}
// ToDataAll returns a new v where v and all its descendents contain only
// the regular fields.
func (v *Vertex) ToDataAll(ctx *OpContext) *Vertex {
arcs := make([]*Vertex, 0, len(v.Arcs))
for _, a := range v.Arcs {
if !a.IsDefined(ctx) {
continue
}
if a.Label.IsRegular() {
arcs = append(arcs, a.ToDataAll(ctx))
}
}
w := *v
w.state = nil
w.status = finalized
w.BaseValue = toDataAll(ctx, w.BaseValue)
w.Arcs = arcs
w.isData = true
w.Conjuncts = make([]Conjunct, len(v.Conjuncts))
// TODO(perf): this is not strictly necessary for evaluation, but it can
// hurt performance greatly. Drawback is that it may disable ordering.
for _, s := range w.Structs {
s.Disable = true
}
copy(w.Conjuncts, v.Conjuncts)
for i, c := range w.Conjuncts {
if v, _ := c.x.(Value); v != nil {
w.Conjuncts[i].x = toDataAll(ctx, v).(Value)
}
}
return &w
}
func toDataAll(ctx *OpContext, v BaseValue) BaseValue {
switch x := v.(type) {
default:
return x
case *Vertex:
return x.ToDataAll(ctx)
// The following cases are always erroneous, but we handle them anyway
// to avoid issues with the closedness algorithm down the line.
case *Disjunction:
d := *x
d.Values = make([]Value, len(x.Values))
for i, v := range x.Values {
switch x := v.(type) {
case *Vertex:
d.Values[i] = x.ToDataAll(ctx)
default:
d.Values[i] = x
}
}
return &d
case *Conjunction:
c := *x
c.Values = make([]Value, len(x.Values))
for i, v := range x.Values {
// This case is okay because the source is of type Value.
c.Values[i] = toDataAll(ctx, v).(Value)
}
return &c
}
}
// func (v *Vertex) IsEvaluating() bool {
// return v.Value == cycle
// }
func (v *Vertex) IsErr() bool {
// if v.Status() > Evaluating {
if _, ok := v.BaseValue.(*Bottom); ok {
return true
}
// }
return false
}
func (v *Vertex) Err(c *OpContext) *Bottom {
v.Finalize(c)
if b, ok := v.BaseValue.(*Bottom); ok {
return b
}
return nil
}
// func (v *Vertex) Evaluate()
func (v *Vertex) Finalize(c *OpContext) {
// Saving and restoring the error context prevents v from panicking in
// case the caller did not handle existing errors in the context.
err := c.errs
c.errs = nil
c.unify(v, final(finalized, allKnown))
c.errs = err
}
// CompleteArcs ensures the set of arcs has been computed.
func (v *Vertex) CompleteArcs(c *OpContext) {
c.unify(v, final(conjuncts, allKnown))
}
func (v *Vertex) AddErr(ctx *OpContext, b *Bottom) {
v.SetValue(ctx, CombineErrors(nil, v.Value(), b))
}
// SetValue sets the value of a node.
func (v *Vertex) SetValue(ctx *OpContext, value BaseValue) *Bottom {
return v.setValue(ctx, finalized, value)
}
func (v *Vertex) setValue(ctx *OpContext, state vertexStatus, value BaseValue) *Bottom {
v.BaseValue = value
// TODO: should not set status here for new evaluator.
v.updateStatus(state)
return nil
}
// ToVertex wraps v in a new Vertex, if necessary.
func ToVertex(v Value) *Vertex {
switch x := v.(type) {
case *Vertex:
return x
default:
n := &Vertex{
status: finalized,
BaseValue: x,
}
n.AddConjunct(MakeRootConjunct(nil, v))
return n
}
}
// Unwrap returns the possibly non-concrete scalar value of v, v itself for
// lists and structs, or nil if v is an undefined type.
func Unwrap(v Value) Value {
x, ok := v.(*Vertex)
if !ok {
return v
}
x = x.Indirect()
if n := x.state; n != nil && isCyclePlaceholder(x.BaseValue) {
if n.errs != nil && !n.errs.IsIncomplete() {
return n.errs
}
if n.scalar != nil {
return n.scalar
}
}
return x.Value()
}
// Indirect unrolls indirections of Vertex values. These may be introduced,
// for instance, by temporary bindings such as comprehension values.
// It returns v itself if v does not point to another Vertex.
func (v *Vertex) Indirect() *Vertex {
for {
arc, ok := v.BaseValue.(*Vertex)
if !ok {
return v
}
v = arc
}
}
// OptionalType is a bit field of the type of optional constraints in use by an
// Acceptor.
type OptionalType int8
const (
HasField OptionalType = 1 << iota // X: T
HasDynamic // (X): T or "\(X)": T
HasPattern // [X]: T
HasComplexPattern // anything but a basic type
HasAdditional // ...T
IsOpen // Defined for all fields
)
func (v *Vertex) Kind() Kind {
// This is possible when evaluating comprehensions. It is potentially
// not known at this time what the type is.
switch {
// TODO: using this line would be more stable.
// case v.status != finalized && v.state != nil:
case v.state != nil:
return v.state.kind
case v.BaseValue == nil:
return TopKind
default:
return v.BaseValue.Kind()
}
}
func (v *Vertex) OptionalTypes() OptionalType {
var mask OptionalType
for _, s := range v.Structs {
mask |= s.OptionalTypes()
}
return mask
}
// IsOptional reports whether a field is explicitly defined as optional,
// as opposed to whether it is allowed by a pattern constraint.
func (v *Vertex) IsOptional(label Feature) bool {
for _, a := range v.Arcs {
if a.Label == label {
return a.IsConstraint()
}
}
return false
}
func (v *Vertex) accepts(ok, required bool) bool {
return ok || (!required && !v.Closed)
}
func (v *Vertex) IsClosedStruct() bool {
switch x := v.BaseValue.(type) {
default:
return false
case *StructMarker:
if x.NeedClose {
return true
}
case *Disjunction:
}
return isClosed(v)
}
func (v *Vertex) IsClosedList() bool {
if x, ok := v.BaseValue.(*ListMarker); ok {
return !x.IsOpen
}
return false
}
// TODO: return error instead of boolean? (or at least have version that does.)
func (v *Vertex) Accept(ctx *OpContext, f Feature) bool {
if f.IsHidden() || f.IsLet() {
return true
}
if x, ok := v.BaseValue.(*Disjunction); ok {
for _, v := range x.Values {
if x, ok := v.(*Vertex); ok && x.Accept(ctx, f) {
return true
}
}
return false
}
if f.IsInt() {
switch v.BaseValue.(type) {
case *ListMarker:
// TODO(perf): use precomputed length.
if f.Index() < len(v.Elems()) {
return true
}
return !v.IsClosedList()
default:
return v.Kind()&ListKind != 0
}
}
if k := v.Kind(); k&StructKind == 0 && f.IsString() {
// If the value is bottom, we may not really know if this used to
// be a struct.
if k != BottomKind || len(v.Structs) == 0 {
return false
}
}
if !v.IsClosedStruct() || v.Lookup(f) != nil {
return true
}
// TODO(perf): collect positions in error.
defer ctx.ReleasePositions(ctx.MarkPositions())
return v.accepts(Accept(ctx, v, f))
}
// MatchAndInsert finds the conjuncts for optional fields, pattern
// constraints, and additional constraints that match f and inserts them in
// arc. Use f is 0 to match all additional constraints only.
func (v *Vertex) MatchAndInsert(ctx *OpContext, arc *Vertex) {
if !v.Accept(ctx, arc.Label) {
return
}
// Go backwards to simulate old implementation.
for i := len(v.Structs) - 1; i >= 0; i-- {
s := v.Structs[i]
if s.Disable {
continue
}
s.MatchAndInsert(ctx, arc)
}
}
func (v *Vertex) IsList() bool {
_, ok := v.BaseValue.(*ListMarker)
return ok
}
// Lookup returns the Arc with label f if it exists or nil otherwise.
func (v *Vertex) Lookup(f Feature) *Vertex {
for _, a := range v.Arcs {
if a.Label == f {
a = a.Indirect()
return a
}
}
return nil
}
// Elems returns the regular elements of a list.
func (v *Vertex) Elems() []*Vertex {
// TODO: add bookkeeping for where list arcs start and end.
a := make([]*Vertex, 0, len(v.Arcs))
for _, x := range v.Arcs {
if x.Label.IsInt() {
a = append(a, x)
}
}
return a
}
// GetArc returns a Vertex for the outgoing arc with label f. It creates and
// ads one if it doesn't yet exist.
func (v *Vertex) GetArc(c *OpContext, f Feature, t ArcType) (arc *Vertex, isNew bool) {
unreachableForDev(c)
arc = v.Lookup(f)
if arc != nil {
arc.updateArcType(t)
return arc, false
}
if v.LockArcs {
// TODO(errors): add positions.
if f.IsInt() {
c.addErrf(EvalError, token.NoPos,
"element at index %v not allowed by earlier comprehension or reference cycle", f)
} else {
c.addErrf(EvalError, token.NoPos,
"field %v not allowed by earlier comprehension or reference cycle", f)
}
}
// TODO: consider setting Dynamic here from parent.
arc = &Vertex{
Parent: v,
Label: f,
ArcType: t,
nonRooted: v.IsDynamic || v.Label.IsLet() || v.nonRooted,
}
v.Arcs = append(v.Arcs, arc)
if t == ArcPending {
v.hasPendingArc = true
}
return arc, true
}
func (v *Vertex) Source() ast.Node {
if v != nil {
if b, ok := v.BaseValue.(Value); ok {
return b.Source()
}
}
return nil
}
// AddConjunct adds the given Conjuncts to v if it doesn't already exist.
func (v *Vertex) AddConjunct(c Conjunct) *Bottom {
if v.BaseValue != nil && !isCyclePlaceholder(v.BaseValue) {
// TODO: investigate why this happens at all. Removing it seems to
// change the order of fields in some cases.
//
// This is likely a bug in the evaluator and should not happen.
return &Bottom{Err: errors.Newf(token.NoPos, "cannot add conjunct")}
}
if !v.hasConjunct(c) {
v.addConjunctUnchecked(c)
}
return nil
}
func (v *Vertex) hasConjunct(c Conjunct) (added bool) {
switch f := c.x.(type) {
case *BulkOptionalField, *Ellipsis:
case *Field:
v.updateArcType(f.ArcType)
case *DynamicField:
v.updateArcType(f.ArcType)
default:
v.ArcType = ArcMember
}
return hasConjunct(v.Conjuncts, c)
}