forked from open-policy-agent/opa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
compile.go
1851 lines (1602 loc) · 43.4 KB
/
compile.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 ast
import (
"fmt"
"strings"
"github.com/open-policy-agent/opa/util"
)
// CompileErrorLimitDefault is the default number errors a compiler will allow before
// exiting.
const CompileErrorLimitDefault = 10
var errLimitReached = NewError(CompileErr, nil, "error limit reached")
// Compiler contains the state of a compilation process.
type Compiler struct {
// Errors contains errors that occurred during the compilation process.
// If there are one or more errors, the compilation process is considered
// "failed".
Errors Errors
// Modules contains the compiled modules. The compiled modules are the
// output of the compilation process. If the compilation process failed,
// there is no guarantee about the state of the modules.
Modules map[string]*Module
// ModuleTree organizes the modules into a tree where each node is keyed by
// an element in the module's package path. E.g., given modules containing
// the following package directives: "a", "a.b", "a.c", and "a.b", the
// resulting module tree would be:
//
// root
// |
// +--- data (no modules)
// |
// +--- a (1 module)
// |
// +--- b (2 modules)
// |
// +--- c (1 module)
//
ModuleTree *ModuleTreeNode
// RuleTree organizes rules into a tree where each node is keyed by an
// element in the rule's path. The rule path is the concatenation of the
// containing package and the stringified rule name. E.g., given the
// following module:
//
// package ex
// p[1] { true }
// p[2] { true }
// q = true
//
// root
// |
// +--- data (no rules)
// |
// +--- ex (no rules)
// |
// +--- p (2 rules)
// |
// +--- q (1 rule)
RuleTree *TreeNode
// FuncTree organizes user functions into a tree where each node is keyed
// by an element in the logical path to the function. The logical path is
// the concatenations of the containing package and the stringified function
// name. Functions are only located at the lead nodes, each of which have
// exactly 1 function. E.g., given the following module:
//
// package a.b
// p(x) = y { y = x }
// q(x) = y { y = 2*x }
//
// root
// |
// +--- a (no functions)
// |
// +--- b (no functions)
// |
// +--- p
// |
// +--- q
FuncTree *TreeNode
// FunctionMap is a map containing the user defined functions of this
// compiler's modules.
FuncMap map[String][]*Func
// Graph represents the dependencies between rules and funcs (lets call
// them targets). An edge (u,v) is added to the graph if target "u"
// depends on target "v". A target "u" depends on target "v" if target
// "u" refers to the virtual document (or function) defined by target "v".
Graph *Graph
// TypeEnv holds type information for values inferred by the compiler.
TypeEnv *TypeEnv
generatedVars map[*Module]VarSet
moduleLoader ModuleLoader
ruleIndices *util.HashMap
stages []func()
maxErrs int
}
// QueryContext contains contextual information for running an ad-hoc query.
//
// Ad-hoc queries can be run in the context of a package and imports may be
// included to provide concise access to data.
type QueryContext struct {
Package *Package
Imports []*Import
Input Value
}
// NewQueryContext returns a new QueryContext object.
func NewQueryContext() *QueryContext {
return &QueryContext{}
}
// InputDefined returns true if the input document is defined in qc.
func (qc *QueryContext) InputDefined() bool {
return qc != nil && qc.Input != nil
}
// WithPackage sets the pkg on qc.
func (qc *QueryContext) WithPackage(pkg *Package) *QueryContext {
if qc == nil {
qc = NewQueryContext()
}
qc.Package = pkg
return qc
}
// WithImports sets the imports on qc.
func (qc *QueryContext) WithImports(imports []*Import) *QueryContext {
if qc == nil {
qc = NewQueryContext()
}
qc.Imports = imports
return qc
}
// WithInput sets the input on qc.
func (qc *QueryContext) WithInput(input Value) *QueryContext {
if qc == nil {
qc = NewQueryContext()
}
qc.Input = input
return qc
}
// Copy returns a deep copy of qc.
func (qc *QueryContext) Copy() *QueryContext {
if qc == nil {
return nil
}
cpy := *qc
if cpy.Package != nil {
cpy.Package = qc.Package.Copy()
}
cpy.Imports = make([]*Import, len(qc.Imports))
for i := range qc.Imports {
cpy.Imports[i] = qc.Imports[i].Copy()
}
return &cpy
}
// QueryCompiler defines the interface for compiling ad-hoc queries.
type QueryCompiler interface {
// Compile should be called to compile ad-hoc queries. The return value is
// the compiled version of the query.
Compile(q Body) (Body, error)
// TypeEnv returns the type environment built after running type checking
// on the query.
TypeEnv() *TypeEnv
// WithContext sets the QueryContext on the QueryCompiler. Subsequent calls
// to Compile will take the QueryContext into account.
WithContext(qctx *QueryContext) QueryCompiler
}
// NewCompiler returns a new empty compiler.
func NewCompiler() *Compiler {
c := &Compiler{
Modules: map[string]*Module{},
TypeEnv: NewTypeEnv(),
FuncMap: map[String][]*Func{},
generatedVars: map[*Module]VarSet{},
ruleIndices: util.NewHashMap(func(a, b util.T) bool {
r1, r2 := a.(Ref), b.(Ref)
return r1.Equal(r2)
}, func(x util.T) int {
return x.(Ref).Hash()
}),
maxErrs: CompileErrorLimitDefault,
}
c.ModuleTree = NewModuleTree(nil)
c.RuleTree = NewRuleTree(c.ModuleTree)
c.FuncTree = NewFuncTree(c.ModuleTree)
checker := newTypeChecker()
c.TypeEnv = checker.checkLanguageBuiltins()
c.stages = []func(){
c.resolveAllRefs,
c.setModuleTree,
c.setRuleTree,
c.setFuncTree,
c.setGraph,
c.rewriteRefsInHead,
c.checkWithModifiers,
c.checkRuleConflicts,
c.checkSafetyFuncHeads,
c.checkSafetyFuncBodies,
c.checkSafetyRuleHeads,
c.checkSafetyRuleBodies,
c.checkRecursion,
c.checkTypes,
c.buildRuleIndices,
}
return c
}
// SetErrorLimit sets the number of errors the compiler can encounter before it
// quits. Zero or a negative number indicates no limit.
func (c *Compiler) SetErrorLimit(limit int) *Compiler {
c.maxErrs = limit
return c
}
// QueryCompiler returns a new QueryCompiler object.
func (c *Compiler) QueryCompiler() QueryCompiler {
return newQueryCompiler(c)
}
// Compile runs the compilation process on the input modules. The compiled
// version of the modules and associated data structures are stored on the
// compiler. If the compilation process fails for any reason, the compiler will
// contain a slice of errors.
func (c *Compiler) Compile(modules map[string]*Module) {
c.Modules = make(map[string]*Module, len(modules))
for k, v := range modules {
c.Modules[k] = v.Copy()
}
c.compile()
}
// Failed returns true if a compilation error has been encountered.
func (c *Compiler) Failed() bool {
return len(c.Errors) > 0
}
// GetRulesExact returns a slice of rules referred to by the reference.
//
// E.g., given the following module:
//
// package a.b.c
//
// p[k] = v { ... } # rule1
// p[k1] = v1 { ... } # rule2
//
// The following calls yield the rules on the right.
//
// GetRulesExact("data.a.b.c.p") => [rule1, rule2]
// GetRulesExact("data.a.b.c.p.x") => nil
// GetRulesExact("data.a.b.c") => nil
func (c *Compiler) GetRulesExact(ref Ref) (rules []*Rule) {
node := c.RuleTree
for _, x := range ref {
if node = node.Child(x.Value); node == nil {
return nil
}
}
return extractRules(node.Values)
}
// GetRulesForVirtualDocument returns a slice of rules that produce the virtual
// document referred to by the reference.
//
// E.g., given the following module:
//
// package a.b.c
//
// p[k] = v { ... } # rule1
// p[k1] = v1 { ... } # rule2
//
// The following calls yield the rules on the right.
//
// GetRulesForVirtualDocument("data.a.b.c.p") => [rule1, rule2]
// GetRulesForVirtualDocument("data.a.b.c.p.x") => [rule1, rule2]
// GetRulesForVirtualDocument("data.a.b.c") => nil
func (c *Compiler) GetRulesForVirtualDocument(ref Ref) (rules []*Rule) {
node := c.RuleTree
for _, x := range ref {
if node = node.Child(x.Value); node == nil {
return nil
}
if len(node.Values) > 0 {
return extractRules(node.Values)
}
}
return extractRules(node.Values)
}
// GetRulesWithPrefix returns a slice of rules that share the prefix ref.
//
// E.g., given the following module:
//
// package a.b.c
//
// p[x] = y { ... } # rule1
// p[k] = v { ... } # rule2
// q { ... } # rule3
//
// The following calls yield the rules on the right.
//
// GetRulesWithPrefix("data.a.b.c.p") => [rule1, rule2]
// GetRulesWithPrefix("data.a.b.c.p.a") => nil
// GetRulesWithPrefix("data.a.b.c") => [rule1, rule2, rule3]
func (c *Compiler) GetRulesWithPrefix(ref Ref) (rules []*Rule) {
node := c.RuleTree
for _, x := range ref {
if node = node.Child(x.Value); node == nil {
return nil
}
}
var acc func(node *TreeNode)
acc = func(node *TreeNode) {
rules = append(rules, extractRules(node.Values)...)
for _, child := range node.Children {
if child.Hide {
continue
}
acc(child)
}
}
acc(node)
return rules
}
func extractRules(s []util.T) (rules []*Rule) {
for _, r := range s {
rules = append(rules, r.(*Rule))
}
return rules
}
// GetRules returns a slice of rules that are referred to by ref.
//
// E.g., given the following module:
//
// package a.b.c
//
// p[x] = y { q[x] = y; ... } # rule1
// q[x] = y { ... } # rule2
//
// The following calls yield the rules on the right.
//
// GetRules("data.a.b.c.p") => [rule1]
// GetRules("data.a.b.c.p.x") => [rule1]
// GetRules("data.a.b.c.q") => [rule2]
// GetRules("data.a.b.c") => [rule1, rule2]
// GetRules("data.a.b.d") => nil
func (c *Compiler) GetRules(ref Ref) (rules []*Rule) {
set := map[*Rule]struct{}{}
for _, rule := range c.GetRulesForVirtualDocument(ref) {
set[rule] = struct{}{}
}
for _, rule := range c.GetRulesWithPrefix(ref) {
set[rule] = struct{}{}
}
for rule := range set {
rules = append(rules, rule)
}
return rules
}
// GetFunc returns the function referred to by name.
func (c *Compiler) GetFunc(name String) []*Func {
if fn, ok := c.FuncMap[name]; ok {
return fn
}
return nil
}
// GetAllFuncs returns a map of functions that this compiler has discovered.
func (c *Compiler) GetAllFuncs() map[String][]*Func {
cpy := map[String][]*Func{}
for _, fn := range c.FuncMap {
var fns []*Func
for _, f := range fn {
fns = append(fns, f.Copy())
}
cpy[fn[0].PathString()] = fns
}
return cpy
}
// RuleIndex returns a RuleIndex built for the rule set referred to by path.
// The path must refer to the rule set exactly, i.e., given a rule set at path
// data.a.b.c.p, refs data.a.b.c.p.x and data.a.b.c would not return a
// RuleIndex built for the rule.
func (c *Compiler) RuleIndex(path Ref) RuleIndex {
r, ok := c.ruleIndices.Get(path)
if !ok {
return nil
}
return r.(RuleIndex)
}
// ModuleLoader defines the interface that callers can implement to enable lazy
// loading of modules during compilation.
type ModuleLoader func(resolved map[string]*Module) (parsed map[string]*Module, err error)
// WithModuleLoader sets f as the ModuleLoader on the compiler.
//
// The compiler will invoke the ModuleLoader after resolving all references in
// the current set of input modules. The ModuleLoader can return a new
// collection of parsed modules that are to be included in the compilation
// process. This process will repeat until the ModuleLoader returns an empty
// collection or an error. If an error is returned, compilation will stop
// immediately.
func (c *Compiler) WithModuleLoader(f ModuleLoader) *Compiler {
c.moduleLoader = f
return c
}
// buildRuleIndices constructs indices for rules.
func (c *Compiler) buildRuleIndices() {
c.RuleTree.DepthFirst(func(node *TreeNode) bool {
if len(node.Values) == 0 {
return false
}
index := newBaseDocEqIndex(func(ref Ref) bool {
return len(c.GetRules(ref.GroundPrefix())) > 0
})
if rules := extractRules(node.Values); index.Build(rules) {
c.ruleIndices.Put(rules[0].Path(), index)
}
return false
})
}
// checkRecursion ensures that there are no recursive definitions, i.e., there are
// no cycles in the Graph.
func (c *Compiler) checkRecursion() {
eq := func(a, b util.T) bool {
ar, aok := a.(*Rule)
br, bok := b.(*Rule)
if aok && bok {
return ar == br
}
af, aok := a.(*Func)
bf, bok := b.(*Func)
return aok && bok && af == bf
}
c.RuleTree.DepthFirst(func(node *TreeNode) bool {
for _, rule := range node.Values {
r := rule.(*Rule)
c.checkSelfPath(RuleTypeName, r.Loc(), eq, r, r)
}
return false
})
c.FuncTree.DepthFirst(func(node *TreeNode) bool {
for _, fn := range node.Values {
f := fn.(*Func)
c.checkSelfPath(FuncTypeName, f.Loc(), eq, f, f)
}
return false
})
}
func (c *Compiler) checkSelfPath(t string, loc *Location, eq func(a, b util.T) bool, a, b util.T) {
tr := newgraphTraversal(c.Graph)
if p := util.DFSPath(tr, eq, a, b); len(p) > 0 {
n := []string{}
for _, x := range p {
n = append(n, astNodeToString(x))
}
c.err(NewError(RecursionErr, loc, "%v %v is recursive: %v", t, astNodeToString(a), strings.Join(n, " -> ")))
}
}
func astNodeToString(x interface{}) string {
switch x := x.(type) {
case *Rule:
return string(x.Head.Name)
case *Func:
return string(x.Head.Name)
default:
panic("not reached")
}
}
// checkRuleConflicts ensures that rules definitions are not in conflict.
func (c *Compiler) checkRuleConflicts() {
c.RuleTree.DepthFirst(func(node *TreeNode) bool {
if len(node.Values) == 0 {
return false
}
kinds := map[DocKind]struct{}{}
defaultRules := 0
for _, rule := range node.Values {
r := rule.(*Rule)
kinds[r.Head.DocKind()] = struct{}{}
if r.Default {
defaultRules++
}
}
name := Var(node.Key.(String))
if len(kinds) > 1 {
c.err(NewError(TypeErr, node.Values[0].(*Rule).Loc(), "conflicting rules named %v found", name))
}
if defaultRules > 1 {
c.err(NewError(TypeErr, node.Values[0].(*Rule).Loc(), "multiple default rules named %s found", name))
}
return false
})
c.ModuleTree.DepthFirst(func(node *ModuleTreeNode) bool {
for _, mod := range node.Modules {
for _, rule := range mod.Rules {
for _, fn := range mod.Funcs {
if rule.Head.Name.Equal(fn.Head.Name) {
msg := fmt.Sprintf("rule defined at %v conflicts with function defined at %v", rule.Loc(), fn.Loc())
c.err(NewError(CompileErr, mod.Package.Loc(), msg))
}
}
if childNode, ok := node.Children[String(rule.Head.Name)]; ok {
for _, childMod := range childNode.Modules {
msg := fmt.Sprintf("%v conflicts with rule defined at %v", childMod.Package, rule.Loc())
c.err(NewError(TypeErr, mod.Package.Loc(), msg))
}
}
}
}
return false
})
}
// checkSafetyRuleBodies ensures that variables appearing in negated expressions or non-target
// positions of built-in expressions will be bound when evaluating the rule from left
// to right, re-ordering as necessary.
func (c *Compiler) checkSafetyRuleBodies() {
for _, m := range c.Modules {
safe := ReservedVars.Copy()
WalkRules(m, func(r *Rule) bool {
r.Body = c.checkBodySafety(safe, m, r.Body, r.Loc())
return false
})
}
}
func (c *Compiler) checkSafetyFuncBodies() {
for _, m := range c.Modules {
safe := ReservedVars.Copy()
WalkFuncs(m, func(f *Func) bool {
s := safe.Copy()
s.Update(f.Head.ArgVars())
f.Body = c.checkBodySafety(s, m, f.Body, f.Loc())
return false
})
}
}
func (c *Compiler) checkBodySafety(safe VarSet, m *Module, b Body, l *Location) Body {
reordered, unsafe := reorderBodyForSafety(safe, b)
if len(unsafe) != 0 {
for v := range unsafe.Vars() {
if !c.generatedVars[m].Contains(v) {
c.err(NewError(UnsafeVarErr, l, "%v %v is unsafe", VarTypeName, v))
}
}
return b
}
return reordered
}
var safetyCheckVarVisitorParams = VarVisitorParams{
SkipClosures: true,
}
// checkSafetyRuleHeads ensures that variables appearing in the head of a
// rule also appear in the body.
func (c *Compiler) checkSafetyRuleHeads() {
for _, m := range c.Modules {
WalkRules(m, func(r *Rule) bool {
unsafe := r.Head.Vars().Diff(r.Body.Vars(safetyCheckVarVisitorParams))
for v := range unsafe {
if !c.generatedVars[m].Contains(v) {
c.err(NewError(UnsafeVarErr, r.Loc(), "%v %v is unsafe", VarTypeName, v))
}
}
return false
})
}
}
func (c *Compiler) checkSafetyFuncHeads() {
for _, m := range c.Modules {
WalkFuncs(m, func(f *Func) bool {
vars := f.Body.Vars(safetyCheckVarVisitorParams)
vars.Update(f.Head.ArgVars())
unsafe := f.Head.OutVars().Diff(vars)
for v := range unsafe {
if !c.generatedVars[m].Contains(v) {
c.err(NewError(UnsafeVarErr, f.Loc(), "%v %v is unsafe", VarTypeName, v))
}
}
return false
})
}
}
// checkTypes runs the type checker on all rules and user functions. The type
// checker builds a TypeEnv that is stored on the compiler.
func (c *Compiler) checkTypes() {
// Recursion is caught in earlier step, so this cannot fail.
sorted, _ := c.Graph.Sort()
checker := newTypeChecker()
env, errs := checker.CheckTypes(c.TypeEnv, sorted)
for _, err := range errs {
c.err(err)
}
c.TypeEnv = env
}
// checkWithModifiers ensures that with modifier values do not contain
// references or closures.
func (c *Compiler) checkWithModifiers() {
for _, m := range c.Modules {
wc := newWithModifierChecker()
for _, err := range wc.Check(m) {
c.err(err)
}
}
}
func (c *Compiler) compile() {
defer func() {
if r := recover(); r != nil && r != errLimitReached {
panic(r)
}
}()
for _, fn := range c.stages {
if fn(); c.Failed() {
return
}
}
}
func (c *Compiler) err(err *Error) {
if c.maxErrs > 0 && len(c.Errors) >= c.maxErrs {
c.Errors = append(c.Errors, errLimitReached)
panic(errLimitReached)
}
c.Errors = append(c.Errors, err)
}
func (c *Compiler) getExports() (*util.HashMap, *util.HashMap) {
rules := util.NewHashMap(func(a, b util.T) bool {
r1 := a.(Ref)
r2 := a.(Ref)
return r1.Equal(r2)
}, func(v util.T) int {
return v.(Ref).Hash()
})
funcs := rules.Copy()
for _, mod := range c.Modules {
rv, ok := rules.Get(mod.Package.Path)
if !ok {
rv = []Var{}
}
rvs := rv.([]Var)
fv, ok := funcs.Get(mod.Package.Path)
if !ok {
fv = []*Func{}
}
fvs := fv.([]*Func)
for _, rule := range mod.Rules {
rvs = append(rvs, rule.Head.Name)
}
for _, fn := range mod.Funcs {
fvs = append(fvs, fn)
}
rules.Put(mod.Package.Path, rvs)
funcs.Put(mod.Package.Path, fvs)
}
return rules, funcs
}
// resolveAllRefs resolves references in expressions to their fully qualified values.
//
// For instance, given the following module:
//
// package a.b
// import data.foo.bar
// p[x] { bar[_] = x }
//
// The reference "bar[_]" would be resolved to "data.foo.bar[_]".
func (c *Compiler) resolveAllRefs() {
rules, funcs := c.getExports()
for _, mod := range c.Modules {
var ruleExports []Var
if x, ok := rules.Get(mod.Package.Path); ok {
ruleExports = x.([]Var)
}
var funcExports []*Func
if x, ok := funcs.Get(mod.Package.Path); ok {
funcExports = x.([]*Func)
}
globals := getGlobals(mod.Package, ruleExports, funcExports, mod.Imports)
WalkRules(mod, func(rule *Rule) bool {
resolveRefsInRule(globals, rule)
return false
})
WalkFuncs(mod, func(fn *Func) bool {
resolveRefsInFunc(globals, fn)
path := fn.PathString()
c.FuncMap[path] = append(c.FuncMap[path], fn)
return false
})
// Once imports have been resolved, they are no longer needed.
mod.Imports = nil
}
for _, mod := range c.Modules {
visitor := NewGenericVisitor(func(x interface{}) bool {
// Walk terms in order to provide more detailed location
// information.
switch x := x.(type) {
case *Term:
switch v := x.Value.(type) {
case Ref:
if _, ok := c.FuncMap[String(v.String())]; ok {
c.err(&Error{
Code: CompileErr,
Message: x.Location.Format("%v refers to a known builtin but does not call it", string(x.Location.Text)),
})
}
}
}
return false
})
Walk(visitor, mod)
}
if c.moduleLoader != nil {
parsed, err := c.moduleLoader(c.Modules)
if err != nil {
c.err(NewError(CompileErr, nil, err.Error()))
return
}
if len(parsed) == 0 {
return
}
for id, module := range parsed {
c.Modules[id] = module
}
c.resolveAllRefs()
}
}
// rewriteTermsInHead will rewrite rules so that the head does not contain any
// terms that require evaluation (e.g., refs or comprehensions). If the key or
// value contains or more of these terms, the key or value will be moved into
// the body and assigned to a new variable. The new variable will replace the
// key or value in the head.
//
// For instance, given the following rule:
//
// p[{"foo": data.foo[i]}] { i < 100 }
//
// The rule would be re-written as:
//
// p[__local0__] { i < 100; __local0__ = {"foo": data.foo[i]} }
func (c *Compiler) rewriteRefsInHead() {
for _, mod := range c.Modules {
generator := newLocalVarGenerator(mod)
WalkRules(mod, func(rule *Rule) bool {
if rule.Head.Key != nil {
found := false
vis := NewGenericVisitor(func(x interface{}) bool {
if found {
return true
}
switch x.(type) {
case Ref, *ArrayComprehension, *ObjectComprehension, *SetComprehension:
found = true
return true
}
return false
})
Walk(vis, rule.Head.Key)
if found {
// Replace rule key with generated var
key := rule.Head.Key
local := generator.Generate()
term := &Term{Value: local}
rule.Head.Key = term
expr := Equality.Expr(term, key)
expr.Location = rule.Loc()
rule.Body.Append(expr)
}
}
if rule.Head.Value != nil {
found := false
vis := NewGenericVisitor(func(x interface{}) bool {
if found {
return true
}
switch x.(type) {
case Ref, *ArrayComprehension, *ObjectComprehension, *SetComprehension:
found = true
return true
}
return false
})
Walk(vis, rule.Head.Value)
if found {
// Replace rule value with generated var
value := rule.Head.Value
local := generator.Generate()
term := &Term{Value: local}
rule.Head.Value = term
expr := Equality.Expr(term, value)
expr.Location = rule.Loc()
rule.Body.Append(expr)
}
}
return false
})
c.generatedVars[mod] = generator.Generated()
}
}
func (c *Compiler) setModuleTree() {
c.ModuleTree = NewModuleTree(c.Modules)
}
func (c *Compiler) setRuleTree() {
c.RuleTree = NewRuleTree(c.ModuleTree)
}
func (c *Compiler) setFuncTree() {
c.FuncTree = NewFuncTree(c.ModuleTree)
}
func (c *Compiler) setGraph() {
c.Graph = NewGraph(c.Modules, c.GetRules, c.GetFunc)
}
type queryCompiler struct {
compiler *Compiler
qctx *QueryContext
typeEnv *TypeEnv
}
func newQueryCompiler(compiler *Compiler) QueryCompiler {
qc := &queryCompiler{
compiler: compiler,
qctx: nil,
}
return qc
}
func (qc *queryCompiler) WithContext(qctx *QueryContext) QueryCompiler {
qc.qctx = qctx
return qc
}
func (qc *queryCompiler) Compile(query Body) (Body, error) {
stages := []func(*QueryContext, Body) (Body, error){
qc.resolveRefs,
qc.checkWithModifiers,
qc.checkSafety,
qc.checkTypes,
}
qctx := qc.qctx.Copy()
for _, s := range stages {
var err error
if query, err = s(qctx, query); err != nil {
if errs, ok := err.(Errors); ok {
if qc.compiler.maxErrs > 0 && len(errs) > qc.compiler.maxErrs {
err = append(errs[:qc.compiler.maxErrs], errLimitReached)
}
}
return nil, err
}
}
return query, nil
}
func (qc *queryCompiler) TypeEnv() *TypeEnv {
return qc.typeEnv
}
func (qc *queryCompiler) resolveRefs(qctx *QueryContext, body Body) (Body, error) {
var globals map[Var]Ref
if qctx != nil && qctx.Package != nil {
var ruleExports []Var
rules, funcs := qc.compiler.getExports()
if exist, ok := rules.Get(qctx.Package.Path); ok {
ruleExports = exist.([]Var)
}
var funcExports []*Func
if exist, ok := funcs.Get(qctx.Package.Path); ok {
funcExports = exist.([]*Func)
}
globals = getGlobals(qctx.Package, ruleExports, funcExports, qc.qctx.Imports)
qctx.Imports = nil
}
return resolveRefsInBody(globals, body), nil
}
func (qc *queryCompiler) checkSafety(_ *QueryContext, body Body) (Body, error) {
safe := ReservedVars.Copy()
reordered, unsafe := reorderBodyForSafety(safe, body)
if len(unsafe) != 0 {
var err Errors
for v := range unsafe.Vars() {
err = append(err, NewError(UnsafeVarErr, body.Loc(), "%v %v is unsafe", VarTypeName, v))
}
return nil, err
}
return reordered, nil
}
func (qc *queryCompiler) checkTypes(qctx *QueryContext, body Body) (Body, error) {
var errs Errors