-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
compile.go
3789 lines (3295 loc) · 99.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"
"sort"
"strconv"
"strings"
"github.com/open-policy-agent/opa/metrics"
"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
// Graph contains dependencies between rules. An edge (u,v) is added to the
// graph if rule 'u' refers to the virtual document defined by 'v'.
Graph *Graph
// TypeEnv holds type information for values inferred by the compiler.
TypeEnv *TypeEnv
// RewrittenVars is a mapping of variables that have been rewritten
// with the key being the generated name and value being the original.
RewrittenVars map[Var]Var
localvargen *localVarGenerator
moduleLoader ModuleLoader
ruleIndices *util.HashMap
stages []struct {
name string
metricName string
f func()
}
maxErrs int
sorted []string // list of sorted module names
pathExists func([]string) (bool, error)
after map[string][]CompilerStageDefinition
metrics metrics.Metrics
capabilities *Capabilities // user-supplied capabilities
builtins map[string]*Builtin // universe of built-in functions
customBuiltins map[string]*Builtin // user-supplied custom built-in functions (deprecated: use capabilities)
unsafeBuiltinsMap map[string]struct{} // user-supplied set of unsafe built-ins functions to block (deprecated: use capabilities)
comprehensionIndices map[*Term]*ComprehensionIndex // comprehension key index
initialized bool // indicates if init() has been called
}
// CompilerStage defines the interface for stages in the compiler.
type CompilerStage func(*Compiler) *Error
// CompilerStageDefinition defines a compiler stage
type CompilerStageDefinition struct {
Name string
MetricName string
Stage CompilerStage
}
// 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
}
// NewQueryContext returns a new QueryContext object.
func NewQueryContext() *QueryContext {
return &QueryContext{}
}
// 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
}
// 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
// WithUnsafeBuiltins sets the built-in functions to treat as unsafe and not
// allow inside of queries. By default the query compiler inherits the
// compiler's unsafe built-in functions. This function allows callers to
// override that set. If an empty (non-nil) map is provided, all built-ins
// are allowed.
WithUnsafeBuiltins(unsafe map[string]struct{}) QueryCompiler
// WithStageAfter registers a stage to run during query compilation after
// the named stage.
WithStageAfter(after string, stage QueryCompilerStageDefinition) QueryCompiler
// RewrittenVars maps generated vars in the compiled query to vars from the
// parsed query. For example, given the query "input := 1" the rewritten
// query would be "__local0__ = 1". The mapping would then be {__local0__: input}.
RewrittenVars() map[Var]Var
// ComprehensionIndex returns an index data structure for the given comprehension
// term. If no index is found, returns nil.
ComprehensionIndex(term *Term) *ComprehensionIndex
}
// QueryCompilerStage defines the interface for stages in the query compiler.
type QueryCompilerStage func(QueryCompiler, Body) (Body, error)
// QueryCompilerStageDefinition defines a QueryCompiler stage
type QueryCompilerStageDefinition struct {
Name string
MetricName string
Stage QueryCompilerStage
}
const compileStageMetricPrefex = "ast_compile_stage_"
// NewCompiler returns a new empty compiler.
func NewCompiler() *Compiler {
c := &Compiler{
Modules: map[string]*Module{},
TypeEnv: NewTypeEnv(),
RewrittenVars: map[Var]Var{},
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,
after: map[string][]CompilerStageDefinition{},
unsafeBuiltinsMap: map[string]struct{}{},
comprehensionIndices: map[*Term]*ComprehensionIndex{},
}
c.ModuleTree = NewModuleTree(nil)
c.RuleTree = NewRuleTree(c.ModuleTree)
c.stages = []struct {
name string
metricName string
f func()
}{
// Reference resolution should run first as it may be used to lazily
// load additional modules. If any stages run before resolution, they
// need to be re-run after resolution.
{"ResolveRefs", "compile_stage_resolve_refs", c.resolveAllRefs},
{"SetModuleTree", "compile_stage_set_module_tree", c.setModuleTree},
{"SetRuleTree", "compile_stage_set_rule_tree", c.setRuleTree},
// The local variable generator must be initialized after references are
// resolved and the dynamic module loader has run but before subsequent
// stages that need to generate variables.
{"InitLocalVarGen", "compile_stage_init_local_var_gen", c.initLocalVarGen},
{"RewriteLocalVars", "compile_stage_rewrite_local_vars", c.rewriteLocalVars},
{"RewriteExprTerms", "compile_stage_rewrite_expr_terms", c.rewriteExprTerms},
{"SetGraph", "compile_stage_set_graph", c.setGraph},
{"RewriteComprehensionTerms", "compile_stage_rewrite_comprehension_terms", c.rewriteComprehensionTerms},
{"RewriteRefsInHead", "compile_stage_rewrite_refs_in_head", c.rewriteRefsInHead},
{"RewriteWithValues", "compile_stage_rewrite_with_values", c.rewriteWithModifiers},
{"CheckRuleConflicts", "compile_stage_check_rule_conflicts", c.checkRuleConflicts},
{"CheckUndefinedFuncs", "compile_stage_check_undefined_funcs", c.checkUndefinedFuncs},
{"CheckSafetyRuleHeads", "compile_stage_check_safety_rule_heads", c.checkSafetyRuleHeads},
{"CheckSafetyRuleBodies", "compile_stage_check_safety_rule_bodies", c.checkSafetyRuleBodies},
{"RewriteEquals", "compile_stage_rewrite_equals", c.rewriteEquals},
{"RewriteDynamicTerms", "compile_stage_rewrite_dynamic_terms", c.rewriteDynamicTerms},
{"CheckRecursion", "compile_stage_check_recursion", c.checkRecursion},
{"CheckTypes", "compile_stage_check_types", c.checkTypes},
{"CheckUnsafeBuiltins", "compile_state_check_unsafe_builtins", c.checkUnsafeBuiltins},
{"BuildRuleIndices", "compile_stage_rebuild_indices", c.buildRuleIndices},
{"BuildComprehensionIndices", "compile_stage_rebuild_comprehension_indices", c.buildComprehensionIndices},
}
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
}
// WithPathConflictsCheck enables base-virtual document conflict
// detection. The compiler will check that rules don't overlap with
// paths that exist as determined by the provided callable.
func (c *Compiler) WithPathConflictsCheck(fn func([]string) (bool, error)) *Compiler {
c.pathExists = fn
return c
}
// WithStageAfter registers a stage to run during compilation after
// the named stage.
func (c *Compiler) WithStageAfter(after string, stage CompilerStageDefinition) *Compiler {
c.after[after] = append(c.after[after], stage)
return c
}
// WithMetrics will set a metrics.Metrics and be used for profiling
// the Compiler instance.
func (c *Compiler) WithMetrics(metrics metrics.Metrics) *Compiler {
c.metrics = metrics
return c
}
// WithCapabilities sets capabilities to enable during compilation. Capabilities allow the caller
// to specify the set of built-in functions available to the policy. In the future, capabilities
// may be able to restrict access to other language features. Capabilities allow callers to check
// if policies are compatible with a particular version of OPA. If policies are a compiled for a
// specific version of OPA, there is no guarantee that _this_ version of OPA can evaluate them
// successfully.
func (c *Compiler) WithCapabilities(capabilities *Capabilities) *Compiler {
c.capabilities = capabilities
return c
}
// WithBuiltins is deprecated. Use WithCapabilities instead.
func (c *Compiler) WithBuiltins(builtins map[string]*Builtin) *Compiler {
c.customBuiltins = make(map[string]*Builtin)
for k, v := range builtins {
c.customBuiltins[k] = v
}
return c
}
// WithUnsafeBuiltins is deprecated. Use WithCapabilities instead.
func (c *Compiler) WithUnsafeBuiltins(unsafeBuiltins map[string]struct{}) *Compiler {
for name := range unsafeBuiltins {
c.unsafeBuiltinsMap[name] = struct{}{}
}
return c
}
// QueryCompiler returns a new QueryCompiler object.
func (c *Compiler) QueryCompiler() QueryCompiler {
c.init()
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.init()
c.Modules = make(map[string]*Module, len(modules))
for k, v := range modules {
c.Modules[k] = v.Copy()
c.sorted = append(c.sorted, k)
}
sort.Strings(c.sorted)
c.compile()
}
// Failed returns true if a compilation error has been encountered.
func (c *Compiler) Failed() bool {
return len(c.Errors) > 0
}
// ComprehensionIndex returns a data structure specifying how to index comprehension
// results so that callers do not have to recompute the comprehension more than once.
// If no index is found, returns nil.
func (c *Compiler) ComprehensionIndex(term *Term) *ComprehensionIndex {
return c.comprehensionIndices[term]
}
// GetArity returns the number of args a function referred to by ref takes. If
// ref refers to built-in function, the built-in declaration is consulted,
// otherwise, the ref is used to perform a ruleset lookup.
func (c *Compiler) GetArity(ref Ref) int {
if bi := c.builtins[ref.String()]; bi != nil {
return len(bi.Decl.Args())
}
rules := c.GetRulesExact(ref)
if len(rules) == 0 {
return -1
}
return len(rules[0].Head.Args)
}
// 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
}
// GetRulesDynamic returns a slice of rules that could be referred to by a ref.
// When parts of the ref are statically known, we use that information to narrow
// down which rules the ref could refer to, but in the most general case this
// will be an over-approximation.
//
// E.g., given the following modules:
//
// package a.b.c
//
// r1 = 1 # rule1
//
// and:
//
// package a.d.c
//
// r2 = 2 # rule2
//
// The following calls yield the rules on the right.
//
// GetRulesDynamic("data.a[x].c[y]") => [rule1, rule2]
// GetRulesDynamic("data.a[x].c.r2") => [rule2]
// GetRulesDynamic("data.a.b[x][y]") => [rule1]
func (c *Compiler) GetRulesDynamic(ref Ref) (rules []*Rule) {
node := c.RuleTree
set := map[*Rule]struct{}{}
var walk func(node *TreeNode, i int)
walk = func(node *TreeNode, i int) {
if i >= len(ref) {
// We've reached the end of the reference and want to collect everything
// under this "prefix".
node.DepthFirst(func(descendant *TreeNode) bool {
insertRules(set, descendant.Values)
return descendant.Hide
})
} else if i == 0 || IsConstant(ref[i].Value) {
// The head of the ref is always grounded. In case another part of the
// ref is also grounded, we can lookup the exact child. If it's not found
// we can immediately return...
if child := node.Child(ref[i].Value); child == nil {
return
} else if len(child.Values) > 0 {
// If there are any rules at this position, it's what the ref would
// refer to. We can just append those and stop here.
insertRules(set, child.Values)
} else {
// Otherwise, we continue using the child node.
walk(child, i+1)
}
} else {
// This part of the ref is a dynamic term. We can't know what it refers
// to and will just need to try all of the children.
for _, child := range node.Children {
if child.Hide {
continue
}
insertRules(set, child.Values)
walk(child, i+1)
}
}
}
walk(node, 0)
for rule := range set {
rules = append(rules, rule)
}
return rules
}
// Utility: add all rule values to the set.
func insertRules(set map[*Rule]struct{}, rules []util.T) {
for _, rule := range rules {
set[rule.(*Rule)] = struct{}{}
}
}
// 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
}
func (c *Compiler) counterAdd(name string, n uint64) {
if c.metrics == nil {
return
}
c.metrics.Counter(name).Add(n)
}
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 isVirtual(c.RuleTree, ref.GroundPrefix())
})
if rules := extractRules(node.Values); index.Build(rules) {
c.ruleIndices.Put(rules[0].Path(), index)
}
return false
})
}
func (c *Compiler) buildComprehensionIndices() {
for _, name := range c.sorted {
WalkRules(c.Modules[name], func(r *Rule) bool {
candidates := r.Head.Args.Vars()
candidates.Update(ReservedVars)
n := buildComprehensionIndices(c.GetArity, candidates, r.Body, c.comprehensionIndices)
c.counterAdd(compileStageComprehensionIndexBuild, n)
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 {
return a.(*Rule) == b.(*Rule)
}
c.RuleTree.DepthFirst(func(node *TreeNode) bool {
for _, rule := range node.Values {
for node := rule.(*Rule); node != nil; node = node.Else {
c.checkSelfPath(node.Loc(), eq, node, node)
}
}
return false
})
}
func (c *Compiler) checkSelfPath(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, "rule %v is recursive: %v", astNodeToString(a), strings.Join(n, " -> ")))
}
}
func astNodeToString(x interface{}) string {
switch x := x.(type) {
case *Rule:
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
arities := map[int]struct{}{}
declared := false
for _, rule := range node.Values {
r := rule.(*Rule)
kinds[r.Head.DocKind()] = struct{}{}
arities[len(r.Head.Args)] = struct{}{}
if r.Head.Assign {
declared = true
}
if r.Default {
defaultRules++
}
}
name := Var(node.Key.(String))
if declared && len(node.Values) > 1 {
c.err(NewError(TypeErr, node.Values[0].(*Rule).Loc(), "rule named %v redeclared at %v", name, node.Values[1].(*Rule).Loc()))
} else if len(kinds) > 1 || len(arities) > 1 {
c.err(NewError(TypeErr, node.Values[0].(*Rule).Loc(), "conflicting rules named %v found", name))
} else if defaultRules > 1 {
c.err(NewError(TypeErr, node.Values[0].(*Rule).Loc(), "multiple default rules named %s found", name))
}
return false
})
if c.pathExists != nil {
for _, err := range CheckPathConflicts(c, c.pathExists) {
c.err(err)
}
}
c.ModuleTree.DepthFirst(func(node *ModuleTreeNode) bool {
for _, mod := range node.Modules {
for _, rule := range mod.Rules {
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
})
}
func (c *Compiler) checkUndefinedFuncs() {
for _, name := range c.sorted {
m := c.Modules[name]
for _, err := range checkUndefinedFuncs(m, c.GetArity) {
c.err(err)
}
}
}
func checkUndefinedFuncs(x interface{}, arity func(Ref) int) Errors {
var errs Errors
WalkExprs(x, func(expr *Expr) bool {
if !expr.IsCall() {
return false
}
ref := expr.Operator()
if arity(ref) >= 0 {
return false
}
errs = append(errs, NewError(TypeErr, expr.Loc(), "undefined function %v", ref))
return true
})
return errs
}
// 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 _, name := range c.sorted {
m := c.Modules[name]
WalkRules(m, func(r *Rule) bool {
safe := ReservedVars.Copy()
safe.Update(r.Head.Args.Vars())
r.Body = c.checkBodySafety(safe, m, r.Body)
return false
})
}
}
func (c *Compiler) checkBodySafety(safe VarSet, m *Module, b Body) Body {
reordered, unsafe := reorderBodyForSafety(c.builtins, c.GetArity, safe, b)
if errs := safetyErrorSlice(unsafe); len(errs) > 0 {
for _, err := range errs {
c.err(err)
}
return b
}
return reordered
}
// SafetyCheckVisitorParams defines the AST visitor parameters to use for collecting
// variables during the safety check. This has to be exported because it's relied on
// by the copy propagation implementation in topdown.
var SafetyCheckVisitorParams = VarVisitorParams{
SkipRefCallHead: true,
SkipClosures: true,
}
// checkSafetyRuleHeads ensures that variables appearing in the head of a
// rule also appear in the body.
func (c *Compiler) checkSafetyRuleHeads() {
for _, name := range c.sorted {
m := c.Modules[name]
WalkRules(m, func(r *Rule) bool {
safe := r.Body.Vars(SafetyCheckVisitorParams)
safe.Update(r.Head.Args.Vars())
unsafe := r.Head.Vars().Diff(safe)
for v := range unsafe {
if !v.IsGenerated() {
c.err(NewError(UnsafeVarErr, r.Loc(), "var %v is unsafe", v))
}
}
return false
})
}
}
// checkTypes runs the type checker on all rules. 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().WithVarRewriter(rewriteVarsInRef(c.RewrittenVars))
env, errs := checker.CheckTypes(c.TypeEnv, sorted)
for _, err := range errs {
c.err(err)
}
c.TypeEnv = env
}
func (c *Compiler) checkUnsafeBuiltins() {
for _, name := range c.sorted {
errs := checkUnsafeBuiltins(c.unsafeBuiltinsMap, c.Modules[name])
for _, err := range errs {
c.err(err)
}
}
}
func (c *Compiler) runStage(metricName string, f func()) {
if c.metrics != nil {
c.metrics.Timer(metricName).Start()
defer c.metrics.Timer(metricName).Stop()
}
f()
}
func (c *Compiler) runStageAfter(metricName string, s CompilerStage) *Error {
if c.metrics != nil {
c.metrics.Timer(metricName).Start()
defer c.metrics.Timer(metricName).Stop()
}
return s(c)
}
func (c *Compiler) compile() {
defer func() {
if r := recover(); r != nil && r != errLimitReached {
panic(r)
}
}()
for _, s := range c.stages {
c.runStage(s.metricName, s.f)
if c.Failed() {
return
}
for _, s := range c.after[s.name] {
err := c.runStageAfter(s.MetricName, s.Stage)
if err != nil {
c.err(err)
}
}
}
}
func (c *Compiler) init() {
if c.initialized {
return
}
if c.capabilities == nil {
c.capabilities = CapabilitiesForThisVersion()
}
c.builtins = make(map[string]*Builtin, len(c.capabilities.Builtins)+len(c.customBuiltins))
for _, bi := range c.capabilities.Builtins {
c.builtins[bi.Name] = bi
}
for name, bi := range c.customBuiltins {
c.builtins[name] = bi
}
tc := newTypeChecker()
c.TypeEnv = tc.checkLanguageBuiltins(nil, c.builtins)
c.initialized = true
}
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 {
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()
})
for _, name := range c.sorted {
mod := c.Modules[name]
rv, ok := rules.Get(mod.Package.Path)
if !ok {
rv = []Var{}
}
rvs := rv.([]Var)
for _, rule := range mod.Rules {
rvs = append(rvs, rule.Head.Name)
}
rules.Put(mod.Package.Path, rvs)
}
return rules
}
// 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 := c.getExports()
for _, name := range c.sorted {
mod := c.Modules[name]
var ruleExports []Var
if x, ok := rules.Get(mod.Package.Path); ok {
ruleExports = x.([]Var)
}
globals := getGlobals(mod.Package, ruleExports, mod.Imports)
WalkRules(mod, func(rule *Rule) bool {
err := resolveRefsInRule(globals, rule)
if err != nil {
c.err(NewError(CompileErr, rule.Location, err.Error()))
}
return false
})
// Once imports have been resolved, they are no longer needed.
mod.Imports = nil
}
if c.moduleLoader != nil {
parsed, err := c.moduleLoader(c.Modules)
if err != nil {
c.err(NewError(CompileErr, nil, err.Error()))
return
}