This repository has been archived by the owner on Dec 8, 2023. It is now read-only.
forked from lab47/peggysue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpeggysue.go
1208 lines (962 loc) · 23.9 KB
/
peggysue.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
package peggysue
import (
"errors"
"fmt"
"reflect"
"regexp"
"strconv"
"strings"
"unicode/utf8"
"github.com/hashicorp/go-hclog"
)
// SetPositioner is an optional interface. When values implement it, peggysue
// will call it with the information about the position of the value in the
// inputs tream.
type SetPositioner interface {
SetPosition(start, end int)
}
type ruleSet map[Rule]struct{}
// Rule is the currency of peggysue. The parser provides the ability
// to match a Rule against an input stream. Rules are created with
// the functions on peggysue, like peggysue.S() to match a literal
// string.
type Rule interface {
match(s *state) result
detectLeftRec(r Rule, rs ruleSet) bool
print() string
}
type result struct {
matched bool
value interface{}
}
func (rs ruleSet) Add(r Rule) bool {
if _, ok := rs[r]; ok {
return false
}
rs[r] = struct{}{}
return true
}
// These are the rules!
type matchAny struct {
}
func (m *matchAny) match(s *state) result {
if s.pos >= len(s.input) {
return result{}
}
b := s.input[s.pos]
var sz int
if b < utf8.RuneSelf {
sz = 1
} else {
_, sz = utf8.DecodeRuneInString(s.cur())
}
s.advance(m, sz)
return result{matched: true}
}
func (m *matchAny) detectLeftRec(r Rule, rs ruleSet) bool {
return false
}
func (m *matchAny) print() string {
return "."
}
// Any returns a rule that will match one rune from the input stream
// of any value. In other words, it only fails if there is no more input.
//
// The value of the match is nil.
func Any() Rule {
return &matchAny{}
}
type matchString struct {
str string
}
func (m *matchString) match(s *state) result {
if len(m.str) > len(s.cur()) {
s.bad(m)
return result{}
}
if strings.HasPrefix(s.cur(), m.str) {
s.advance(m, len(m.str))
return result{matched: true}
}
s.bad(m)
return result{}
}
func (m *matchString) detectLeftRec(r Rule, rs ruleSet) bool {
return false
}
func (m *matchString) print() string {
return strconv.Quote(m.str)
}
// S returns a Rule that will match a literal string exactly.
//
// The value of the match is nil.
func S(str string) Rule {
return &matchString{str: str}
}
type matchRegexp struct {
re *regexp.Regexp
str string
}
func (m *matchRegexp) match(s *state) result {
loc := m.re.FindStringIndex(s.cur())
if loc == nil {
s.bad(m)
return result{}
}
s.advance(m, loc[1])
return result{matched: true}
}
func (m *matchRegexp) detectLeftRec(r Rule, rs ruleSet) bool {
return false
}
func (m *matchRegexp) print() string {
return "/" + m.str + "/"
}
// Re returns a Rule that will match a regexp at the current input
// position. This regexp can only match at the beginning of the input,
// it does not search the input for a match.
//
// The value of the match is nil.
func Re(re string) Rule {
return &matchRegexp{
str: re,
re: regexp.MustCompile(`\A` + re),
}
}
type matchCharRange struct {
start, end rune
}
func (m *matchCharRange) match(s *state) result {
if s.pos >= len(s.input) {
s.bad(m)
return result{}
}
b := s.input[s.pos]
var (
rn rune
sz int
)
if b < utf8.RuneSelf {
rn = rune(b)
sz = 1
} else {
rn, sz = utf8.DecodeRuneInString(s.cur())
}
if rn >= m.start && rn <= m.end {
s.advance(m, sz)
return result{matched: true}
}
s.bad(m)
return result{}
}
func (m *matchCharRange) detectLeftRec(r Rule, rs ruleSet) bool {
return false
}
func (m *matchCharRange) print() string {
return fmt.Sprintf("[%c-%c]", m.start, m.end)
}
// Range returns a rule that will match the next rune in the input
// stream as being at least 'start', and at most 'end'. This corresponds
// with the regexp pattern `[A-Z]` but is much faster as it does not require
// any regexp tracking.
//
// The value of the match is nil.
func Range(start, end rune) Rule {
return &matchCharRange{
start: start,
end: end,
}
}
type matchOr struct {
rules []Rule
}
func (m *matchOr) match(s *state) result {
save := s.mark()
for _, r := range m.rules {
res := r.match(s)
if res.matched {
s.good(m)
return res
}
s.restore(save)
}
s.bad(m)
return result{}
}
func (m *matchOr) detectLeftRec(r Rule, rs ruleSet) bool {
for _, sub := range m.rules {
if !rs.Add(sub) {
return false
}
if r == sub {
return true
}
if sub.detectLeftRec(r, rs) {
return true
}
}
return false
}
func (m *matchOr) print() string {
var subs []string
for _, r := range m.rules {
subs = append(subs, r.print())
}
return strings.Join(subs, " | ")
}
// Or returns a Rule that will try each of the given rules, completing when
// the first one successfully matches. This corresponds with a PEG's "ordered
// choice" operation.
//
// The value of the match is the value of the sub-rule that matched correctly.
func Or(rules ...Rule) Rule {
return &matchOr{rules: rules}
}
type matchSeq struct {
rules []Rule
}
func (m *matchSeq) match(s *state) result {
var ret result
for _, r := range m.rules {
res := r.match(s)
if !res.matched {
s.bad(m)
return result{}
}
if res.value != nil {
ret.value = res.value
}
}
ret.matched = true
s.good(m)
return ret
}
func (m *matchSeq) detectLeftRec(r Rule, rs ruleSet) bool {
sub := m.rules[0]
if !rs.Add(sub) {
return false
}
if sub == r {
return true
}
return sub.detectLeftRec(r, rs)
}
func (m *matchSeq) print() string {
var subs []string
for _, r := range m.rules {
subs = append(subs, r.print())
}
return strings.Join(subs, " ")
}
// Seq returns a rule that will attempt to match each of the given rules
// in order. It only matches succesfully if each of it's rules match.
//
// The value of the match is the value of the right most sub-rule that
// produced a non-nil value.
func Seq(rules ...Rule) Rule {
return &matchSeq{rules: rules}
}
type matchZeroOrMore struct {
rule Rule
}
func (m *matchZeroOrMore) match(s *state) result {
for {
res := m.rule.match(s)
if res.matched {
continue
}
s.good(m)
return result{value: res.value, matched: true}
}
}
func (m *matchZeroOrMore) detectLeftRec(r Rule, rs ruleSet) bool {
if !rs.Add(m.rule) {
return false
}
return m.rule == r || m.rule.detectLeftRec(r, rs)
}
func (m *matchZeroOrMore) print() string {
return addParens(m.rule) + "*"
}
// Star returns a rule that will attempt to match it's given rule
// as many times as possible. This rule always matches because it
// allows for zero matches. It corresponds to the star rule ("e*") in most
// PEGs.
//
// The value of the match is the value of the last iteration of applying
// the sub rule.
func Star(rule Rule) Rule {
return &matchZeroOrMore{rule: rule}
}
type matchOneOrMore struct {
rule Rule
}
func (m *matchOneOrMore) match(s *state) result {
res := m.rule.match(s)
if !res.matched {
return result{}
}
for {
res := m.rule.match(s)
if res.matched {
continue
}
return s.check(m, result{value: res.value, matched: true})
}
}
func (m *matchOneOrMore) detectLeftRec(r Rule, rs ruleSet) bool {
if !rs.Add(m.rule) {
return false
}
return m.rule == r || m.rule.detectLeftRec(r, rs)
}
func addParens(r Rule) string {
switch r.(type) {
case *matchOr, *matchSeq:
return "(" + r.print() + ")"
default:
return r.print()
}
}
func (m *matchOneOrMore) print() string {
return addParens(m.rule) + "+"
}
// Plus returns a rule that attempts to match it's given rule
// as many times as possible. The rule requires that the given
// rule match at least once. It corresponds to the plus rule ("e+") in
// most PEGs.
//
// The value of the match is the value of the last successful match of
// the sub-rule
func Plus(rule Rule) Rule {
return &matchOneOrMore{rule: rule}
}
type matchOptional struct {
rule Rule
}
func (m *matchOptional) match(s *state) result {
res := m.rule.match(s)
res.matched = true
return s.check(m, res)
}
func (m *matchOptional) detectLeftRec(r Rule, rs ruleSet) bool {
if !rs.Add(m.rule) {
return false
}
return m.rule == r || m.rule.detectLeftRec(r, rs)
}
func (m *matchOptional) print() string {
return m.rule.print() + "?"
}
// Maybe returns a rule that will allow it's rule to match, but
// will always return that it's succesfully matched, regardless
// of what it's rule does. This corresponds with the question mark
// rule ("e?") in most PEGs.
//
// The value of the match is the value of the sub-rule.
func Maybe(rule Rule) Rule {
return &matchOptional{rule: rule}
}
type matchCheck struct {
rule Rule
}
func (m *matchCheck) match(s *state) result {
defer s.restore(s.mark())
return s.check(m, m.rule.match(s))
}
func (m *matchCheck) detectLeftRec(r Rule, rs ruleSet) bool {
if !rs.Add(m.rule) {
return false
}
return m.rule == r || m.rule.detectLeftRec(r, rs)
}
func (m *matchCheck) print() string {
return "&" + m.rule.print()
}
// Check returns a rule that will attempt to match it's given rule
// and returns it's given rules match result, but it does not consume
// an input on the stream. This corresponds with the and-predicate ("&e") in
// most PEGs.
//
// The value of the match is the value of the sub-rule.
func Check(rule Rule) Rule {
return &matchCheck{rule: rule}
}
type matchNot struct {
rule Rule
}
func (m *matchNot) match(s *state) result {
defer s.restore(s.mark())
res := m.rule.match(s)
res.matched = !res.matched
return s.check(m, res)
}
func (m *matchNot) detectLeftRec(r Rule, rs ruleSet) bool {
if !rs.Add(m.rule) {
return false
}
return m.rule == r || m.rule.detectLeftRec(r, rs)
}
func (m *matchNot) print() string {
return "!" + m.rule.print()
}
// Not returns a rule that will attempt to match it's given rule.
// If the rule matches, it returns that it did not match (inverting
// the match result). Regardless of matching, it does not consume any
// input on the stream. This corresponds with the not-predicate ("!e") in
// most PEGs.
//
// The value of the match is the value of the sub-rule.
func Not(rule Rule) Rule {
return &matchNot{rule: rule}
}
// Ref is a type that provides a reference to a rule. This allows for creating
// recursive rule sets. Ref rules are memoized, meaning the
// value of the ref's rule and it's position in the stream are saved and returned
// to prevent constantly re-running the same rule on the same input. This
// is a key feature of Packrat parsing as it tames the time complexity of infinite
// backtracking to linear time.
type Ref interface {
Rule
// Set assigns the given rule to the ref. When the ref is matched as a rule,
// it will delegate the matching to this rule. The rule will not be invoked
// the multiple times at the same input position as the Ref caches the result
// of previous attempts. Thusly it's critical that the rule not depend on state
// when calculate it's value.
Set(r Rule)
// Indicates if this reference has left recursive properties.
LeftRecursive() bool
}
type matchRef struct {
name string
rule Rule
leftRec bool
}
func (r *matchRef) Set(rule Rule) {
// When invoking a ref, introduce a new scope since this matches the
// semantics of all parsers, where within a single named rule, there
// is a unique scope of produced values from it's parts.
if _, ok := rule.(*matchScope); ok {
rule = &matchScope{rule: rule}
}
r.rule = rule
rs := make(ruleSet)
if rule == r {
r.leftRec = true
} else {
rs.Add(rule)
if rule.detectLeftRec(r, rs) {
r.leftRec = true
}
}
}
func (r *matchRef) LeftRecursive() bool {
return r.leftRec
}
func (m *matchRef) match(s *state) result {
// The memoization code was ported from
// https://github.com/we-like-parsers/pegen_experiments/blob/master/story7/memo.py
pos := s.mark()
memo := s.memos[pos]
if memo == nil {
memo = make(map[Rule]*memoResult)
s.memos[pos] = memo
}
if res, ok := memo[m]; ok {
res.used++
s.restore(res.endPos)
return s.check(m, res.result)
} else if m.leftRec {
var (
lastRes = result{}
lastPos = pos
)
mr := &memoResult{endPos: pos}
memo[m] = mr
for {
s.restore(pos)
res := m.rule.match(s)
endPos := s.mark()
if endPos <= lastPos {
break
}
lastRes = res
lastPos = endPos
mr.result = res
mr.endPos = endPos
}
s.restore(lastPos)
return s.check(m, lastRes)
} else {
if res, ok := memo[m]; ok {
s.restore(res.endPos)
return res.result
}
res := m.rule.match(s)
endPos := s.mark()
if res.matched {
if endPos <= pos {
panic("bad memo")
}
} else if endPos != pos {
panic("bad memo")
}
memo[m] = &memoResult{result: res, endPos: endPos}
return s.check(m, res)
}
}
func (m *matchRef) detectLeftRec(r Rule, rs ruleSet) bool {
if !rs.Add(m.rule) {
return false
}
return m.rule == r || (m.rule != nil && m.rule.detectLeftRec(r, rs))
}
func (m *matchRef) print() string {
return m.name
}
// R returns a Ref type. These are used to create recursive rule sets where a rule
// is used before it's definition is created. Ref rules are memoized, meaning the
// value of the ref's rule and it's position in the stream are saved and returned
// to prevent constantly re-running the same rule on the same input. This
// is a key feature of Packrat parsing as it tames the time complexity of infinite
// backtracking to linear time.
//
// The value of the match is the value of the sub-rule.
func R(name string) Ref {
return &matchRef{name: name}
}
// Memo creates a rule that perform memoization as part of matching. Memoization is used
// to speed up matching.
//
// The value of the match is the value of the sub-rule.
func Memo(rule Rule) Rule {
r := R("")
r.Set(rule)
return r
}
// Values provides the same of rule values gathered. The names correspond
// to Named rules that were observed in the current scope.
type Values interface {
Get(name string) interface{}
}
type valMap map[string]interface{}
func (m valMap) Get(name string) interface{} {
return m[name]
}
type matchAction struct {
rule Rule
fn func(Values) interface{}
}
func (m *matchAction) match(s *state) result {
pos := s.mark()
res := m.rule.match(s)
if res.matched {
res.value = m.fn(s.values)
if sp, ok := res.value.(SetPositioner); ok {
sp.SetPosition(pos, s.mark())
}
}
return s.check(m, res)
}
func (m *matchAction) detectLeftRec(r Rule, rs ruleSet) bool {
if !rs.Add(m.rule) {
return false
}
return m.rule == r || m.rule.detectLeftRec(r, rs)
}
func (m *matchAction) print() string {
return m.rule.print()
}
// Action returns a rule that when it's given rule is matched, the given
// function is called. The return value of the function becomes the rule's
// value. The Values argument contains all rule values observed in the curent
// rule scope (toplevel or from invoking a Ref).
//
// The value of the match is the return value of the given function.
func Action(r Rule, fn func(Values) interface{}) Rule {
return &matchScope{rule: &matchAction{rule: r, fn: fn}}
}
type matchApply struct {
rule Rule
typ reflect.Type
}
func (m *matchApply) match(s *state) result {
res := m.rule.match(s)
if res.matched {
res.value = m.expand(s)
}
return res
}
func (m *matchApply) expand(s *state) interface{} {
ret := reflect.New(m.typ)
rv := ret.Elem()
for i := 0; i < rv.NumField(); i++ {
ft := m.typ.Field(i)
if !ft.IsExported() {
continue
}
name := ft.Tag.Get("ast")
if name == "" {
name = ft.Name
}
if val := s.values.Get(name); val != nil {
rv.Field(i).Set(reflect.ValueOf(val))
}
}
return ret.Interface()
}
func (m *matchApply) detectLeftRec(r Rule, rs ruleSet) bool {
if !rs.Add(m.rule) {
return false
}
return m.rule == r || m.rule.detectLeftRec(r, rs)
}
func (m *matchApply) print() string {
return m.rule.print()
}
// Apply returns a rule that when it's given rule matches, it will
// make a new struct and attempt to assign rule values in scope
// to the members of the struct. The struct type is computed from
// the argument v and then saved to be used at match time.
// The value names should exactly match the struct fields OR if
// the struct fields use the `ast:` tag, it will be used to look
// for values.
//
// For example, given:
// type Node struct {
// Age int `ast:"age"`
// }
//
// Apply(Named("age", numberRule), Node{})
//
// When the above Apply matches, the value from numberRule will be assigned
// to a new value of Node.
//
// The value of the match is the newly created and populated struct.
func Apply(rule Rule, v interface{}) Rule {
rv := reflect.ValueOf(v)
for rv.Kind() == reflect.Pointer {
rv = rv.Elem()
}
if rv.Kind() != reflect.Struct {
panic("apply must be passed a struct to infer the type of")
}
return &matchApply{
rule: rule,
typ: rv.Type(),
}
}
type matchScope struct {
rule Rule
}
func (m *matchScope) match(s *state) result {
curValues := s.values
defer func() {
s.values = curValues
}()
v := make(valMap)
s.values = v
return s.check(m, m.rule.match(s))
}
func (m *matchScope) detectLeftRec(r Rule, rs ruleSet) bool {
if !rs.Add(m.rule) {
return false
}
return m.rule == r || m.rule.detectLeftRec(r, rs)
}
func (m *matchScope) print() string {
return m.rule.print()
}
// Scope introduces a new rule scope. This is generally not needed as
// most users will use the automatically created scope from an Action rule.
//
// The value of the match is the value of the sub-rule.
func Scope(rule Rule) Rule {
return &matchScope{rule: rule}
}
type matchNamed struct {
name string
rule Rule
}
func (m *matchNamed) match(s *state) result {
res := m.rule.match(s)
if res.matched {
if s.p.debug {
fmt.Printf("N (%p) %s => %v\n", s.values, m.name, res.value)
}
s.values[m.name] = res.value
}
return s.check(m, res)
}
func (m *matchNamed) detectLeftRec(r Rule, rs ruleSet) bool {
if !rs.Add(m.rule) {
return false
}
return m.rule == r || m.rule.detectLeftRec(r, rs)
}
func (m *matchNamed) print() string {
return fmt.Sprintf("%s:%s", m.rule.print(), m.name)
}
// Named will assign the value of the given rule to the current rule scope
// if it matches.
//
// The value of the match is the value of the sub-rule.
func Named(name string, rule Rule) Rule {
return &matchNamed{name: name, rule: rule}
}
type matchTransform struct {
rule Rule
fn func(str string) interface{}
}
func (m *matchTransform) match(s *state) result {
pos := s.mark()
res := m.rule.match(s)
if res.matched {
res.value = m.fn(s.input[pos:s.mark()])
if sp, ok := res.value.(SetPositioner); ok {
sp.SetPosition(pos, s.mark())
}
}
return s.check(m, res)
}
func (m *matchTransform) detectLeftRec(r Rule, rs ruleSet) bool {
if !rs.Add(m.rule) {
return false
}
return m.rule == r || m.rule.detectLeftRec(r, rs)
}
func (m *matchTransform) print() string {
return m.rule.print()
}
// Transform returns a Rule that invokes it's given rule and if it matches
// calls the given function, passing the section of the input stream that
// was matched. The return value becomes the value of the rule.
//
// The value of the match is the return value of the given function.
func Transform(r Rule, fn func(string) interface{}) Rule {
return &matchTransform{rule: r, fn: fn}
}
type matchCapture struct {
rule Rule
}
func (m *matchCapture) match(s *state) result {
pos := s.mark()
res := m.rule.match(s)
if res.matched {
res.value = s.input[pos:s.mark()]
}
return s.check(m, res)
}
func (m *matchCapture) detectLeftRec(r Rule, rs ruleSet) bool {
if !rs.Add(m.rule) {
return false
}
return m.rule == r || m.rule.detectLeftRec(r, rs)
}
func (m *matchCapture) print() string {
return fmt.Sprintf("< %s >", m.rule.print())
}
// Capture returns a Rule that attempts to match it's given rule. If it
// matches, the value of the rule is set to the section of the input stream
// that was matched. Said another way, Capture pulls the matched text up
// as a value.
//
// The value of the match is portion of the input stream that matched
// the sub-rule.
func Capture(r Rule) Rule {
return &matchCapture{rule: r}
}
type matchCheckAction struct {
rule Rule
fn func(vals Values) bool
}
func (m *matchCheckAction) match(s *state) result {
defer s.restore(s.mark())
if m.fn(s.values) {
s.good(m)
return result{matched: true}
}
s.bad(m)
return result{}
}
func (m *matchCheckAction) detectLeftRec(r Rule, rs ruleSet) bool {
if !rs.Add(m.rule) {
return false
}
return m.rule == r || m.rule.detectLeftRec(r, rs)
}
// CheckAction returns a rule that when a match is attempted, calls the given
// function. If the function returns true, the match succeeds. This corresponds with
// check functions ("&{ a > 2}") style constructions in other PEGs. The Values
// argument provides access to the current scope.
//
// The value of the match is nil.
func CheckAction(fn func(Values) bool) Rule {
return &matchCheckAction{fn: fn}
}
func (m *matchCheckAction) print() string {
return "&<go-func>"
}