-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy patheval.go
2829 lines (2360 loc) · 63.8 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
package topdown
import (
"context"
"fmt"
"io"
"sort"
"strconv"
"strings"
"github.com/open-policy-agent/opa/ast"
"github.com/open-policy-agent/opa/metrics"
"github.com/open-policy-agent/opa/storage"
"github.com/open-policy-agent/opa/topdown/builtins"
"github.com/open-policy-agent/opa/topdown/cache"
"github.com/open-policy-agent/opa/topdown/copypropagation"
)
type evalIterator func(*eval) error
type unifyIterator func() error
type queryIDFactory struct {
curr uint64
}
// Note: The first call to Next() returns 0.
func (f *queryIDFactory) Next() uint64 {
curr := f.curr
f.curr++
return curr
}
type builtinErrors struct {
errs []error
}
type eval struct {
ctx context.Context
metrics metrics.Metrics
seed io.Reader
time *ast.Term
queryID uint64
queryIDFact *queryIDFactory
parent *eval
caller *eval
cancel Cancel
query ast.Body
queryCompiler ast.QueryCompiler
index int
indexing bool
bindings *bindings
store storage.Store
baseCache *baseCache
txn storage.Transaction
compiler *ast.Compiler
input *ast.Term
data *ast.Term
external *resolverTrie
targetStack *refStack
tracers []QueryTracer
traceEnabled bool
plugTraceVars bool
instr *Instrumentation
builtins map[string]*Builtin
builtinCache builtins.Cache
virtualCache *virtualCache
comprehensionCache *comprehensionCache
interQueryBuiltinCache cache.InterQueryCache
saveSet *saveSet
saveStack *saveStack
saveSupport *saveSupport
saveNamespace *ast.Term
skipSaveNamespace bool
inliningControl *inliningControl
genvarprefix string
genvarid int
runtime *ast.Term
builtinErrors *builtinErrors
}
func (e *eval) Run(iter evalIterator) error {
e.traceEnter(e.query)
return e.eval(func(e *eval) error {
e.traceExit(e.query)
err := iter(e)
e.traceRedo(e.query)
return err
})
}
func (e *eval) builtinFunc(name string) (*ast.Builtin, BuiltinFunc, bool) {
decl, ok := ast.BuiltinMap[name]
if !ok {
bi, ok := e.builtins[name]
if ok {
return bi.Decl, bi.Func, true
}
} else {
f, ok := builtinFunctions[name]
if ok {
return decl, f, true
}
}
return nil, nil, false
}
func (e *eval) closure(query ast.Body) *eval {
cpy := *e
cpy.index = 0
cpy.query = query
cpy.queryID = cpy.queryIDFact.Next()
cpy.parent = e
return &cpy
}
func (e *eval) child(query ast.Body) *eval {
cpy := *e
cpy.index = 0
cpy.query = query
cpy.queryID = cpy.queryIDFact.Next()
cpy.bindings = newBindings(cpy.queryID, e.instr)
cpy.parent = e
return &cpy
}
func (e *eval) next(iter evalIterator) error {
e.index++
err := e.evalExpr(iter)
e.index--
return err
}
func (e *eval) partial() bool {
return e.saveSet != nil
}
func (e *eval) unknown(x interface{}, b *bindings) bool {
if !e.partial() {
return false
}
// If the caller provided an ast.Value directly (e.g., an ast.Ref) wrap
// it as an ast.Term because the saveSet Contains() function expects
// ast.Term.
if v, ok := x.(ast.Value); ok {
x = ast.NewTerm(v)
}
return saveRequired(e.compiler, e.inliningControl, true, e.saveSet, b, x, false)
}
func (e *eval) traceEnter(x ast.Node) {
e.traceEvent(EnterOp, x, "", nil)
}
func (e *eval) traceExit(x ast.Node) {
e.traceEvent(ExitOp, x, "", nil)
}
func (e *eval) traceEval(x ast.Node) {
e.traceEvent(EvalOp, x, "", nil)
}
func (e *eval) traceFail(x ast.Node) {
e.traceEvent(FailOp, x, "", nil)
}
func (e *eval) traceRedo(x ast.Node) {
e.traceEvent(RedoOp, x, "", nil)
}
func (e *eval) traceSave(x ast.Node) {
e.traceEvent(SaveOp, x, "", nil)
}
func (e *eval) traceIndex(x ast.Node, msg string, target *ast.Ref) {
e.traceEvent(IndexOp, x, msg, target)
}
func (e *eval) traceWasm(x ast.Node, target *ast.Ref) {
e.traceEvent(WasmOp, x, "", target)
}
func (e *eval) traceEvent(op Op, x ast.Node, msg string, target *ast.Ref) {
if !e.traceEnabled {
return
}
var parentID uint64
if e.parent != nil {
parentID = e.parent.queryID
}
evt := Event{
QueryID: e.queryID,
ParentID: parentID,
Op: op,
Node: x,
Location: x.Loc(),
Message: msg,
Ref: target,
}
// Skip plugging the local variables, unless any of the tracers
// had required it via their configuration. If any required the
// variable bindings then we will plug and give values for all
// tracers.
if e.plugTraceVars {
evt.Locals = ast.NewValueMap()
evt.LocalMetadata = map[ast.Var]VarMetadata{}
e.bindings.Iter(nil, func(k, v *ast.Term) error {
original := k.Value.(ast.Var)
rewritten, _ := e.rewrittenVar(original)
evt.LocalMetadata[original] = VarMetadata{
Name: rewritten,
Location: k.Loc(),
}
// For backwards compatibility save a copy of the values too..
evt.Locals.Put(k.Value, v.Value)
return nil
})
ast.WalkTerms(x, func(term *ast.Term) bool {
if v, ok := term.Value.(ast.Var); ok {
if _, ok := evt.LocalMetadata[v]; !ok {
if rewritten, ok := e.rewrittenVar(v); ok {
evt.LocalMetadata[v] = VarMetadata{
Name: rewritten,
Location: term.Loc(),
}
}
}
}
return false
})
}
for i := range e.tracers {
e.tracers[i].TraceEvent(evt)
}
}
func (e *eval) eval(iter evalIterator) error {
return e.evalExpr(iter)
}
func (e *eval) evalExpr(iter evalIterator) error {
if e.cancel != nil && e.cancel.Cancelled() {
return &Error{
Code: CancelErr,
Message: "caller cancelled query execution",
}
}
if e.index >= len(e.query) {
return iter(e)
}
expr := e.query[e.index]
e.traceEval(expr)
if len(expr.With) > 0 {
return e.evalWith(iter)
}
return e.evalStep(func(e *eval) error {
return e.next(iter)
})
}
func (e *eval) evalStep(iter evalIterator) error {
expr := e.query[e.index]
if expr.Negated {
return e.evalNot(iter)
}
var defined bool
var err error
switch terms := expr.Terms.(type) {
case []*ast.Term:
if expr.IsEquality() {
err = e.unify(terms[1], terms[2], func() error {
defined = true
err := iter(e)
e.traceRedo(expr)
return err
})
} else {
err = e.evalCall(terms, func() error {
defined = true
err := iter(e)
e.traceRedo(expr)
return err
})
}
case *ast.Term:
rterm := e.generateVar(fmt.Sprintf("term_%d_%d", e.queryID, e.index))
err = e.unify(terms, rterm, func() error {
if e.saveSet.Contains(rterm, e.bindings) {
return e.saveExpr(ast.NewExpr(rterm), e.bindings, func() error {
return iter(e)
})
}
if !e.bindings.Plug(rterm).Equal(ast.BooleanTerm(false)) {
defined = true
err := iter(e)
e.traceRedo(expr)
return err
}
return nil
})
}
if err != nil {
return err
}
if !defined {
e.traceFail(expr)
}
return nil
}
func (e *eval) evalNot(iter evalIterator) error {
expr := e.query[e.index]
if e.unknown(expr, e.bindings) {
return e.evalNotPartial(iter)
}
negation := ast.NewBody(expr.Complement().NoWith())
child := e.closure(negation)
var defined bool
child.traceEnter(negation)
err := child.eval(func(*eval) error {
child.traceExit(negation)
defined = true
child.traceRedo(negation)
return nil
})
if err != nil {
return err
}
if !defined {
return iter(e)
}
e.traceFail(expr)
return nil
}
func (e *eval) evalWith(iter evalIterator) error {
expr := e.query[e.index]
var disable []ast.Ref
if e.partial() {
// If the value is unknown the with statement cannot be evaluated and so
// the entire expression should be saved to be safe. In the future this
// could be relaxed in certain cases (e.g., if the with statement would
// have no affect.)
for _, with := range expr.With {
if e.saveSet.ContainsRecursive(with.Value, e.bindings) {
return e.saveExprMarkUnknowns(expr, e.bindings, func() error {
return e.next(iter)
})
}
}
// Disable inlining on all references in the expression so the result of
// partial evaluation has the same semamntics w/ the with statements
// preserved.
ast.WalkRefs(expr, func(x ast.Ref) bool {
disable = append(disable, x.GroundPrefix())
return false
})
}
pairsInput := [][2]*ast.Term{}
pairsData := [][2]*ast.Term{}
targets := []ast.Ref{}
for i := range expr.With {
plugged := e.bindings.Plug(expr.With[i].Value)
if isInputRef(expr.With[i].Target) {
pairsInput = append(pairsInput, [...]*ast.Term{expr.With[i].Target, plugged})
} else if isDataRef(expr.With[i].Target) {
pairsData = append(pairsData, [...]*ast.Term{expr.With[i].Target, plugged})
}
targets = append(targets, expr.With[i].Target.Value.(ast.Ref))
}
input, err := mergeTermWithValues(e.input, pairsInput)
if err != nil {
return &Error{
Code: ConflictErr,
Location: expr.Location,
Message: err.Error(),
}
}
data, err := mergeTermWithValues(e.data, pairsData)
if err != nil {
return &Error{
Code: ConflictErr,
Location: expr.Location,
Message: err.Error(),
}
}
oldInput, oldData := e.evalWithPush(input, data, targets, disable)
err = e.evalStep(func(e *eval) error {
e.evalWithPop(oldInput, oldData)
err := e.next(iter)
oldInput, oldData = e.evalWithPush(input, data, targets, disable)
return err
})
e.evalWithPop(oldInput, oldData)
return err
}
func (e *eval) evalWithPush(input *ast.Term, data *ast.Term, targets []ast.Ref, disable []ast.Ref) (*ast.Term, *ast.Term) {
var oldInput *ast.Term
if input != nil {
oldInput = e.input
e.input = input
}
var oldData *ast.Term
if data != nil {
oldData = e.data
e.data = data
}
e.comprehensionCache.Push()
e.virtualCache.Push()
e.targetStack.Push(targets)
e.inliningControl.PushDisable(disable, true)
return oldInput, oldData
}
func (e *eval) evalWithPop(input *ast.Term, data *ast.Term) {
e.inliningControl.PopDisable()
e.targetStack.Pop()
e.virtualCache.Pop()
e.comprehensionCache.Pop()
e.data = data
e.input = input
}
func (e *eval) evalNotPartial(iter evalIterator) error {
// Prepare query normally.
expr := e.query[e.index]
negation := expr.Complement().NoWith()
child := e.closure(ast.NewBody(negation))
// Unknowns is the set of variables that are marked as unknown. The variables
// are namespaced with the query ID that they originate in. This ensures that
// variables across two or more queries are identified uniquely.
//
// NOTE(tsandall): this is greedy in the sense that we only need variable
// dependencies of the negation.
unknowns := e.saveSet.Vars(e.caller.bindings)
// Run partial evaluation. Since the result may require support, push a new
// query onto the save stack to avoid mutating the current save query. If
// shallow inlining is not enabled, run copy propagation to further simplify
// the result.
var cp *copypropagation.CopyPropagator
if !e.inliningControl.shallow {
cp = copypropagation.New(unknowns).WithEnsureNonEmptyBody(true).WithCompiler(e.compiler)
}
var savedQueries []ast.Body
e.saveStack.PushQuery(nil)
child.eval(func(*eval) error {
query := e.saveStack.Peek()
plugged := query.Plug(e.caller.bindings)
if cp != nil {
plugged = applyCopyPropagation(cp, e.instr, plugged)
}
savedQueries = append(savedQueries, plugged)
return nil
})
e.saveStack.PopQuery()
// If partial evaluation produced no results, the expression is always undefined
// so it does not have to be saved.
if len(savedQueries) == 0 {
return iter(e)
}
// Check if the partial evaluation result can be inlined in this query. If not,
// generate support rules for the result. Depending on the size of the partial
// evaluation result and the contents, it may or may not be inlinable. We treat
// the unknowns as safe because vars in the save set will either be known to
// the caller or made safe by an expression on the save stack.
if !canInlineNegation(unknowns, savedQueries) {
return e.evalNotPartialSupport(child.queryID, expr, unknowns, savedQueries, iter)
}
// If we can inline the result, we have to generate the cross product of the
// queries. For example:
//
// (A && B) || (C && D)
//
// Becomes:
//
// (!A && !C) || (!A && !D) || (!B && !C) || (!B && !D)
return complementedCartesianProduct(savedQueries, 0, nil, func(q ast.Body) error {
return e.saveInlinedNegatedExprs(q, func() error {
return iter(e)
})
})
}
func (e *eval) evalNotPartialSupport(negationID uint64, expr *ast.Expr, unknowns ast.VarSet, queries []ast.Body, iter evalIterator) error {
// Prepare support rule head.
supportName := fmt.Sprintf("__not%d_%d_%d__", e.queryID, e.index, negationID)
term := ast.RefTerm(ast.DefaultRootDocument, e.saveNamespace, ast.StringTerm(supportName))
path := term.Value.(ast.Ref)
head := ast.NewHead(ast.Var(supportName), nil, ast.BooleanTerm(true))
bodyVars := ast.NewVarSet()
for _, q := range queries {
bodyVars.Update(q.Vars(ast.VarVisitorParams{}))
}
unknowns = unknowns.Intersect(bodyVars)
// Make rule args. Sort them to ensure order is deterministic.
args := make([]*ast.Term, 0, len(unknowns))
for v := range unknowns {
args = append(args, ast.NewTerm(v))
}
sort.Slice(args, func(i, j int) bool {
return args[i].Value.Compare(args[j].Value) < 0
})
if len(args) > 0 {
head.Args = ast.Args(args)
}
// Save support rules.
for _, query := range queries {
e.saveSupport.Insert(path, &ast.Rule{
Head: head,
Body: query,
})
}
// Save expression that refers to support rule set.
terms := expr.Terms
expr.Terms = nil // Prevent unnecessary copying the terms.
cpy := expr.Copy()
expr.Terms = terms
if len(args) > 0 {
terms := make([]*ast.Term, len(args)+1)
terms[0] = term
for i := 0; i < len(args); i++ {
terms[i+1] = args[i]
}
cpy.Terms = terms
} else {
cpy.Terms = term
}
return e.saveInlinedNegatedExprs([]*ast.Expr{cpy}, func() error {
return e.next(iter)
})
}
func (e *eval) evalCall(terms []*ast.Term, iter unifyIterator) error {
ref := terms[0].Value.(ast.Ref)
if ref[0].Equal(ast.DefaultRootDocument) {
eval := evalFunc{
e: e,
ref: ref,
terms: terms,
}
return eval.eval(iter)
}
bi, f, ok := e.builtinFunc(ref.String())
if !ok {
return unsupportedBuiltinErr(e.query[e.index].Location)
}
if e.unknown(e.query[e.index], e.bindings) {
return e.saveCall(len(bi.Decl.Args()), terms, iter)
}
var parentID uint64
if e.parent != nil {
parentID = e.parent.queryID
}
bctx := BuiltinContext{
Context: e.ctx,
Metrics: e.metrics,
Seed: e.seed,
Time: e.time,
Cancel: e.cancel,
Runtime: e.runtime,
Cache: e.builtinCache,
InterQueryBuiltinCache: e.interQueryBuiltinCache,
Location: e.query[e.index].Location,
QueryTracers: e.tracers,
TraceEnabled: e.traceEnabled,
QueryID: e.queryID,
ParentID: parentID,
}
eval := evalBuiltin{
e: e,
bi: bi,
bctx: bctx,
f: f,
terms: terms[1:],
}
return eval.eval(iter)
}
func (e *eval) unify(a, b *ast.Term, iter unifyIterator) error {
return e.biunify(a, b, e.bindings, e.bindings, iter)
}
func (e *eval) biunify(a, b *ast.Term, b1, b2 *bindings, iter unifyIterator) error {
a, b1 = b1.apply(a)
b, b2 = b2.apply(b)
switch vA := a.Value.(type) {
case ast.Var, ast.Ref, *ast.ArrayComprehension, *ast.SetComprehension, *ast.ObjectComprehension:
return e.biunifyValues(a, b, b1, b2, iter)
case ast.Null:
switch b.Value.(type) {
case ast.Var, ast.Null, ast.Ref:
return e.biunifyValues(a, b, b1, b2, iter)
}
case ast.Boolean:
switch b.Value.(type) {
case ast.Var, ast.Boolean, ast.Ref:
return e.biunifyValues(a, b, b1, b2, iter)
}
case ast.Number:
switch b.Value.(type) {
case ast.Var, ast.Number, ast.Ref:
return e.biunifyValues(a, b, b1, b2, iter)
}
case ast.String:
switch b.Value.(type) {
case ast.Var, ast.String, ast.Ref:
return e.biunifyValues(a, b, b1, b2, iter)
}
case *ast.Array:
switch vB := b.Value.(type) {
case ast.Var, ast.Ref, *ast.ArrayComprehension:
return e.biunifyValues(a, b, b1, b2, iter)
case *ast.Array:
return e.biunifyArrays(vA, vB, b1, b2, iter)
}
case ast.Object:
switch vB := b.Value.(type) {
case ast.Var, ast.Ref, *ast.ObjectComprehension:
return e.biunifyValues(a, b, b1, b2, iter)
case ast.Object:
return e.biunifyObjects(vA, vB, b1, b2, iter)
}
case ast.Set:
return e.biunifyValues(a, b, b1, b2, iter)
}
return nil
}
func (e *eval) biunifyArrays(a, b *ast.Array, b1, b2 *bindings, iter unifyIterator) error {
if a.Len() != b.Len() {
return nil
}
return e.biunifyArraysRec(a, b, b1, b2, iter, 0)
}
func (e *eval) biunifyArraysRec(a, b *ast.Array, b1, b2 *bindings, iter unifyIterator, idx int) error {
if idx == a.Len() {
return iter()
}
return e.biunify(a.Elem(idx), b.Elem(idx), b1, b2, func() error {
return e.biunifyArraysRec(a, b, b1, b2, iter, idx+1)
})
}
func (e *eval) biunifyObjects(a, b ast.Object, b1, b2 *bindings, iter unifyIterator) error {
if a.Len() != b.Len() {
return nil
}
// Objects must not contain unbound variables as keys at this point as we
// cannot unify them. Similar to sets, plug both sides before comparing the
// keys and unifying the values.
if nonGroundKeys(a) {
a = plugKeys(a, b1)
}
if nonGroundKeys(b) {
b = plugKeys(b, b2)
}
return e.biunifyObjectsRec(a, b, b1, b2, iter, a, 0)
}
func (e *eval) biunifyObjectsRec(a, b ast.Object, b1, b2 *bindings, iter unifyIterator, keys ast.Object, idx int) error {
if idx == keys.Len() {
return iter()
}
key, _ := keys.Elem(idx)
v2 := b.Get(key)
if v2 == nil {
return nil
}
return e.biunify(a.Get(key), v2, b1, b2, func() error {
return e.biunifyObjectsRec(a, b, b1, b2, iter, keys, idx+1)
})
}
func (e *eval) biunifyValues(a, b *ast.Term, b1, b2 *bindings, iter unifyIterator) error {
// Try to evaluate refs and comprehensions. If partial evaluation is
// enabled, then skip evaluation (and save the expression) if the term is
// in the save set. Currently, comprehensions are not evaluated during
// partial eval. This could be improved in the future.
var saveA, saveB bool
if _, ok := a.Value.(ast.Set); ok {
saveA = e.saveSet.ContainsRecursive(a, b1)
} else {
saveA = e.saveSet.Contains(a, b1)
if !saveA {
if _, refA := a.Value.(ast.Ref); refA {
return e.biunifyRef(a, b, b1, b2, iter)
}
}
}
if _, ok := b.Value.(ast.Set); ok {
saveB = e.saveSet.ContainsRecursive(b, b2)
} else {
saveB = e.saveSet.Contains(b, b2)
if !saveB {
if _, refB := b.Value.(ast.Ref); refB {
return e.biunifyRef(b, a, b2, b1, iter)
}
}
}
if saveA || saveB {
return e.saveUnify(a, b, b1, b2, iter)
}
if ast.IsComprehension(a.Value) {
return e.biunifyComprehension(a, b, b1, b2, false, iter)
} else if ast.IsComprehension(b.Value) {
return e.biunifyComprehension(b, a, b2, b1, true, iter)
}
// Perform standard unification.
_, varA := a.Value.(ast.Var)
_, varB := b.Value.(ast.Var)
if varA && varB {
if b1 == b2 && a.Equal(b) {
return iter()
}
undo := b1.bind(a, b, b2)
err := iter()
undo.Undo()
return err
} else if varA && !varB {
undo := b1.bind(a, b, b2)
err := iter()
undo.Undo()
return err
} else if varB && !varA {
undo := b2.bind(b, a, b1)
err := iter()
undo.Undo()
return err
}
// Sets must not contain unbound variables at this point as we cannot unify
// them. So simply plug both sides (to substitute any bound variables with
// values) and then check for equality.
switch a.Value.(type) {
case ast.Set:
a = b1.Plug(a)
b = b2.Plug(b)
}
if a.Equal(b) {
return iter()
}
return nil
}
func (e *eval) biunifyRef(a, b *ast.Term, b1, b2 *bindings, iter unifyIterator) error {
ref := a.Value.(ast.Ref)
if ref[0].Equal(ast.DefaultRootDocument) {
node := e.compiler.RuleTree.Child(ref[0].Value)
eval := evalTree{
e: e,
ref: ref,
pos: 1,
plugged: ref.Copy(),
bindings: b1,
rterm: b,
rbindings: b2,
node: node,
}
return eval.eval(iter)
}
var term *ast.Term
var termbindings *bindings
if ref[0].Equal(ast.InputRootDocument) {
term = e.input
termbindings = b1
} else {
term, termbindings = b1.apply(ref[0])
if term == ref[0] {
term = nil
}
}
if term == nil {
return nil
}
eval := evalTerm{
e: e,
ref: ref,
pos: 1,
bindings: b1,
term: term,
termbindings: termbindings,
rterm: b,
rbindings: b2,
}
return eval.eval(iter)
}
func (e *eval) biunifyComprehension(a, b *ast.Term, b1, b2 *bindings, swap bool, iter unifyIterator) error {
if e.unknown(a, b1) {
return e.biunifyComprehensionPartial(a, b, b1, b2, swap, iter)
}
value, err := e.buildComprehensionCache(a)
if err != nil {
return err
} else if value != nil {
return e.biunify(value, b, b1, b2, iter)
} else {
e.instr.counterIncr(evalOpComprehensionCacheMiss)
}
switch a := a.Value.(type) {
case *ast.ArrayComprehension:
return e.biunifyComprehensionArray(a, b, b1, b2, iter)
case *ast.SetComprehension:
return e.biunifyComprehensionSet(a, b, b1, b2, iter)
case *ast.ObjectComprehension:
return e.biunifyComprehensionObject(a, b, b1, b2, iter)
}
return internalErr(e.query[e.index].Location, "illegal comprehension type")
}
func (e *eval) buildComprehensionCache(a *ast.Term) (*ast.Term, error) {
index := e.comprehensionIndex(a)
if index == nil {
e.instr.counterIncr(evalOpComprehensionCacheSkip)
return nil, nil
}
cache, ok := e.comprehensionCache.Elem(a)
if !ok {
var err error
switch x := a.Value.(type) {
case *ast.ArrayComprehension:
cache, err = e.buildComprehensionCacheArray(x, index.Keys)
case *ast.SetComprehension:
cache, err = e.buildComprehensionCacheSet(x, index.Keys)
case *ast.ObjectComprehension:
cache, err = e.buildComprehensionCacheObject(x, index.Keys)
default:
err = internalErr(e.query[e.index].Location, "illegal comprehension type")
}
if err != nil {
return nil, err
}
e.comprehensionCache.Set(a, cache)
e.instr.counterIncr(evalOpComprehensionCacheBuild)
} else {
e.instr.counterIncr(evalOpComprehensionCacheHit)
}
values := make([]*ast.Term, len(index.Keys))
for i := range index.Keys {
values[i] = e.bindings.Plug(index.Keys[i])
}
return cache.Get(values), nil
}
func (e *eval) buildComprehensionCacheArray(x *ast.ArrayComprehension, keys []*ast.Term) (*comprehensionCacheElem, error) {
child := e.child(x.Body)
node := newComprehensionCacheElem()
return node, child.Run(func(child *eval) error {
values := make([]*ast.Term, len(keys))
for i := range keys {
values[i] = child.bindings.Plug(keys[i])
}
head := child.bindings.Plug(x.Term)
cached := node.Get(values)
if cached != nil {
cached.Value = cached.Value.(*ast.Array).Append(head)
} else {
node.Put(values, ast.ArrayTerm(head))
}
return nil
})
}
func (e *eval) buildComprehensionCacheSet(x *ast.SetComprehension, keys []*ast.Term) (*comprehensionCacheElem, error) {
child := e.child(x.Body)
node := newComprehensionCacheElem()
return node, child.Run(func(child *eval) error {
values := make([]*ast.Term, len(keys))
for i := range keys {
values[i] = child.bindings.Plug(keys[i])
}
head := child.bindings.Plug(x.Term)
cached := node.Get(values)
if cached != nil {
set := cached.Value.(ast.Set)
set.Add(head)
} else {
node.Put(values, ast.SetTerm(head))
}
return nil
})
}
func (e *eval) buildComprehensionCacheObject(x *ast.ObjectComprehension, keys []*ast.Term) (*comprehensionCacheElem, error) {
child := e.child(x.Body)
node := newComprehensionCacheElem()
return node, child.Run(func(child *eval) error {
values := make([]*ast.Term, len(keys))
for i := range keys {