forked from open-policy-agent/opa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.go
2317 lines (1994 loc) · 51.6 KB
/
parser.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 2020 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"
"io"
"math/big"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
"github.com/pkg/errors"
"gopkg.in/yaml.v2"
"github.com/open-policy-agent/opa/ast/internal/scanner"
"github.com/open-policy-agent/opa/ast/internal/tokens"
"github.com/open-policy-agent/opa/ast/location"
)
// Note: This state is kept isolated from the parser so that we
// can do efficient shallow copies of these values when doing a
// save() and restore().
type state struct {
s *scanner.Scanner
lastEnd int
skippedNL bool
tok tokens.Token
tokEnd int
lit string
loc Location
errors Errors
hints []string
comments []*Comment
wildcard int
}
func (s *state) String() string {
return fmt.Sprintf("<s: %v, tok: %v, lit: %q, loc: %v, errors: %d, comments: %d>", s.s, s.tok, s.lit, s.loc, len(s.errors), len(s.comments))
}
func (s *state) Loc() *location.Location {
cpy := s.loc
return &cpy
}
func (s *state) Text(offset, end int) []byte {
bs := s.s.Bytes()
if offset >= 0 && offset < len(bs) {
if end >= offset && end <= len(bs) {
return bs[offset:end]
}
}
return nil
}
// Parser is used to parse Rego statements.
type Parser struct {
r io.Reader
s *state
po ParserOptions
cache parsedTermCache
}
type parsedTermCacheItem struct {
t *Term
post *state // post is the post-state that's restored on a cache-hit
offset int
next *parsedTermCacheItem
}
type parsedTermCache struct {
m *parsedTermCacheItem
}
func (c parsedTermCache) String() string {
s := strings.Builder{}
s.WriteRune('{')
var e *parsedTermCacheItem
for e = c.m; e != nil; e = e.next {
fmt.Fprintf(&s, "%v", e)
}
s.WriteRune('}')
return s.String()
}
func (e *parsedTermCacheItem) String() string {
return fmt.Sprintf("<%d:%v>", e.offset, e.t)
}
// ParserOptions defines the options for parsing Rego statements.
type ParserOptions struct {
Capabilities *Capabilities
ProcessAnnotation bool
AllFutureKeywords bool
FutureKeywords []string
unreleasedKeywords bool // TODO(sr): cleanup
}
// NewParser creates and initializes a Parser.
func NewParser() *Parser {
p := &Parser{
s: &state{},
po: ParserOptions{},
}
return p
}
// WithFilename provides the filename for Location details
// on parsed statements.
func (p *Parser) WithFilename(filename string) *Parser {
p.s.loc.File = filename
return p
}
// WithReader provides the io.Reader that the parser will
// use as its source.
func (p *Parser) WithReader(r io.Reader) *Parser {
p.r = r
return p
}
// WithProcessAnnotation enables or disables the processing of
// annotations by the Parser
func (p *Parser) WithProcessAnnotation(processAnnotation bool) *Parser {
p.po.ProcessAnnotation = processAnnotation
return p
}
// WithFutureKeywords enables "future" keywords, i.e., keywords that can
// be imported via
//
// import future.keywords.kw
// import future.keywords.other
//
// but in a more direct way. The equivalent of this import would be
//
// WithFutureKeywords("kw", "other")
func (p *Parser) WithFutureKeywords(kws ...string) *Parser {
p.po.FutureKeywords = kws
return p
}
// WithAllFutureKeywords enables all "future" keywords, i.e., the
// ParserOption equivalent of
//
// import future.keywords
func (p *Parser) WithAllFutureKeywords(yes bool) *Parser {
p.po.AllFutureKeywords = yes
return p
}
// withUnreleasedKeywords allows using keywords that haven't surfaced
// as future keywords (see above) yet, but have tests that require
// them to be parsed
func (p *Parser) withUnreleasedKeywords(yes bool) *Parser {
p.po.unreleasedKeywords = yes
return p
}
// WithCapabilities sets the capabilities structure on the parser.
func (p *Parser) WithCapabilities(c *Capabilities) *Parser {
p.po.Capabilities = c
return p
}
func (p *Parser) parsedTermCacheLookup() (*Term, *state) {
l := p.s.loc.Offset
// stop comparing once the cached offsets are lower than l
for h := p.cache.m; h != nil && h.offset >= l; h = h.next {
if h.offset == l {
return h.t, h.post
}
}
return nil, nil
}
func (p *Parser) parsedTermCachePush(t *Term, s0 *state) {
s1 := p.save()
o0 := s0.loc.Offset
entry := parsedTermCacheItem{t: t, post: s1, offset: o0}
// find the first one whose offset is smaller than ours
var e *parsedTermCacheItem
for e = p.cache.m; e != nil; e = e.next {
if e.offset < o0 {
break
}
}
entry.next = e
p.cache.m = &entry
}
// futureParser returns a shallow copy of `p` with an empty
// cache, and a scanner that knows all future keywords.
// It's used to present hints in errors, when statements would
// only parse successfully if some future keyword is enabled.
func (p *Parser) futureParser() *Parser {
q := *p
q.s = p.save()
q.s.s = p.s.s.WithKeywords(futureKeywords)
q.cache = parsedTermCache{}
return &q
}
// presentParser returns a shallow copy of `p` with an empty
// cache, and a scanner that knows none of the future keywords.
// It is used to successfully parse keyword imports, like
//
// import future.keywords.in
//
// even when the parser has already been informed about the
// future keyword "in". This parser won't error out because
// "in" is an identifier.
func (p *Parser) presentParser() (*Parser, map[string]tokens.Token) {
var cpy map[string]tokens.Token
q := *p
q.s = p.save()
q.s.s, cpy = p.s.s.WithoutKeywords(futureKeywords)
q.cache = parsedTermCache{}
return &q, cpy
}
// Parse will read the Rego source and parse statements and
// comments as they are found. Any errors encountered while
// parsing will be accumulated and returned as a list of Errors.
func (p *Parser) Parse() ([]Statement, []*Comment, Errors) {
if p.po.Capabilities == nil {
p.po.Capabilities = CapabilitiesForThisVersion()
}
allowedFutureKeywords := map[string]tokens.Token{}
for _, kw := range p.po.Capabilities.FutureKeywords {
var ok bool
allowedFutureKeywords[kw], ok = futureKeywords[kw]
if !ok {
return nil, nil, Errors{
&Error{
Code: ParseErr,
Message: fmt.Sprintf("illegal capabilities: unknown keyword: %v", kw),
Location: nil,
},
}
}
}
var err error
p.s.s, err = scanner.New(p.r)
if err != nil {
return nil, nil, Errors{
&Error{
Code: ParseErr,
Message: err.Error(),
Location: nil,
},
}
}
selected := map[string]tokens.Token{}
if p.po.AllFutureKeywords {
for kw, tok := range allowedFutureKeywords {
selected[kw] = tok
}
} else {
for _, kw := range p.po.FutureKeywords {
tok, ok := allowedFutureKeywords[kw]
if !ok {
return nil, nil, Errors{
&Error{
Code: ParseErr,
Message: fmt.Sprintf("unknown future keyword: %v", kw),
Location: nil,
},
}
}
selected[kw] = tok
}
}
p.s.s = p.s.s.WithKeywords(selected)
// read the first token to initialize the parser
p.scan()
var stmts []Statement
// Read from the scanner until the last token is reached or no statements
// can be parsed. Attempt to parse package statements, import statements,
// rule statements, and then body/query statements (in that order). If a
// statement cannot be parsed, restore the parser state before trying the
// next type of statement. If a statement can be parsed, continue from that
// point trying to parse packages, imports, etc. in the same order.
for p.s.tok != tokens.EOF {
s := p.save()
if pkg := p.parsePackage(); pkg != nil {
stmts = append(stmts, pkg)
continue
} else if len(p.s.errors) > 0 {
break
}
p.restore(s)
s = p.save()
if imp := p.parseImport(); imp != nil {
if FutureRootDocument.Equal(imp.Path.Value.(Ref)[0]) {
p.futureImport(imp, allowedFutureKeywords)
}
stmts = append(stmts, imp)
continue
} else if len(p.s.errors) > 0 {
break
}
p.restore(s)
s = p.save()
if rules := p.parseRules(); rules != nil {
for i := range rules {
stmts = append(stmts, rules[i])
}
continue
} else if len(p.s.errors) > 0 {
break
}
p.restore(s)
if body := p.parseQuery(true, tokens.EOF); body != nil {
stmts = append(stmts, body)
continue
}
break
}
if p.po.ProcessAnnotation {
stmts = p.parseAnnotations(stmts)
}
return stmts, p.s.comments, p.s.errors
}
func (p *Parser) parseAnnotations(stmts []Statement) []Statement {
annotStmts, errs := parseAnnotations(p.s.comments)
for _, err := range errs {
p.error(err.Location, err.Message)
}
for _, annotStmt := range annotStmts {
stmts = append(stmts, annotStmt)
}
return stmts
}
func parseAnnotations(comments []*Comment) ([]*Annotations, Errors) {
var hint = []byte("METADATA")
var curr *metadataParser
var blocks []*metadataParser
for i := 0; i < len(comments); i++ {
if curr != nil {
if comments[i].Location.Row == comments[i-1].Location.Row+1 && comments[i].Location.Col == 1 {
curr.Append(comments[i])
continue
}
curr = nil
}
if bytes.HasPrefix(bytes.TrimSpace(comments[i].Text), hint) {
curr = newMetadataParser(comments[i].Location)
blocks = append(blocks, curr)
}
}
var stmts []*Annotations
var errs Errors
for _, b := range blocks {
a, err := b.Parse()
if err != nil {
errs = append(errs, &Error{
Code: ParseErr,
Message: err.Error(),
Location: b.loc,
})
} else {
stmts = append(stmts, a)
}
}
return stmts, errs
}
func (p *Parser) parsePackage() *Package {
var pkg Package
pkg.SetLoc(p.s.Loc())
if p.s.tok != tokens.Package {
return nil
}
p.scan()
if p.s.tok != tokens.Ident {
p.illegalToken()
return nil
}
term := p.parseTerm()
if term != nil {
switch v := term.Value.(type) {
case Var:
pkg.Path = Ref{
DefaultRootDocument.Copy().SetLocation(term.Location),
StringTerm(string(v)).SetLocation(term.Location),
}
case Ref:
pkg.Path = make(Ref, len(v)+1)
pkg.Path[0] = DefaultRootDocument.Copy().SetLocation(v[0].Location)
first, ok := v[0].Value.(Var)
if !ok {
p.errorf(v[0].Location, "unexpected %v token: expecting var", TypeName(v[0].Value))
return nil
}
pkg.Path[1] = StringTerm(string(first)).SetLocation(v[0].Location)
for i := 2; i < len(pkg.Path); i++ {
switch v[i-1].Value.(type) {
case String:
pkg.Path[i] = v[i-1]
default:
p.errorf(v[i-1].Location, "unexpected %v token: expecting string", TypeName(v[i-1].Value))
return nil
}
}
default:
p.illegalToken()
return nil
}
}
if pkg.Path == nil {
if len(p.s.errors) == 0 {
p.error(p.s.Loc(), "expected path")
}
return nil
}
return &pkg
}
func (p *Parser) parseImport() *Import {
var imp Import
imp.SetLoc(p.s.Loc())
if p.s.tok != tokens.Import {
return nil
}
p.scan()
if p.s.tok != tokens.Ident {
p.error(p.s.Loc(), "expected ident")
return nil
}
q, prev := p.presentParser()
term := q.parseTerm()
if term != nil {
switch v := term.Value.(type) {
case Var:
imp.Path = RefTerm(term).SetLocation(term.Location)
case Ref:
for i := 1; i < len(v); i++ {
if _, ok := v[i].Value.(String); !ok {
p.errorf(v[i].Location, "unexpected %v token: expecting string", TypeName(v[i].Value))
return nil
}
}
imp.Path = term
}
}
// keep advanced parser state, reset known keywords
p.s = q.s
p.s.s = q.s.s.WithKeywords(prev)
if imp.Path == nil {
p.error(p.s.Loc(), "expected path")
return nil
}
path := imp.Path.Value.(Ref)
if !RootDocumentNames.Contains(path[0]) && !FutureRootDocument.Equal(path[0]) {
p.errorf(imp.Path.Location, "unexpected import path, must begin with one of: %v, got: %v",
RootDocumentNames.Union(NewSet(FutureRootDocument)),
path[0])
return nil
}
if p.s.tok == tokens.As {
p.scan()
if p.s.tok != tokens.Ident {
p.illegal("expected var")
return nil
}
if alias := p.parseTerm(); alias != nil {
v, ok := alias.Value.(Var)
if ok {
imp.Alias = v
return &imp
}
}
p.illegal("expected var")
return nil
}
return &imp
}
func (p *Parser) parseRules() []*Rule {
var rule Rule
rule.SetLoc(p.s.Loc())
if p.s.tok == tokens.Default {
p.scan()
rule.Default = true
}
if p.s.tok != tokens.Ident {
return nil
}
if rule.Head = p.parseHead(rule.Default); rule.Head == nil {
return nil
}
if rule.Default {
if !p.validateDefaultRuleValue(&rule) {
return nil
}
rule.Body = NewBody(NewExpr(BooleanTerm(true).SetLocation(rule.Location)).SetLocation(rule.Location))
return []*Rule{&rule}
}
if p.s.tok == tokens.LBrace {
p.scan()
if rule.Body = p.parseBody(tokens.RBrace); rule.Body == nil {
return nil
}
p.scan()
} else {
return nil
}
if p.s.tok == tokens.Else {
if rule.Head.Key != nil {
p.error(p.s.Loc(), "else keyword cannot be used on partial rules")
return nil
}
if rule.Else = p.parseElse(rule.Head); rule.Else == nil {
return nil
}
}
rule.Location.Text = p.s.Text(rule.Location.Offset, p.s.lastEnd)
var rules []*Rule
rules = append(rules, &rule)
for p.s.tok == tokens.LBrace {
if rule.Else != nil {
p.error(p.s.Loc(), "expected else keyword")
return nil
}
loc := p.s.Loc()
p.scan()
var next Rule
if next.Body = p.parseBody(tokens.RBrace); next.Body == nil {
return nil
}
p.scan()
loc.Text = p.s.Text(loc.Offset, p.s.lastEnd)
next.SetLoc(loc)
// Chained rule head's keep the original
// rule's head AST but have their location
// set to the rule body.
next.Head = rule.Head.Copy()
setLocRecursive(next.Head, loc)
rules = append(rules, &next)
}
return rules
}
func (p *Parser) parseElse(head *Head) *Rule {
var rule Rule
rule.SetLoc(p.s.Loc())
rule.Head = head.Copy()
rule.Head.SetLoc(p.s.Loc())
defer func() {
rule.Location.Text = p.s.Text(rule.Location.Offset, p.s.lastEnd)
}()
p.scan()
switch p.s.tok {
case tokens.LBrace:
rule.Head.Value = BooleanTerm(true)
case tokens.Assign, tokens.Unify:
p.scan()
rule.Head.Value = p.parseTermInfixCall()
if rule.Head.Value == nil {
return nil
}
rule.Head.Location.Text = p.s.Text(rule.Head.Location.Offset, p.s.lastEnd)
default:
p.illegal("expected else value term or rule body")
return nil
}
if p.s.tok != tokens.LBrace {
rule.Body = NewBody(NewExpr(BooleanTerm(true)))
setLocRecursive(rule.Body, rule.Location)
return &rule
}
p.scan()
if rule.Body = p.parseBody(tokens.RBrace); rule.Body == nil {
return nil
}
p.scan()
if p.s.tok == tokens.Else {
if rule.Else = p.parseElse(head); rule.Else == nil {
return nil
}
}
return &rule
}
func (p *Parser) parseHead(defaultRule bool) *Head {
var head Head
head.SetLoc(p.s.Loc())
defer func() {
head.Location.Text = p.s.Text(head.Location.Offset, p.s.lastEnd)
}()
if term := p.parseVar(); term != nil {
head.Name = term.Value.(Var)
} else {
p.illegal("expected rule head name")
}
p.scan()
if p.s.tok == tokens.LParen {
p.scan()
if p.s.tok != tokens.RParen {
head.Args = p.parseTermList(tokens.RParen, nil)
if head.Args == nil {
return nil
}
}
p.scan()
if p.s.tok == tokens.LBrack {
return nil
}
}
if p.s.tok == tokens.LBrack {
p.scan()
head.Key = p.parseTermInfixCall()
if head.Key == nil {
p.illegal("expected rule key term (e.g., %s[<VALUE>] { ... })", head.Name)
}
if p.s.tok != tokens.RBrack {
if _, ok := futureKeywords[head.Name.String()]; ok {
p.hint("`import future.keywords.%[1]s` for '%[1]s' keyword", head.Name.String())
}
p.illegal("non-terminated rule key")
}
p.scan()
}
if p.s.tok == tokens.Unify {
p.scan()
head.Value = p.parseTermInfixCall()
if head.Value == nil {
p.illegal("expected rule value term (e.g., %s[%s] = <VALUE> { ... })", head.Name, head.Key)
}
} else if p.s.tok == tokens.Assign {
s := p.save()
p.scan()
head.Assign = true
head.Value = p.parseTermInfixCall()
if head.Value == nil {
p.restore(s)
switch {
case len(head.Args) > 0:
p.illegal("expected function value term (e.g., %s(...) := <VALUE> { ... })", head.Name)
case head.Key != nil:
p.illegal("expected partial rule value term (e.g., %s[...] := <VALUE> { ... })", head.Name)
case defaultRule:
p.illegal("expected default rule value term (e.g., default %s := <VALUE>)", head.Name)
default:
p.illegal("expected rule value term (e.g., %s := <VALUE> { ... })", head.Name)
}
}
}
if head.Value == nil && head.Key == nil {
head.Value = BooleanTerm(true).SetLocation(head.Location)
}
return &head
}
func (p *Parser) parseBody(end tokens.Token) Body {
return p.parseQuery(false, end)
}
func (p *Parser) parseQuery(requireSemi bool, end tokens.Token) Body {
body := Body{}
if p.s.tok == end {
p.error(p.s.Loc(), "found empty body")
return nil
}
for {
expr := p.parseLiteral()
if expr == nil {
return nil
}
body.Append(expr)
if p.s.tok == tokens.Semicolon {
p.scan()
continue
}
if p.s.tok == end || requireSemi {
return body
}
if !p.s.skippedNL {
// If there was already an error then don't pile this one on
if len(p.s.errors) == 0 {
p.illegal(`expected \n or %s or %s`, tokens.Semicolon, end)
}
return nil
}
}
}
func (p *Parser) parseLiteral() (expr *Expr) {
offset := p.s.loc.Offset
loc := p.s.Loc()
defer func() {
if expr != nil {
loc.Text = p.s.Text(offset, p.s.lastEnd)
expr.SetLoc(loc)
}
}()
var negated bool
if p.s.tok == tokens.Not {
p.scan()
negated = true
}
switch p.s.tok {
case tokens.Some:
if negated {
p.illegal("illegal negation of 'some'")
return nil
}
return p.parseSome()
case tokens.Every:
if negated {
p.illegal("illegal negation of 'every'")
return nil
}
return p.parseEvery()
default:
s := p.save()
expr := p.parseExpr()
if expr != nil {
expr.Negated = negated
if p.s.tok == tokens.With {
if expr.With = p.parseWith(); expr.With == nil {
return nil
}
}
// If we find a plain `every` identifier, attempt to parse an every expression,
// add hint if it succeeds.
if term, ok := expr.Terms.(*Term); ok && Var("every").Equal(term.Value) {
var hint bool
t := p.save()
p.restore(s)
if expr := p.futureParser().parseEvery(); expr != nil {
_, hint = expr.Terms.(*Every)
}
p.restore(t)
if hint {
p.hint("`import future.keywords.every` for `every x in xs { ... }` expressions")
}
}
return expr
}
return nil
}
}
func (p *Parser) parseWith() []*With {
withs := []*With{}
for {
with := With{
Location: p.s.Loc(),
}
p.scan()
if p.s.tok != tokens.Ident {
p.illegal("expected ident")
return nil
}
with.Target = p.parseTerm()
if with.Target == nil {
return nil
}
switch with.Target.Value.(type) {
case Ref, Var:
break
default:
p.illegal("expected with target path")
}
if p.s.tok != tokens.As {
p.illegal("expected as keyword")
return nil
}
p.scan()
if with.Value = p.parseTermInfixCall(); with.Value == nil {
return nil
}
with.Location.Text = p.s.Text(with.Location.Offset, p.s.lastEnd)
withs = append(withs, &with)
if p.s.tok != tokens.With {
break
}
}
return withs
}
func (p *Parser) parseSome() *Expr {
decl := &SomeDecl{}
decl.SetLoc(p.s.Loc())
// Attempt to parse "some x in xs", which will end up in
// SomeDecl{Symbols: ["member(x, xs)"]}
s := p.save()
p.scan()
if term := p.parseTermInfixCall(); term != nil {
if call, ok := term.Value.(Call); ok {
switch call[0].String() {
case Member.Name:
if len(call) != 3 {
p.illegal("illegal domain")
return nil
}
case MemberWithKey.Name:
if len(call) != 4 {
p.illegal("illegal domain")
return nil
}
default:
p.illegal("expected `x in xs` or `x, y in xs` expression")
return nil
}
decl.Symbols = []*Term{term}
expr := NewExpr(decl).SetLocation(decl.Location)
if p.s.tok == tokens.With {
if expr.With = p.parseWith(); expr.With == nil {
return nil
}
}
return expr
}
}
p.restore(s)
s = p.save() // new copy for later
var hint bool
p.scan()
if term := p.futureParser().parseTermInfixCall(); term != nil {
if call, ok := term.Value.(Call); ok {
switch call[0].String() {
case Member.Name, MemberWithKey.Name:
hint = true
}
}
}
// go on as before, it's `some x[...]` or illegal
p.restore(s)
if hint {
p.hint("`import future.keywords.in` for `some x in xs` expressions")
}
for { // collecting var args
p.scan()
if p.s.tok != tokens.Ident {
p.illegal("expected var")
return nil
}
decl.Symbols = append(decl.Symbols, p.parseVar())
p.scan()
if p.s.tok != tokens.Comma {
break
}
}
return NewExpr(decl).SetLocation(decl.Location)
}
func (p *Parser) parseEvery() *Expr {
qb := &Every{}
qb.SetLoc(p.s.Loc())
// TODO(sr): We'd get more accurate error messages if we didn't rely on
// parseTermInfixCall here, but parsed "var [, var] in term" manually.
p.scan()
term := p.parseTermInfixCall()
if term == nil {
return nil
}
call, ok := term.Value.(Call)
if !ok {
p.illegal("expected `x[, y] in xs { ... }` expression")
return nil
}
switch call[0].String() {
case Member.Name: // x in xs
if len(call) != 3 {
p.illegal("illegal domain")