forked from open-policy-agent/opa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
policy.go
1321 lines (1158 loc) · 30.6 KB
/
policy.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 (
"bytes"
"encoding/json"
"fmt"
"math/rand"
"strings"
"time"
"github.com/open-policy-agent/opa/util"
)
// Initialize seed for term hashing. This is intentionally placed before the
// root document sets are constructed to ensure they use the same hash seed as
// subsequent lookups. If the hash seeds are out of sync, lookups will fail.
var hashSeed = rand.New(rand.NewSource(time.Now().UnixNano()))
var hashSeed0 = (uint64(hashSeed.Uint32()) << 32) | uint64(hashSeed.Uint32())
var hashSeed1 = (uint64(hashSeed.Uint32()) << 32) | uint64(hashSeed.Uint32())
// DefaultRootDocument is the default root document.
//
// All package directives inside source files are implicitly prefixed with the
// DefaultRootDocument value.
var DefaultRootDocument = VarTerm("data")
// InputRootDocument names the document containing query arguments.
var InputRootDocument = VarTerm("input")
// RootDocumentNames contains the names of top-level documents that can be
// referred to in modules and queries.
var RootDocumentNames = NewSet(
DefaultRootDocument,
InputRootDocument,
)
// DefaultRootRef is a reference to the root of the default document.
//
// All refs to data in the policy engine's storage layer are prefixed with this ref.
var DefaultRootRef = Ref{DefaultRootDocument}
// InputRootRef is a reference to the root of the input document.
//
// All refs to query arguments are prefixed with this ref.
var InputRootRef = Ref{InputRootDocument}
// RootDocumentRefs contains the prefixes of top-level documents that all
// non-local references start with.
var RootDocumentRefs = NewSet(
NewTerm(DefaultRootRef),
NewTerm(InputRootRef),
)
// SystemDocumentKey is the name of the top-level key that identifies the system
// document.
var SystemDocumentKey = String("system")
// ReservedVars is the set of names that refer to implicitly ground vars.
var ReservedVars = NewVarSet(
DefaultRootDocument.Value.(Var),
InputRootDocument.Value.(Var),
)
// Wildcard represents the wildcard variable as defined in the language.
var Wildcard = &Term{Value: Var("_")}
// WildcardPrefix is the special character that all wildcard variables are
// prefixed with when the statement they are contained in is parsed.
var WildcardPrefix = "$"
// Keywords contains strings that map to language keywords.
var Keywords = [...]string{
"not",
"package",
"import",
"as",
"default",
"else",
"with",
"null",
"true",
"false",
"some",
}
// IsKeyword returns true if s is a language keyword.
func IsKeyword(s string) bool {
for _, x := range Keywords {
if x == s {
return true
}
}
return false
}
type (
// Node represents a node in an AST. Nodes may be statements in a policy module
// or elements of an ad-hoc query, expression, etc.
Node interface {
fmt.Stringer
Loc() *Location
SetLoc(*Location)
}
// Statement represents a single statement in a policy module.
Statement interface {
Node
}
)
type (
// Module represents a collection of policies (defined by rules)
// within a namespace (defined by the package) and optional
// dependencies on external documents (defined by imports).
Module struct {
Package *Package `json:"package"`
Imports []*Import `json:"imports,omitempty"`
Rules []*Rule `json:"rules,omitempty"`
Comments []*Comment `json:"comments,omitempty"`
}
// Comment contains the raw text from the comment in the definition.
Comment struct {
Text []byte
Location *Location
}
// Package represents the namespace of the documents produced
// by rules inside the module.
Package struct {
Location *Location `json:"-"`
Path Ref `json:"path"`
}
// Import represents a dependency on a document outside of the policy
// namespace. Imports are optional.
Import struct {
Location *Location `json:"-"`
Path *Term `json:"path"`
Alias Var `json:"alias,omitempty"`
}
// Rule represents a rule as defined in the language. Rules define the
// content of documents that represent policy decisions.
Rule struct {
Location *Location `json:"-"`
Default bool `json:"default,omitempty"`
Head *Head `json:"head"`
Body Body `json:"body"`
Else *Rule `json:"else,omitempty"`
// Module is a pointer to the module containing this rule. If the rule
// was NOT created while parsing/constructing a module, this should be
// left unset. The pointer is not included in any standard operations
// on the rule (e.g., printing, comparison, visiting, etc.)
Module *Module `json:"-"`
}
// Head represents the head of a rule.
Head struct {
Location *Location `json:"-"`
Name Var `json:"name"`
Args Args `json:"args,omitempty"`
Key *Term `json:"key,omitempty"`
Value *Term `json:"value,omitempty"`
}
// Args represents zero or more arguments to a rule.
Args []*Term
// Body represents one or more expressions contained inside a rule or user
// function.
Body []*Expr
// Expr represents a single expression contained inside the body of a rule.
Expr struct {
Location *Location `json:"-"`
Generated bool `json:"generated,omitempty"`
Index int `json:"index"`
Negated bool `json:"negated,omitempty"`
Terms interface{} `json:"terms"`
With []*With `json:"with,omitempty"`
}
// SomeDecl represents a variable declaration statement. The symbols are variables.
SomeDecl struct {
Location *Location `json:"-"`
Symbols []*Term `json:"symbols"`
}
// With represents a modifier on an expression.
With struct {
Location *Location `json:"-"`
Target *Term `json:"target"`
Value *Term `json:"value"`
}
)
// Compare returns an integer indicating whether mod is less than, equal to,
// or greater than other.
func (mod *Module) Compare(other *Module) int {
if mod == nil {
if other == nil {
return 0
}
return -1
} else if other == nil {
return 1
}
if cmp := mod.Package.Compare(other.Package); cmp != 0 {
return cmp
}
if cmp := importsCompare(mod.Imports, other.Imports); cmp != 0 {
return cmp
}
return rulesCompare(mod.Rules, other.Rules)
}
// Copy returns a deep copy of mod.
func (mod *Module) Copy() *Module {
cpy := *mod
cpy.Rules = make([]*Rule, len(mod.Rules))
for i := range mod.Rules {
cpy.Rules[i] = mod.Rules[i].Copy()
}
cpy.Imports = make([]*Import, len(mod.Imports))
for i := range mod.Imports {
cpy.Imports[i] = mod.Imports[i].Copy()
}
cpy.Package = mod.Package.Copy()
return &cpy
}
// Equal returns true if mod equals other.
func (mod *Module) Equal(other *Module) bool {
return mod.Compare(other) == 0
}
func (mod *Module) String() string {
buf := []string{}
buf = append(buf, mod.Package.String())
if len(mod.Imports) > 0 {
buf = append(buf, "")
for _, imp := range mod.Imports {
buf = append(buf, imp.String())
}
}
if len(mod.Rules) > 0 {
buf = append(buf, "")
for _, rule := range mod.Rules {
buf = append(buf, rule.String())
}
}
return strings.Join(buf, "\n")
}
// RuleSet returns a RuleSet containing named rules in the mod.
func (mod *Module) RuleSet(name Var) RuleSet {
rs := NewRuleSet()
for _, rule := range mod.Rules {
if rule.Head.Name.Equal(name) {
rs.Add(rule)
}
}
return rs
}
// NewComment returns a new Comment object.
func NewComment(text []byte) *Comment {
return &Comment{
Text: text,
}
}
// Loc returns the location of the comment in the definition.
func (c *Comment) Loc() *Location {
if c == nil {
return nil
}
return c.Location
}
// SetLoc sets the location on c.
func (c *Comment) SetLoc(loc *Location) {
c.Location = loc
}
func (c *Comment) String() string {
return "#" + string(c.Text)
}
// Equal returns true if this comment equals the other comment.
// Unlike other equality checks on AST nodes, comment equality
// depends on location.
func (c *Comment) Equal(other *Comment) bool {
return c.Location.Equal(other.Location) && bytes.Equal(c.Text, other.Text)
}
// Compare returns an integer indicating whether pkg is less than, equal to,
// or greater than other.
func (pkg *Package) Compare(other *Package) int {
return Compare(pkg.Path, other.Path)
}
// Copy returns a deep copy of pkg.
func (pkg *Package) Copy() *Package {
cpy := *pkg
cpy.Path = pkg.Path.Copy()
return &cpy
}
// Equal returns true if pkg is equal to other.
func (pkg *Package) Equal(other *Package) bool {
return pkg.Compare(other) == 0
}
// Loc returns the location of the Package in the definition.
func (pkg *Package) Loc() *Location {
if pkg == nil {
return nil
}
return pkg.Location
}
// SetLoc sets the location on pkg.
func (pkg *Package) SetLoc(loc *Location) {
pkg.Location = loc
}
func (pkg *Package) String() string {
if pkg == nil {
return "<illegal nil package>"
} else if len(pkg.Path) <= 1 {
return fmt.Sprintf("package <illegal path %q>", pkg.Path)
}
// Omit head as all packages have the DefaultRootDocument prepended at parse time.
path := make(Ref, len(pkg.Path)-1)
path[0] = VarTerm(string(pkg.Path[1].Value.(String)))
copy(path[1:], pkg.Path[2:])
return fmt.Sprintf("package %v", path)
}
// IsValidImportPath returns an error indicating if the import path is invalid.
// If the import path is invalid, err is nil.
func IsValidImportPath(v Value) (err error) {
switch v := v.(type) {
case Var:
if !v.Equal(DefaultRootDocument.Value) && !v.Equal(InputRootDocument.Value) {
return fmt.Errorf("invalid path %v: path must begin with input or data", v)
}
case Ref:
if err := IsValidImportPath(v[0].Value); err != nil {
return fmt.Errorf("invalid path %v: path must begin with input or data", v)
}
for _, e := range v[1:] {
if _, ok := e.Value.(String); !ok {
return fmt.Errorf("invalid path %v: path elements must be strings", v)
}
}
default:
return fmt.Errorf("invalid path %v: path must be ref or var", v)
}
return nil
}
// Compare returns an integer indicating whether imp is less than, equal to,
// or greater than other.
func (imp *Import) Compare(other *Import) int {
if imp == nil {
if other == nil {
return 0
}
return -1
} else if other == nil {
return 1
}
if cmp := Compare(imp.Path, other.Path); cmp != 0 {
return cmp
}
return Compare(imp.Alias, other.Alias)
}
// Copy returns a deep copy of imp.
func (imp *Import) Copy() *Import {
cpy := *imp
cpy.Path = imp.Path.Copy()
return &cpy
}
// Equal returns true if imp is equal to other.
func (imp *Import) Equal(other *Import) bool {
return imp.Compare(other) == 0
}
// Loc returns the location of the Import in the definition.
func (imp *Import) Loc() *Location {
if imp == nil {
return nil
}
return imp.Location
}
// SetLoc sets the location on imp.
func (imp *Import) SetLoc(loc *Location) {
imp.Location = loc
}
// Name returns the variable that is used to refer to the imported virtual
// document. This is the alias if defined otherwise the last element in the
// path.
func (imp *Import) Name() Var {
if len(imp.Alias) != 0 {
return imp.Alias
}
switch v := imp.Path.Value.(type) {
case Var:
return v
case Ref:
if len(v) == 1 {
return v[0].Value.(Var)
}
return Var(v[len(v)-1].Value.(String))
}
panic("illegal import")
}
func (imp *Import) String() string {
buf := []string{"import", imp.Path.String()}
if len(imp.Alias) > 0 {
buf = append(buf, "as "+imp.Alias.String())
}
return strings.Join(buf, " ")
}
// Compare returns an integer indicating whether rule is less than, equal to,
// or greater than other.
func (rule *Rule) Compare(other *Rule) int {
if rule == nil {
if other == nil {
return 0
}
return -1
} else if other == nil {
return 1
}
if cmp := rule.Head.Compare(other.Head); cmp != 0 {
return cmp
}
if cmp := util.Compare(rule.Default, other.Default); cmp != 0 {
return cmp
}
if cmp := rule.Body.Compare(other.Body); cmp != 0 {
return cmp
}
return rule.Else.Compare(other.Else)
}
// Copy returns a deep copy of rule.
func (rule *Rule) Copy() *Rule {
cpy := *rule
cpy.Head = rule.Head.Copy()
cpy.Body = rule.Body.Copy()
if cpy.Else != nil {
cpy.Else = rule.Else.Copy()
}
return &cpy
}
// Equal returns true if rule is equal to other.
func (rule *Rule) Equal(other *Rule) bool {
return rule.Compare(other) == 0
}
// Loc returns the location of the Rule in the definition.
func (rule *Rule) Loc() *Location {
if rule == nil {
return nil
}
return rule.Location
}
// SetLoc sets the location on rule.
func (rule *Rule) SetLoc(loc *Location) {
rule.Location = loc
}
// Path returns a ref referring to the document produced by this rule. If rule
// is not contained in a module, this function panics.
func (rule *Rule) Path() Ref {
if rule.Module == nil {
panic("assertion failed")
}
return rule.Module.Package.Path.Append(StringTerm(string(rule.Head.Name)))
}
func (rule *Rule) String() string {
buf := []string{}
if rule.Default {
buf = append(buf, "default")
}
buf = append(buf, rule.Head.String())
if !rule.Default {
buf = append(buf, "{")
buf = append(buf, rule.Body.String())
buf = append(buf, "}")
}
if rule.Else != nil {
buf = append(buf, rule.Else.elseString())
}
return strings.Join(buf, " ")
}
func (rule *Rule) elseString() string {
var buf []string
buf = append(buf, "else")
value := rule.Head.Value
if value != nil {
buf = append(buf, "=")
buf = append(buf, value.String())
}
buf = append(buf, "{")
buf = append(buf, rule.Body.String())
buf = append(buf, "}")
if rule.Else != nil {
buf = append(buf, rule.Else.elseString())
}
return strings.Join(buf, " ")
}
// NewHead returns a new Head object. If args are provided, the first will be
// used for the key and the second will be used for the value.
func NewHead(name Var, args ...*Term) *Head {
head := &Head{
Name: name,
}
if len(args) == 0 {
return head
}
head.Key = args[0]
if len(args) == 1 {
return head
}
head.Value = args[1]
return head
}
// DocKind represents the collection of document types that can be produced by rules.
type DocKind int
const (
// CompleteDoc represents a document that is completely defined by the rule.
CompleteDoc = iota
// PartialSetDoc represents a set document that is partially defined by the rule.
PartialSetDoc = iota
// PartialObjectDoc represents an object document that is partially defined by the rule.
PartialObjectDoc = iota
)
// DocKind returns the type of document produced by this rule.
func (head *Head) DocKind() DocKind {
if head.Key != nil {
if head.Value != nil {
return PartialObjectDoc
}
return PartialSetDoc
}
return CompleteDoc
}
// Compare returns an integer indicating whether head is less than, equal to,
// or greater than other.
func (head *Head) Compare(other *Head) int {
if head == nil {
if other == nil {
return 0
}
return -1
} else if other == nil {
return 1
}
if cmp := Compare(head.Args, other.Args); cmp != 0 {
return cmp
}
if cmp := Compare(head.Name, other.Name); cmp != 0 {
return cmp
}
if cmp := Compare(head.Key, other.Key); cmp != 0 {
return cmp
}
return Compare(head.Value, other.Value)
}
// Copy returns a deep copy of head.
func (head *Head) Copy() *Head {
cpy := *head
cpy.Args = head.Args.Copy()
cpy.Key = head.Key.Copy()
cpy.Value = head.Value.Copy()
return &cpy
}
// Equal returns true if this head equals other.
func (head *Head) Equal(other *Head) bool {
return head.Compare(other) == 0
}
func (head *Head) String() string {
var buf []string
if len(head.Args) != 0 {
buf = append(buf, head.Name.String()+head.Args.String())
} else if head.Key != nil {
buf = append(buf, head.Name.String()+"["+head.Key.String()+"]")
} else {
buf = append(buf, head.Name.String())
}
if head.Value != nil {
buf = append(buf, "=")
buf = append(buf, head.Value.String())
}
return strings.Join(buf, " ")
}
// Vars returns a set of vars found in the head.
func (head *Head) Vars() VarSet {
vis := &VarVisitor{vars: VarSet{}}
// TODO: improve test coverage for this.
if head.Args != nil {
Walk(vis, head.Args)
}
if head.Key != nil {
Walk(vis, head.Key)
}
if head.Value != nil {
Walk(vis, head.Value)
}
return vis.vars
}
// Loc returns the Location of head.
func (head *Head) Loc() *Location {
if head == nil {
return nil
}
return head.Location
}
// SetLoc sets the location on head.
func (head *Head) SetLoc(loc *Location) {
head.Location = loc
}
// Copy returns a deep copy of a.
func (a Args) Copy() Args {
cpy := Args{}
for _, t := range a {
cpy = append(cpy, t.Copy())
}
return cpy
}
func (a Args) String() string {
var buf []string
for _, t := range a {
buf = append(buf, t.String())
}
return "(" + strings.Join(buf, ", ") + ")"
}
// Loc returns the Location of a.
func (a Args) Loc() *Location {
if len(a) == 0 {
return nil
}
return a[0].Location
}
// SetLoc sets the location on a.
func (a Args) SetLoc(loc *Location) {
if len(a) != 0 {
a[0].SetLocation(loc)
}
}
// Vars returns a set of vars that appear in a.
func (a Args) Vars() VarSet {
vis := &VarVisitor{vars: VarSet{}}
Walk(vis, a)
return vis.vars
}
// NewBody returns a new Body containing the given expressions. The indices of
// the immediate expressions will be reset.
func NewBody(exprs ...*Expr) Body {
for i, expr := range exprs {
expr.Index = i
}
return Body(exprs)
}
// MarshalJSON returns JSON encoded bytes representing body.
func (body Body) MarshalJSON() ([]byte, error) {
// Serialize empty Body to empty array. This handles both the empty case and the
// nil case (whereas by default the result would be null if body was nil.)
if len(body) == 0 {
return []byte(`[]`), nil
}
return json.Marshal([]*Expr(body))
}
// Append adds the expr to the body and updates the expr's index accordingly.
func (body *Body) Append(expr *Expr) {
n := len(*body)
expr.Index = n
*body = append(*body, expr)
}
// Set sets the expr in the body at the specified position and updates the
// expr's index accordingly.
func (body Body) Set(expr *Expr, pos int) {
body[pos] = expr
expr.Index = pos
}
// Compare returns an integer indicating whether body is less than, equal to,
// or greater than other.
//
// If body is a subset of other, it is considered less than (and vice versa).
func (body Body) Compare(other Body) int {
minLen := len(body)
if len(other) < minLen {
minLen = len(other)
}
for i := 0; i < minLen; i++ {
if cmp := body[i].Compare(other[i]); cmp != 0 {
return cmp
}
}
if len(body) < len(other) {
return -1
}
if len(other) < len(body) {
return 1
}
return 0
}
// Copy returns a deep copy of body.
func (body Body) Copy() Body {
cpy := make(Body, len(body))
for i := range body {
cpy[i] = body[i].Copy()
}
return cpy
}
// Contains returns true if this body contains the given expression.
func (body Body) Contains(x *Expr) bool {
for _, e := range body {
if e.Equal(x) {
return true
}
}
return false
}
// Equal returns true if this Body is equal to the other Body.
func (body Body) Equal(other Body) bool {
return body.Compare(other) == 0
}
// Hash returns the hash code for the Body.
func (body Body) Hash() int {
s := 0
for _, e := range body {
s += e.Hash()
}
return s
}
// IsGround returns true if all of the expressions in the Body are ground.
func (body Body) IsGround() bool {
for _, e := range body {
if !e.IsGround() {
return false
}
}
return true
}
// Loc returns the location of the Body in the definition.
func (body Body) Loc() *Location {
if len(body) == 0 {
return nil
}
return body[0].Location
}
// SetLoc sets the location on body.
func (body Body) SetLoc(loc *Location) {
if len(body) != 0 {
body[0].SetLocation(loc)
}
}
func (body Body) String() string {
var buf []string
for _, v := range body {
buf = append(buf, v.String())
}
return strings.Join(buf, "; ")
}
// Vars returns a VarSet containing variables in body. The params can be set to
// control which vars are included.
func (body Body) Vars(params VarVisitorParams) VarSet {
vis := NewVarVisitor().WithParams(params)
Walk(vis, body)
return vis.Vars()
}
// NewExpr returns a new Expr object.
func NewExpr(terms interface{}) *Expr {
return &Expr{
Negated: false,
Terms: terms,
Index: 0,
With: nil,
}
}
// Complement returns a copy of this expression with the negation flag flipped.
func (expr *Expr) Complement() *Expr {
cpy := *expr
cpy.Negated = !cpy.Negated
return &cpy
}
// Equal returns true if this Expr equals the other Expr.
func (expr *Expr) Equal(other *Expr) bool {
return expr.Compare(other) == 0
}
// Compare returns an integer indicating whether expr is less than, equal to,
// or greater than other.
//
// Expressions are compared as follows:
//
// 1. Declarations are always less than other expressions.
// 2. Preceding expression (by Index) is always less than the other expression.
// 3. Non-negated expressions are always less than than negated expressions.
// 4. Single term expressions are always less than built-in expressions.
//
// Otherwise, the expression terms are compared normally. If both expressions
// have the same terms, the modifiers are compared.
func (expr *Expr) Compare(other *Expr) int {
if expr == nil {
if other == nil {
return 0
}
return -1
} else if other == nil {
return 1
}
o1 := expr.sortOrder()
o2 := other.sortOrder()
if o1 < o2 {
return -1
} else if o2 < o1 {
return 1
}
switch {
case expr.Index < other.Index:
return -1
case expr.Index > other.Index:
return 1
}
switch {
case expr.Negated && !other.Negated:
return 1
case !expr.Negated && other.Negated:
return -1
}
switch t := expr.Terms.(type) {
case *Term:
if cmp := Compare(t.Value, other.Terms.(*Term).Value); cmp != 0 {
return cmp
}
case []*Term:
if cmp := termSliceCompare(t, other.Terms.([]*Term)); cmp != 0 {
return cmp
}
case *SomeDecl:
if cmp := Compare(t, other.Terms.(*SomeDecl)); cmp != 0 {
return cmp
}
}
return withSliceCompare(expr.With, other.With)
}
func (expr *Expr) sortOrder() int {
switch expr.Terms.(type) {
case *SomeDecl:
return 0
case *Term:
return 1
case []*Term:
return 2
}
return -1
}
// Copy returns a deep copy of expr.
func (expr *Expr) Copy() *Expr {
cpy := *expr
switch ts := expr.Terms.(type) {
case *SomeDecl:
cpy.Terms = ts.Copy()
case []*Term:
cpyTs := make([]*Term, len(ts))
for i := range ts {
cpyTs[i] = ts[i].Copy()
}
cpy.Terms = cpyTs
case *Term:
cpy.Terms = ts.Copy()
}
cpy.With = make([]*With, len(expr.With))
for i := range expr.With {
cpy.With[i] = expr.With[i].Copy()
}
return &cpy
}
// Hash returns the hash code of the Expr.
func (expr *Expr) Hash() int {
s := expr.Index
switch ts := expr.Terms.(type) {
case *SomeDecl:
s += ts.Hash()
case []*Term:
for _, t := range ts {
s += t.Value.Hash()
}
case *Term:
s += ts.Value.Hash()
}
if expr.Negated {
s++
}
for _, w := range expr.With {
s += w.Hash()
}
return s
}
// IncludeWith returns a copy of expr with the with modifier appended.
func (expr *Expr) IncludeWith(target *Term, value *Term) *Expr {
cpy := *expr
cpy.With = append(cpy.With, &With{Target: target, Value: value})
return &cpy
}
// NoWith returns a copy of expr where the with modifier has been removed.
func (expr *Expr) NoWith() *Expr {
expr.With = nil
return expr
}
// IsEquality returns true if this is an equality expression.
func (expr *Expr) IsEquality() bool {
return isglobalbuiltin(expr, Var(Equality.Name))
}
// IsAssignment returns true if this an assignment expression.
func (expr *Expr) IsAssignment() bool {
return isglobalbuiltin(expr, Var(Assign.Name))
}