forked from open-policy-agent/opa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
topdown.go
2278 lines (1908 loc) · 52.1 KB
/
topdown.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 2016 The OPA Authors. All rights reserved.
// Use of this source code is governed by an Apache2
// license that can be found in the LICENSE file.
package topdown
import (
"context"
"fmt"
"strings"
"sync"
"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/pkg/errors"
)
// Topdown stores the state of the evaluation process and contains context
// needed to evaluate queries.
type Topdown struct {
Cancel Cancel
Query ast.Body
Compiler *ast.Compiler
Input ast.Value
Index int
Previous *Topdown
Store storage.Store
Tracer Tracer
Context context.Context
txn storage.Transaction
locals *ast.ValueMap
refs *valueMapStack
cache *contextcache
qid uint64
redos *redoStack
builtins builtins.Cache
userBuiltins map[ast.String]BuiltinFunc
}
// ResetQueryIDs resets the query ID generator. This is only for test purposes.
func ResetQueryIDs() {
qidFactory.Reset()
}
type queryIDFactory struct {
next uint64
mtx sync.Mutex
}
func (f *queryIDFactory) Next() uint64 {
f.mtx.Lock()
defer f.mtx.Unlock()
next := f.next
f.next++
return next
}
func (f *queryIDFactory) Reset() {
f.mtx.Lock()
defer f.mtx.Unlock()
f.next = uint64(1)
}
var qidFactory = &queryIDFactory{
next: uint64(1),
}
type redoStack struct {
events []*redoStackElement
}
type redoStackElement struct {
t *Topdown
evt *Event
}
// New returns a new Topdown object without any bindings.
func New(ctx context.Context, query ast.Body, compiler *ast.Compiler, store storage.Store, txn storage.Transaction) *Topdown {
t := &Topdown{
Context: ctx,
Query: query,
Compiler: compiler,
Store: store,
refs: newValueMapStack(),
txn: txn,
cache: newContextCache(),
qid: qidFactory.Next(),
redos: &redoStack{},
builtins: builtins.Cache{},
userBuiltins: map[ast.String]BuiltinFunc{},
}
t.registerUserFunctions()
return t
}
// Vars represents a set of var bindings.
type Vars map[ast.Var]ast.Value
// Diff returns the var bindings in vs that are not in other.
func (vs Vars) Diff(other Vars) Vars {
result := Vars{}
for k := range vs {
if _, ok := other[k]; !ok {
result[k] = vs[k]
}
}
return result
}
// Equal returns true if vs is equal to other.
func (vs Vars) Equal(other Vars) bool {
return len(vs.Diff(other)) == 0 && len(other.Diff(vs)) == 0
}
// Vars returns bindings for the vars in the current query
func (t *Topdown) Vars() map[ast.Var]ast.Value {
result := map[ast.Var]ast.Value{}
t.locals.Iter(func(k, v ast.Value) bool {
if k, ok := k.(ast.Var); ok {
result[k] = v
}
return false
})
return result
}
// Binding returns the value bound to the given key.
func (t *Topdown) Binding(k ast.Value) ast.Value {
if _, ok := k.(ast.Ref); ok {
return t.refs.Binding(k)
}
return t.locals.Get(k)
}
// Undo represents a binding that can be undone.
type Undo struct {
Key ast.Value
Value ast.Value
Prev *Undo
}
// Bind updates t to include a binding from the key to the value. The return
// value is used to return t to the state before the binding was added.
func (t *Topdown) Bind(key ast.Value, value ast.Value, prev *Undo) *Undo {
if _, ok := key.(ast.Ref); ok {
return t.refs.Bind(key, value, prev)
}
o := t.locals.Get(key)
if t.locals == nil {
t.locals = ast.NewValueMap()
}
t.locals.Put(key, value)
return &Undo{key, o, prev}
}
// Unbind updates t by removing the binding represented by the undo.
func (t *Topdown) Unbind(undo *Undo) {
if undo == nil {
return
}
if _, ok := undo.Key.(ast.Ref); ok {
for u := undo; u != nil; u = u.Prev {
t.refs.Unbind(u)
}
} else {
for u := undo; u != nil; u = u.Prev {
if u.Value != nil {
t.locals.Put(u.Key, u.Value)
} else {
t.locals.Delete(u.Key)
}
}
}
}
// Closure returns a new Topdown object to evaluate query with bindings from t.
func (t *Topdown) Closure(query ast.Body) *Topdown {
cpy := *t
cpy.Query = query
cpy.Previous = t
cpy.Index = 0
cpy.qid = qidFactory.Next()
return &cpy
}
// Child returns a new Topdown object to evaluate query without bindings from t.
func (t *Topdown) Child(query ast.Body) *Topdown {
cpy := t.Closure(query)
cpy.locals = nil
cpy.refs = newValueMapStack()
return cpy
}
// Current returns the current expression to evaluate.
func (t *Topdown) Current() *ast.Expr {
return t.Query[t.Index]
}
// Resolve returns the native Go value referred to by the ref.
func (t *Topdown) Resolve(ref ast.Ref) (interface{}, error) {
if ref.IsNested() {
cpy := make(ast.Ref, len(ref))
for i := range ref {
switch v := ref[i].Value.(type) {
case ast.Ref:
r, err := lookupValue(t, v)
if err != nil {
return nil, err
}
cpy[i] = ast.NewTerm(r)
default:
cpy[i] = ref[i]
}
}
ref = cpy
}
path, err := storage.NewPathForRef(ref)
if err != nil {
return nil, err
}
doc, err := t.Store.Read(t.Context, t.txn, path)
if err != nil {
return nil, err
}
// When the root document is queried we hide the SystemDocumentKey.
if len(path) == 0 {
obj := doc.(map[string]interface{})
tmp := map[string]interface{}{}
for k := range obj {
if k != string(ast.SystemDocumentKey) {
tmp[k] = obj[k]
}
}
doc = tmp
}
return doc, nil
}
// Step returns a new Topdown object to evaluate the next expression.
func (t *Topdown) Step() *Topdown {
cpy := *t
cpy.Index++
return &cpy
}
// WithInput returns a new Topdown object that has the input document set.
func (t *Topdown) WithInput(input ast.Value) *Topdown {
cpy := *t
cpy.Input = input
return &cpy
}
// WithTracer returns a new Topdown object that has a tracer set.
func (t *Topdown) WithTracer(tracer Tracer) *Topdown {
cpy := *t
cpy.Tracer = tracer
return &cpy
}
// WithCancel returns a new Topdown object that has cancellation set.
func (t *Topdown) WithCancel(c Cancel) *Topdown {
cpy := *t
cpy.Cancel = c
return &cpy
}
// currentLocation returns the current expression's location or the first
// fallback that has a location set, otherwise nil.
func (t *Topdown) currentLocation(fallback ...ast.Statement) *ast.Location {
curr := t.Current().Location
if curr != nil {
return curr
}
for i := range fallback {
curr = fallback[i].Loc()
if curr != nil {
return curr
}
}
return nil
}
func (t *Topdown) traceEnter(node interface{}) {
if t.tracingEnabled() {
evt := t.makeEvent(EnterOp, node)
t.flushRedos(evt)
t.Tracer.Trace(t, evt)
}
}
func (t *Topdown) traceExit(node interface{}) {
if t.tracingEnabled() {
evt := t.makeEvent(ExitOp, node)
t.flushRedos(evt)
t.Tracer.Trace(t, evt)
}
}
func (t *Topdown) traceEval(node interface{}) {
if t.tracingEnabled() {
evt := t.makeEvent(EvalOp, node)
t.flushRedos(evt)
t.Tracer.Trace(t, evt)
}
}
func (t *Topdown) traceRedo(node interface{}) {
if t.tracingEnabled() {
evt := t.makeEvent(RedoOp, node)
t.saveRedo(evt)
}
}
func (t *Topdown) traceFail(node interface{}) {
if t.tracingEnabled() {
evt := t.makeEvent(FailOp, node)
t.flushRedos(evt)
t.Tracer.Trace(t, evt)
}
}
func (t *Topdown) tracingEnabled() bool {
return t.Tracer != nil && t.Tracer.Enabled()
}
func (t *Topdown) saveRedo(evt *Event) {
buf := &redoStackElement{
t: t,
evt: evt,
}
// Search stack for redo that this (redo) event should follow.
for len(t.redos.events) > 0 {
idx := len(t.redos.events) - 1
top := t.redos.events[idx]
// Expression redo should follow rule/body redo from the same query.
if evt.HasExpr() {
if top.evt.QueryID == evt.QueryID && (top.evt.HasBody() || top.evt.HasRule()) {
break
}
}
// Rule/body redo should follow expression redo from the parent query.
if evt.HasRule() || evt.HasBody() {
if top.evt.QueryID == evt.ParentID && top.evt.HasExpr() {
break
}
}
// Top of stack can be discarded. This indicates the search terminated
// without producing any more events.
t.redos.events = t.redos.events[:idx]
}
t.redos.events = append(t.redos.events, buf)
}
func (t *Topdown) flushRedos(evt *Event) {
idx := len(t.redos.events) - 1
if idx != -1 {
top := t.redos.events[idx]
if top.evt.QueryID == evt.QueryID {
for _, buf := range t.redos.events {
t.Tracer.Trace(buf.t, buf.evt)
}
}
t.redos.events = nil
}
}
func (t *Topdown) makeEvent(op Op, node interface{}) *Event {
evt := Event{
Op: op,
Node: node,
QueryID: t.qid,
Locals: t.locals.Copy(),
}
if t.Previous != nil {
evt.ParentID = t.Previous.qid
}
return &evt
}
// contextcache stores the result of rule evaluation for a query. The
// contextcache is inherited by child contexts. The contextcache is consulted
// when virtual document references are evaluated. If a miss occurs, the virtual
// document is generated and the contextcache is updated.
type contextcache struct {
partialobjs partialObjDocCache
complete completeDocCache
}
type partialObjDocCache map[*ast.Rule]map[ast.Value]ast.Value
type completeDocCache map[*ast.Rule]ast.Value
func newContextCache() *contextcache {
return &contextcache{
partialobjs: partialObjDocCache{},
complete: completeDocCache{},
}
}
func (c *contextcache) Invalidate() {
c.partialobjs = partialObjDocCache{}
c.complete = completeDocCache{}
}
// Iterator is the interface for processing evaluation results.
type Iterator func(*Topdown) error
// Continue binds key to value in t and calls the iterator. This is a helper
// function for simple cases where a single value (e.g., a variable) needs to be
// bound to a value in order for the evaluation the proceed.
func Continue(t *Topdown, key, value ast.Value, iter Iterator) error {
undo := t.Bind(key, value, nil)
err := iter(t)
t.Unbind(undo)
return err
}
// Eval evaluates the query in t and calls iter once for each set of bindings
// that satisfy all of the expressions in the query.
func Eval(t *Topdown, iter Iterator) error {
t.traceEnter(t.Query)
return eval(t, func(t *Topdown) error {
t.traceExit(t.Query)
if err := iter(t); err != nil {
return err
}
t.traceRedo(t.Query)
return nil
})
}
// Binding defines the interface used to apply term bindings to terms,
// expressions, etc.
type Binding func(ast.Value) ast.Value
// PlugHead returns a copy of head with bound terms substituted for the binding.
func PlugHead(head *ast.Head, binding Binding) *ast.Head {
plugged := *head
if plugged.Key != nil {
plugged.Key = PlugTerm(plugged.Key, binding)
}
if plugged.Value != nil {
plugged.Value = PlugTerm(plugged.Value, binding)
}
return &plugged
}
// PlugExpr returns a copy of expr with bound terms substituted for the binding.
func PlugExpr(expr *ast.Expr, binding Binding) *ast.Expr {
plugged := *expr
switch ts := plugged.Terms.(type) {
case []*ast.Term:
var buf []*ast.Term
buf = append(buf, ts[0])
for _, term := range ts[1:] {
buf = append(buf, PlugTerm(term, binding))
}
plugged.Terms = buf
case *ast.Term:
plugged.Terms = PlugTerm(ts, binding)
default:
panic(fmt.Sprintf("illegal argument: %v", ts))
}
return &plugged
}
// PlugTerm returns a copy of term with bound terms substituted for the binding.
func PlugTerm(term *ast.Term, binding Binding) *ast.Term {
switch v := term.Value.(type) {
case ast.Var:
plugged := *term
plugged.Value = PlugValue(v, binding)
return &plugged
case ast.Ref:
plugged := *term
plugged.Value = PlugValue(v, binding)
return &plugged
case ast.Array:
plugged := *term
plugged.Value = PlugValue(v, binding)
return &plugged
case ast.Object:
plugged := *term
plugged.Value = PlugValue(v, binding)
return &plugged
case *ast.Set:
plugged := *term
plugged.Value = PlugValue(v, binding)
return &plugged
case *ast.ArrayComprehension:
plugged := *term
plugged.Value = PlugValue(v, binding)
return &plugged
default:
if !term.IsGround() {
panic("unreachable")
}
return term
}
}
// PlugValue returns a copy of v with bound terms substituted for the binding.
func PlugValue(v ast.Value, binding func(ast.Value) ast.Value) ast.Value {
switch v := v.(type) {
case ast.Var:
if b := binding(v); b != nil {
return PlugValue(b, binding)
}
return v
case *ast.ArrayComprehension:
b := binding(v)
if b == nil {
return v
}
return b
case ast.Ref:
if b := binding(v); b != nil {
return PlugValue(b, binding)
}
buf := make(ast.Ref, len(v))
buf[0] = v[0]
for i, p := range v[1:] {
buf[i+1] = PlugTerm(p, binding)
}
if b := binding(buf); b != nil {
return PlugValue(b, binding)
}
return buf
case ast.Array:
buf := make(ast.Array, len(v))
for i, e := range v {
buf[i] = PlugTerm(e, binding)
}
return buf
case ast.Object:
buf := make(ast.Object, len(v))
for i, e := range v {
k := PlugTerm(e[0], binding)
v := PlugTerm(e[1], binding)
buf[i] = [...]*ast.Term{k, v}
}
return buf
case *ast.Set:
buf := &ast.Set{}
for _, e := range *v {
buf.Add(PlugTerm(e, binding))
}
return buf
case nil:
return nil
default:
if !v.IsGround() {
panic(fmt.Sprintf("illegal value: %v", v))
}
return v
}
}
// QueryParams defines input parameters for the query interface.
type QueryParams struct {
Context context.Context
Cancel Cancel
Compiler *ast.Compiler
Store storage.Store
Transaction storage.Transaction
Input ast.Value
Tracer Tracer
Metrics metrics.Metrics
Path ast.Ref
}
// NewQueryParams returns a new QueryParams.
func NewQueryParams(ctx context.Context, compiler *ast.Compiler, store storage.Store, txn storage.Transaction, input ast.Value, path ast.Ref) *QueryParams {
return &QueryParams{
Context: ctx,
Compiler: compiler,
Store: store,
Transaction: txn,
Input: input,
Path: path,
}
}
// NewTopdown returns a new Topdown object.
//
// This function will not propagate optional values such as the tracer, input
// document, etc. Those must be set by the caller.
func (q *QueryParams) NewTopdown(query ast.Body) *Topdown {
return New(q.Context, query, q.Compiler, q.Store, q.Transaction).WithCancel(q.Cancel)
}
// QueryResult represents a single query result.
type QueryResult struct {
Result interface{} // Result contains the document referred to by the params Path.
Bindings map[string]interface{} // Bindings contains values for variables in the params Input.
}
func (qr *QueryResult) String() string {
return fmt.Sprintf("[%v %v]", qr.Result, qr.Bindings)
}
// QueryResultSet represents a collection of query results.
type QueryResultSet []*QueryResult
// Undefined returns true if the query did not find any results.
func (qrs QueryResultSet) Undefined() bool {
return len(qrs) == 0
}
// Add inserts a result into the query result set.
func (qrs *QueryResultSet) Add(qr *QueryResult) {
*qrs = append(*qrs, qr)
}
// Query returns the value of the document referred to by the params' path. If
// the params' input contains non-ground terms, there may be multiple query
// results.
func Query(params *QueryParams) (QueryResultSet, error) {
if params.Metrics == nil {
params.Metrics = metrics.New()
}
t, resultVar, requestVars, err := makeTopdown(params)
if err != nil {
return nil, err
}
qrs := QueryResultSet{}
params.Metrics.Timer(metrics.RegoQueryEval).Start()
err = Eval(t, func(t *Topdown) error {
// Gather bindings for vars from the request.
bindings := map[string]interface{}{}
for v := range requestVars {
binding, err := ast.ValueToInterface(PlugValue(v, t.Binding), t)
if err != nil {
return err
}
bindings[v.String()] = binding
}
// Gather binding for result var.
val, err := ast.ValueToInterface(PlugValue(resultVar, t.Binding), t)
if err != nil {
return err
}
// Aggregate results.
qrs.Add(&QueryResult{val, bindings})
return nil
})
params.Metrics.Timer(metrics.RegoQueryEval).Stop()
return qrs, err
}
func makeTopdown(params *QueryParams) (*Topdown, ast.Var, ast.VarSet, error) {
inputVar := ast.VarTerm(ast.WildcardPrefix + "0")
pathVar := ast.VarTerm(ast.WildcardPrefix + "1")
var query ast.Body
params.Metrics.Timer(metrics.RegoQueryCompile).Start()
if params.Input == nil {
query = ast.NewBody(ast.Equality.Expr(ast.NewTerm(params.Path), pathVar))
} else {
// <input> = $0,
// <path> = $1 with input as $0
inputExpr := ast.Equality.Expr(ast.NewTerm(params.Input), inputVar)
pathExpr := ast.Equality.Expr(ast.NewTerm(params.Path), pathVar).
IncludeWith(ast.NewTerm(ast.InputRootRef), inputVar)
query = ast.NewBody(inputExpr, pathExpr)
}
compiled, err := params.Compiler.QueryCompiler().Compile(query)
if err != nil {
return nil, "", nil, err
}
params.Metrics.Timer(metrics.RegoQueryCompile).Stop()
vis := ast.NewVarVisitor().WithParams(ast.VarVisitorParams{
SkipRefHead: true,
SkipClosures: true,
})
ast.Walk(vis, params.Input)
t := params.NewTopdown(compiled).
WithTracer(params.Tracer)
return t, pathVar.Value.(ast.Var), vis.Vars(), nil
}
// Resolver defines the interface for resolving references to base documents to
// native Go values. The native Go value types map to JSON types.
type Resolver interface {
Resolve(ref ast.Ref) (value interface{}, err error)
}
type resolver struct {
context context.Context
store storage.Store
txn storage.Transaction
}
func (r resolver) Resolve(ref ast.Ref) (interface{}, error) {
path, err := storage.NewPathForRef(ref)
if err != nil {
return nil, err
}
return r.store.Read(r.context, r.txn, path)
}
// ResolveRefs returns the value obtained by resolving references to base
// documents.
func ResolveRefs(v ast.Value, t *Topdown) (ast.Value, error) {
result, err := ast.TransformRefs(v, func(r ast.Ref) (ast.Value, error) {
return lookupValue(t, r)
})
if err != nil {
return nil, err
}
return result.(ast.Value), nil
}
// ResolveRefsTerm returns a copy of term obtained by resolving references to
// base documents.
func ResolveRefsTerm(term *ast.Term, t *Topdown) (*ast.Term, error) {
cpy := *term
var err error
cpy.Value, err = ResolveRefs(term.Value, t)
if err != nil {
return nil, err
}
return &cpy, nil
}
func eval(t *Topdown, iter Iterator) error {
if t.Cancel != nil && t.Cancel.Cancelled() {
return &Error{
Code: CancelErr,
Message: "caller cancelled query execution",
}
}
if t.Index >= len(t.Query) {
return iter(t)
}
if len(t.Current().With) > 0 {
return evalWith(t, iter)
}
return evalStep(t, func(t *Topdown) error {
t = t.Step()
return eval(t, iter)
})
}
func evalStep(t *Topdown, iter Iterator) error {
if t.Current().Negated {
return evalNot(t, iter)
}
t.traceEval(t.Current())
// isRedo indicates if the expression's terms are defined at least once. If
// any of the terms are undefined, then the closure below will not run (but
// a Fail event still needs to be emitted).
isRedo := false
err := evalTerms(t, func(t *Topdown) error {
isRedo = true
// isTrue indicates if the expression is true and is used to determine
// if a Fail event should be emitted below.
isTrue := false
err := evalExpr(t, func(t *Topdown) error {
isTrue = true
return iter(t)
})
if err != nil {
return err
}
if !isTrue {
t.traceFail(t.Current())
}
t.traceRedo(t.Current())
return nil
})
if err != nil {
return err
}
if !isRedo {
t.traceFail(t.Current())
}
return nil
}
func evalNot(t *Topdown, iter Iterator) error {
negation := ast.NewBody(t.Current().Complement().NoWith())
child := t.Closure(negation)
t.traceEval(t.Current())
isTrue := false
err := Eval(child, func(*Topdown) error {
isTrue = true
return nil
})
if err != nil {
return err
}
if !isTrue {
return iter(t)
}
t.traceFail(t.Current())
return nil
}
func evalWith(t *Topdown, iter Iterator) error {
curr := t.Current()
pairs := make([][2]*ast.Term, len(curr.With))
for i := range curr.With {
plugged := PlugTerm(curr.With[i].Value, t.Binding)
resolved, err := ResolveRefsTerm(plugged, t)
if err != nil {
return err
}
pairs[i] = [...]*ast.Term{curr.With[i].Target, resolved}
}
input, err := MakeInput(pairs)
if err != nil {
return &Error{
Code: ConflictErr,
Location: curr.Location,
Message: err.Error(),
}
}
cpy := t.WithInput(input)
// All ref bindings added during evaluation of this expression must be
// discarded before moving to the next expression. Push a new binding map
// onto the stack that will be popped below before continuing. Similarly,
// the document caches must be invalidated before continuing.
//
// TODO(tsandall): analyze queries and invalidate only affected caches.
cpy.refs.Push(ast.NewValueMap())
err = evalStep(cpy, func(next *Topdown) error {
next.refs.Pop()
next.cache.Invalidate()
next = next.Step()
return eval(next, iter)
})
if err != nil {
return err
}
if vm := cpy.refs.Peek(); vm != nil {
cpy.refs.Pop()
}
cpy.cache.Invalidate()
return nil
}
func evalExpr(t *Topdown, iter Iterator) error {
expr := PlugExpr(t.Current(), t.Binding)
switch tt := expr.Terms.(type) {
case []*ast.Term:
name := tt[0].Value.(ast.String)
builtin, ok := builtinFunctions[name]
if !ok {
builtin, ok = t.userBuiltins[name]
if !ok {
return unsupportedBuiltinErr(expr.Location)
}
}
return builtin(t, expr, iter)
case *ast.Term:
v := tt.Value
if r, ok := v.(ast.Ref); ok {
var err error
v, err = lookupValue(t, r)
if err != nil {
return err
}
}
if v.Compare(ast.Boolean(false)) != 0 {
if v.IsGround() {
return iter(t)
}
}
return nil
default:
panic(fmt.Sprintf("illegal argument: %v", tt))
}
}
// evalRef evaluates the reference and invokes the iterator for each instance of
// the reference that is defined. The iterator is invoked with bindings for (1)
// all variables found in the reference and (2) the reference itself if that
// reference refers to a virtual document (ditto for nested references).
func evalRef(t *Topdown, ref, path ast.Ref, iter Iterator) error {
// If ref is already bound then invoke iterator immediately. No further
// evaluation has to be done.
if len(path) == 0 && t.Binding(ref) != nil {
return iter(t)
}
if len(ref) == 0 {
if path.HasPrefix(ast.DefaultRootRef) {
return evalRefRec(t, path, iter)
}
if path.HasPrefix(ast.InputRootRef) {
// If no input was supplied, then any references to the input
// are undefined.
if t.Input == nil {
return nil
}
return evalRefRuleResult(t, path, path[1:], t.Input, iter)
}
if v := t.Binding(path[0].Value); v != nil {
return evalRefRuleResult(t, path, path[1:], v, iter)
}
// This should not be reachable.
return fmt.Errorf("unbound ref head: %v", path)
}
head, tail := ref[0], ref[1:]
n, ok := head.Value.(ast.Ref)
if !ok {
path = append(path, head)