/
calculator.go
1309 lines (1171 loc) · 27.8 KB
/
calculator.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
// Command calculator is a small PEG-generated parser that computes
// simple math using integers.
//
// Example usage: $ calculator "3 + (2 - 5 * 12)"
//
// Inspired by pegjs arithmetic example:
// https://github.com/pegjs/pegjs/blob/master/examples/arithmetics.pegjs
//
package main
import (
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"strconv"
"strings"
"unicode"
"unicode/utf8"
)
var ops = map[string]func(int, int) int{
"+": func(l, r int) int {
return l + r
},
"-": func(l, r int) int {
return l - r
},
"*": func(l, r int) int {
return l * r
},
"/": func(l, r int) int {
return l / r
},
}
// for testing purpose
var cntCodeBlocks int
func main() {
if len(os.Args) != 2 {
log.Fatal("Usage: calculator 'EXPR'")
}
got, err := ParseReader("", strings.NewReader(os.Args[1]))
if err != nil {
log.Fatal(err)
}
fmt.Println("=", got)
}
func toIfaceSlice(v interface{}) []interface{} {
if v == nil {
return nil
}
return v.([]interface{})
}
func eval(first, rest interface{}) int {
l := first.(int)
restSl := toIfaceSlice(rest)
for _, v := range restSl {
restExpr := toIfaceSlice(v)
r := restExpr[3].(int)
op := restExpr[1].(string)
l = ops[op](l, r)
}
return l
}
var g = &grammar{
rules: []*rule{
{
name: "Input",
pos: position{line: 61, col: 1, offset: 1247},
expr: &actionExpr{
pos: position{line: 61, col: 10, offset: 1256},
run: (*parser).callonInput1,
expr: &seqExpr{
pos: position{line: 61, col: 10, offset: 1256},
exprs: []interface{}{
&labeledExpr{
pos: position{line: 61, col: 10, offset: 1256},
label: "expr",
expr: &ruleRefExpr{
pos: position{line: 61, col: 15, offset: 1261},
name: "Expr",
},
},
&ruleRefExpr{
pos: position{line: 61, col: 20, offset: 1266},
name: "EOF",
},
},
},
},
},
{
name: "Expr",
pos: position{line: 66, col: 1, offset: 1316},
expr: &actionExpr{
pos: position{line: 66, col: 9, offset: 1324},
run: (*parser).callonExpr1,
expr: &seqExpr{
pos: position{line: 66, col: 9, offset: 1324},
exprs: []interface{}{
&ruleRefExpr{
pos: position{line: 66, col: 9, offset: 1324},
name: "_",
},
&labeledExpr{
pos: position{line: 66, col: 11, offset: 1326},
label: "first",
expr: &ruleRefExpr{
pos: position{line: 66, col: 17, offset: 1332},
name: "Term",
},
},
&labeledExpr{
pos: position{line: 66, col: 22, offset: 1337},
label: "rest",
expr: &zeroOrMoreExpr{
pos: position{line: 66, col: 27, offset: 1342},
expr: &seqExpr{
pos: position{line: 66, col: 29, offset: 1344},
exprs: []interface{}{
&ruleRefExpr{
pos: position{line: 66, col: 29, offset: 1344},
name: "_",
},
&ruleRefExpr{
pos: position{line: 66, col: 31, offset: 1346},
name: "AddOp",
},
&ruleRefExpr{
pos: position{line: 66, col: 37, offset: 1352},
name: "_",
},
&ruleRefExpr{
pos: position{line: 66, col: 39, offset: 1354},
name: "Term",
},
},
},
},
},
&ruleRefExpr{
pos: position{line: 66, col: 47, offset: 1362},
name: "_",
},
},
},
},
},
{
name: "Term",
pos: position{line: 71, col: 1, offset: 1423},
expr: &actionExpr{
pos: position{line: 71, col: 9, offset: 1431},
run: (*parser).callonTerm1,
expr: &seqExpr{
pos: position{line: 71, col: 9, offset: 1431},
exprs: []interface{}{
&labeledExpr{
pos: position{line: 71, col: 9, offset: 1431},
label: "first",
expr: &ruleRefExpr{
pos: position{line: 71, col: 15, offset: 1437},
name: "Factor",
},
},
&labeledExpr{
pos: position{line: 71, col: 22, offset: 1444},
label: "rest",
expr: &zeroOrMoreExpr{
pos: position{line: 71, col: 27, offset: 1449},
expr: &seqExpr{
pos: position{line: 71, col: 29, offset: 1451},
exprs: []interface{}{
&ruleRefExpr{
pos: position{line: 71, col: 29, offset: 1451},
name: "_",
},
&ruleRefExpr{
pos: position{line: 71, col: 31, offset: 1453},
name: "MulOp",
},
&ruleRefExpr{
pos: position{line: 71, col: 37, offset: 1459},
name: "_",
},
&ruleRefExpr{
pos: position{line: 71, col: 39, offset: 1461},
name: "Factor",
},
},
},
},
},
},
},
},
},
{
name: "Factor",
pos: position{line: 76, col: 1, offset: 1530},
expr: &choiceExpr{
pos: position{line: 76, col: 11, offset: 1540},
alternatives: []interface{}{
&actionExpr{
pos: position{line: 76, col: 11, offset: 1540},
run: (*parser).callonFactor2,
expr: &seqExpr{
pos: position{line: 76, col: 11, offset: 1540},
exprs: []interface{}{
&litMatcher{
pos: position{line: 76, col: 11, offset: 1540},
val: "(",
ignoreCase: false,
},
&labeledExpr{
pos: position{line: 76, col: 15, offset: 1544},
label: "expr",
expr: &ruleRefExpr{
pos: position{line: 76, col: 20, offset: 1549},
name: "Expr",
},
},
&litMatcher{
pos: position{line: 76, col: 25, offset: 1554},
val: ")",
ignoreCase: false,
},
},
},
},
&actionExpr{
pos: position{line: 79, col: 5, offset: 1605},
run: (*parser).callonFactor8,
expr: &labeledExpr{
pos: position{line: 79, col: 5, offset: 1605},
label: "integer",
expr: &ruleRefExpr{
pos: position{line: 79, col: 13, offset: 1613},
name: "Integer",
},
},
},
},
},
},
{
name: "AddOp",
pos: position{line: 84, col: 1, offset: 1670},
expr: &actionExpr{
pos: position{line: 84, col: 10, offset: 1679},
run: (*parser).callonAddOp1,
expr: &choiceExpr{
pos: position{line: 84, col: 12, offset: 1681},
alternatives: []interface{}{
&litMatcher{
pos: position{line: 84, col: 12, offset: 1681},
val: "+",
ignoreCase: false,
},
&litMatcher{
pos: position{line: 84, col: 18, offset: 1687},
val: "-",
ignoreCase: false,
},
},
},
},
},
{
name: "MulOp",
pos: position{line: 89, col: 1, offset: 1749},
expr: &actionExpr{
pos: position{line: 89, col: 10, offset: 1758},
run: (*parser).callonMulOp1,
expr: &choiceExpr{
pos: position{line: 89, col: 12, offset: 1760},
alternatives: []interface{}{
&litMatcher{
pos: position{line: 89, col: 12, offset: 1760},
val: "*",
ignoreCase: false,
},
&litMatcher{
pos: position{line: 89, col: 18, offset: 1766},
val: "/",
ignoreCase: false,
},
},
},
},
},
{
name: "Integer",
pos: position{line: 94, col: 1, offset: 1828},
expr: &actionExpr{
pos: position{line: 94, col: 12, offset: 1839},
run: (*parser).callonInteger1,
expr: &seqExpr{
pos: position{line: 94, col: 12, offset: 1839},
exprs: []interface{}{
&zeroOrOneExpr{
pos: position{line: 94, col: 12, offset: 1839},
expr: &litMatcher{
pos: position{line: 94, col: 12, offset: 1839},
val: "-",
ignoreCase: false,
},
},
&oneOrMoreExpr{
pos: position{line: 94, col: 17, offset: 1844},
expr: &charClassMatcher{
pos: position{line: 94, col: 17, offset: 1844},
val: "[0-9]",
ranges: []rune{'0', '9'},
ignoreCase: false,
inverted: false,
},
},
},
},
},
},
{
name: "_",
displayName: "\"whitespace\"",
pos: position{line: 99, col: 1, offset: 1916},
expr: &zeroOrMoreExpr{
pos: position{line: 99, col: 19, offset: 1934},
expr: &charClassMatcher{
pos: position{line: 99, col: 19, offset: 1934},
val: "[ \\n\\t\\r]",
chars: []rune{' ', '\n', '\t', '\r'},
ignoreCase: false,
inverted: false,
},
},
},
{
name: "EOF",
pos: position{line: 101, col: 1, offset: 1946},
expr: ¬Expr{
pos: position{line: 101, col: 8, offset: 1953},
expr: &anyMatcher{
line: 101, col: 9, offset: 1954,
},
},
},
},
}
func (c *current) onInput1(expr interface{}) (interface{}, error) {
cntCodeBlocks++
return expr, nil
}
func (p *parser) callonInput1() (interface{}, error) {
stack := p.vstack[len(p.vstack)-1]
_ = stack
return p.cur.onInput1(stack["expr"])
}
func (c *current) onExpr1(first, rest interface{}) (interface{}, error) {
cntCodeBlocks++
return eval(first, rest), nil
}
func (p *parser) callonExpr1() (interface{}, error) {
stack := p.vstack[len(p.vstack)-1]
_ = stack
return p.cur.onExpr1(stack["first"], stack["rest"])
}
func (c *current) onTerm1(first, rest interface{}) (interface{}, error) {
cntCodeBlocks++
return eval(first, rest), nil
}
func (p *parser) callonTerm1() (interface{}, error) {
stack := p.vstack[len(p.vstack)-1]
_ = stack
return p.cur.onTerm1(stack["first"], stack["rest"])
}
func (c *current) onFactor2(expr interface{}) (interface{}, error) {
cntCodeBlocks++
return expr, nil
}
func (p *parser) callonFactor2() (interface{}, error) {
stack := p.vstack[len(p.vstack)-1]
_ = stack
return p.cur.onFactor2(stack["expr"])
}
func (c *current) onFactor8(integer interface{}) (interface{}, error) {
cntCodeBlocks++
return integer, nil
}
func (p *parser) callonFactor8() (interface{}, error) {
stack := p.vstack[len(p.vstack)-1]
_ = stack
return p.cur.onFactor8(stack["integer"])
}
func (c *current) onAddOp1() (interface{}, error) {
cntCodeBlocks++
return string(c.text), nil
}
func (p *parser) callonAddOp1() (interface{}, error) {
stack := p.vstack[len(p.vstack)-1]
_ = stack
return p.cur.onAddOp1()
}
func (c *current) onMulOp1() (interface{}, error) {
cntCodeBlocks++
return string(c.text), nil
}
func (p *parser) callonMulOp1() (interface{}, error) {
stack := p.vstack[len(p.vstack)-1]
_ = stack
return p.cur.onMulOp1()
}
func (c *current) onInteger1() (interface{}, error) {
cntCodeBlocks++
return strconv.Atoi(string(c.text))
}
func (p *parser) callonInteger1() (interface{}, error) {
stack := p.vstack[len(p.vstack)-1]
_ = stack
return p.cur.onInteger1()
}
var (
// errNoRule is returned when the grammar to parse has no rule.
errNoRule = errors.New("grammar has no rule")
// errInvalidEncoding is returned when the source is not properly
// utf8-encoded.
errInvalidEncoding = errors.New("invalid encoding")
// errNoMatch is returned if no match could be found.
errNoMatch = errors.New("no match found")
)
// Option is a function that can set an option on the parser. It returns
// the previous setting as an Option.
type Option func(*parser) Option
// Debug creates an Option to set the debug flag to b. When set to true,
// debugging information is printed to stdout while parsing.
//
// The default is false.
func Debug(b bool) Option {
return func(p *parser) Option {
old := p.debug
p.debug = b
return Debug(old)
}
}
// Memoize creates an Option to set the memoize flag to b. When set to true,
// the parser will cache all results so each expression is evaluated only
// once. This guarantees linear parsing time even for pathological cases,
// at the expense of more memory and slower times for typical cases.
//
// The default is false.
func Memoize(b bool) Option {
return func(p *parser) Option {
old := p.memoize
p.memoize = b
return Memoize(old)
}
}
// Recover creates an Option to set the recover flag to b. When set to
// true, this causes the parser to recover from panics and convert it
// to an error. Setting it to false can be useful while debugging to
// access the full stack trace.
//
// The default is true.
func Recover(b bool) Option {
return func(p *parser) Option {
old := p.recover
p.recover = b
return Recover(old)
}
}
// ParseFile parses the file identified by filename.
func ParseFile(filename string, opts ...Option) (interface{}, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
return ParseReader(filename, f, opts...)
}
// ParseReader parses the data from r using filename as information in the
// error messages.
func ParseReader(filename string, r io.Reader, opts ...Option) (interface{}, error) {
b, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
return Parse(filename, b, opts...)
}
// Parse parses the data from b using filename as information in the
// error messages.
func Parse(filename string, b []byte, opts ...Option) (interface{}, error) {
return newParser(filename, b, opts...).parse(g)
}
// position records a position in the text.
type position struct {
line, col, offset int
}
func (p position) String() string {
return fmt.Sprintf("%d:%d [%d]", p.line, p.col, p.offset)
}
// savepoint stores all state required to go back to this point in the
// parser.
type savepoint struct {
position
rn rune
w int
}
type current struct {
pos position // start position of the match
text []byte // raw text of the match
}
// the AST types...
type grammar struct {
pos position
rules []*rule
}
type rule struct {
pos position
name string
displayName string
expr interface{}
}
type choiceExpr struct {
pos position
alternatives []interface{}
}
type actionExpr struct {
pos position
expr interface{}
run func(*parser) (interface{}, error)
}
type seqExpr struct {
pos position
exprs []interface{}
}
type labeledExpr struct {
pos position
label string
expr interface{}
}
type expr struct {
pos position
expr interface{}
}
type andExpr expr
type notExpr expr
type zeroOrOneExpr expr
type zeroOrMoreExpr expr
type oneOrMoreExpr expr
type ruleRefExpr struct {
pos position
name string
}
type andCodeExpr struct {
pos position
run func(*parser) (bool, error)
}
type notCodeExpr struct {
pos position
run func(*parser) (bool, error)
}
type litMatcher struct {
pos position
val string
ignoreCase bool
}
type charClassMatcher struct {
pos position
val string
chars []rune
ranges []rune
classes []*unicode.RangeTable
ignoreCase bool
inverted bool
}
type anyMatcher position
// errList cumulates the errors found by the parser.
type errList []error
func (e *errList) add(err error) {
*e = append(*e, err)
}
func (e errList) err() error {
if len(e) == 0 {
return nil
}
e.dedupe()
return e
}
func (e *errList) dedupe() {
var cleaned []error
set := make(map[string]bool)
for _, err := range *e {
if msg := err.Error(); !set[msg] {
set[msg] = true
cleaned = append(cleaned, err)
}
}
*e = cleaned
}
func (e errList) Error() string {
switch len(e) {
case 0:
return ""
case 1:
return e[0].Error()
default:
var buf bytes.Buffer
for i, err := range e {
if i > 0 {
buf.WriteRune('\n')
}
buf.WriteString(err.Error())
}
return buf.String()
}
}
// parserError wraps an error with a prefix indicating the rule in which
// the error occurred. The original error is stored in the Inner field.
type parserError struct {
Inner error
pos position
prefix string
}
// Error returns the error message.
func (p *parserError) Error() string {
return p.prefix + ": " + p.Inner.Error()
}
// newParser creates a parser with the specified input source and options.
func newParser(filename string, b []byte, opts ...Option) *parser {
p := &parser{
filename: filename,
errs: new(errList),
data: b,
pt: savepoint{position: position{line: 1}},
recover: true,
}
p.setOptions(opts)
return p
}
// setOptions applies the options to the parser.
func (p *parser) setOptions(opts []Option) {
for _, opt := range opts {
opt(p)
}
}
type resultTuple struct {
v interface{}
b bool
end savepoint
}
type parser struct {
filename string
pt savepoint
cur current
data []byte
errs *errList
recover bool
debug bool
depth int
memoize bool
// memoization table for the packrat algorithm:
// map[offset in source] map[expression or rule] {value, match}
memo map[int]map[interface{}]resultTuple
// rules table, maps the rule identifier to the rule node
rules map[string]*rule
// variables stack, map of label to value
vstack []map[string]interface{}
// rule stack, allows identification of the current rule in errors
rstack []*rule
// stats
exprCnt int
}
// push a variable set on the vstack.
func (p *parser) pushV() {
if cap(p.vstack) == len(p.vstack) {
// create new empty slot in the stack
p.vstack = append(p.vstack, nil)
} else {
// slice to 1 more
p.vstack = p.vstack[:len(p.vstack)+1]
}
// get the last args set
m := p.vstack[len(p.vstack)-1]
if m != nil && len(m) == 0 {
// empty map, all good
return
}
m = make(map[string]interface{})
p.vstack[len(p.vstack)-1] = m
}
// pop a variable set from the vstack.
func (p *parser) popV() {
// if the map is not empty, clear it
m := p.vstack[len(p.vstack)-1]
if len(m) > 0 {
// GC that map
p.vstack[len(p.vstack)-1] = nil
}
p.vstack = p.vstack[:len(p.vstack)-1]
}
func (p *parser) print(prefix, s string) string {
if !p.debug {
return s
}
fmt.Printf("%s %d:%d:%d: %s [%#U]\n",
prefix, p.pt.line, p.pt.col, p.pt.offset, s, p.pt.rn)
return s
}
func (p *parser) in(s string) string {
p.depth++
return p.print(strings.Repeat(" ", p.depth)+">", s)
}
func (p *parser) out(s string) string {
p.depth--
return p.print(strings.Repeat(" ", p.depth)+"<", s)
}
func (p *parser) addErr(err error) {
p.addErrAt(err, p.pt.position)
}
func (p *parser) addErrAt(err error, pos position) {
var buf bytes.Buffer
if p.filename != "" {
buf.WriteString(p.filename)
}
if buf.Len() > 0 {
buf.WriteString(":")
}
buf.WriteString(fmt.Sprintf("%d:%d (%d)", pos.line, pos.col, pos.offset))
if len(p.rstack) > 0 {
if buf.Len() > 0 {
buf.WriteString(": ")
}
rule := p.rstack[len(p.rstack)-1]
if rule.displayName != "" {
buf.WriteString("rule " + rule.displayName)
} else {
buf.WriteString("rule " + rule.name)
}
}
pe := &parserError{Inner: err, pos: pos, prefix: buf.String()}
p.errs.add(pe)
}
// read advances the parser to the next rune.
func (p *parser) read() {
p.pt.offset += p.pt.w
rn, n := utf8.DecodeRune(p.data[p.pt.offset:])
p.pt.rn = rn
p.pt.w = n
p.pt.col++
if rn == '\n' {
p.pt.line++
p.pt.col = 0
}
if rn == utf8.RuneError {
if n == 1 {
p.addErr(errInvalidEncoding)
}
}
}
// restore parser position to the savepoint pt.
func (p *parser) restore(pt savepoint) {
if p.debug {
defer p.out(p.in("restore"))
}
if pt.offset == p.pt.offset {
return
}
p.pt = pt
}
// get the slice of bytes from the savepoint start to the current position.
func (p *parser) sliceFrom(start savepoint) []byte {
return p.data[start.position.offset:p.pt.position.offset]
}
func (p *parser) getMemoized(node interface{}) (resultTuple, bool) {
if len(p.memo) == 0 {
return resultTuple{}, false
}
m := p.memo[p.pt.offset]
if len(m) == 0 {
return resultTuple{}, false
}
res, ok := m[node]
return res, ok
}
func (p *parser) setMemoized(pt savepoint, node interface{}, tuple resultTuple) {
if p.memo == nil {
p.memo = make(map[int]map[interface{}]resultTuple)
}
m := p.memo[pt.offset]
if m == nil {
m = make(map[interface{}]resultTuple)
p.memo[pt.offset] = m
}
m[node] = tuple
}
func (p *parser) buildRulesTable(g *grammar) {
p.rules = make(map[string]*rule, len(g.rules))
for _, r := range g.rules {
p.rules[r.name] = r
}
}
func (p *parser) parse(g *grammar) (val interface{}, err error) {
if len(g.rules) == 0 {
p.addErr(errNoRule)
return nil, p.errs.err()
}
// TODO : not super critical but this could be generated
p.buildRulesTable(g)
if p.recover {
// panic can be used in action code to stop parsing immediately
// and return the panic as an error.
defer func() {
if e := recover(); e != nil {
if p.debug {
defer p.out(p.in("panic handler"))
}
val = nil
switch e := e.(type) {
case error:
p.addErr(e)
default:
p.addErr(fmt.Errorf("%v", e))
}
err = p.errs.err()
}
}()
}
// start rule is rule [0]
p.read() // advance to first rune
val, ok := p.parseRule(g.rules[0])
if !ok {
if len(*p.errs) == 0 {
// make sure this doesn't go out silently
p.addErr(errNoMatch)
}
return nil, p.errs.err()
}
return val, p.errs.err()
}
func (p *parser) parseRule(rule *rule) (interface{}, bool) {
if p.debug {
defer p.out(p.in("parseRule " + rule.name))
}
if p.memoize {
res, ok := p.getMemoized(rule)
if ok {
p.restore(res.end)
return res.v, res.b
}
}
start := p.pt
p.rstack = append(p.rstack, rule)
p.pushV()
val, ok := p.parseExpr(rule.expr)
p.popV()
p.rstack = p.rstack[:len(p.rstack)-1]
if ok && p.debug {
p.print(strings.Repeat(" ", p.depth)+"MATCH", string(p.sliceFrom(start)))
}
if p.memoize {
p.setMemoized(start, rule, resultTuple{val, ok, p.pt})
}
return val, ok
}
func (p *parser) parseExpr(expr interface{}) (interface{}, bool) {
var pt savepoint
var ok bool
if p.memoize {
res, ok := p.getMemoized(expr)
if ok {
p.restore(res.end)
return res.v, res.b
}
pt = p.pt
}
p.exprCnt++
var val interface{}
switch expr := expr.(type) {
case *actionExpr:
val, ok = p.parseActionExpr(expr)
case *andCodeExpr:
val, ok = p.parseAndCodeExpr(expr)
case *andExpr:
val, ok = p.parseAndExpr(expr)
case *anyMatcher:
val, ok = p.parseAnyMatcher(expr)
case *charClassMatcher:
val, ok = p.parseCharClassMatcher(expr)
case *choiceExpr:
val, ok = p.parseChoiceExpr(expr)
case *labeledExpr:
val, ok = p.parseLabeledExpr(expr)
case *litMatcher:
val, ok = p.parseLitMatcher(expr)
case *notCodeExpr:
val, ok = p.parseNotCodeExpr(expr)
case *notExpr:
val, ok = p.parseNotExpr(expr)
case *oneOrMoreExpr:
val, ok = p.parseOneOrMoreExpr(expr)
case *ruleRefExpr: