-
Notifications
You must be signed in to change notification settings - Fork 8
/
parse-edif.go
1831 lines (1634 loc) · 42.9 KB
/
parse-edif.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
// Code generated by pigeon; DO NOT EDIT.
// This file is part of edif2qmasm. It implements a parser for the Electronic
// Design Interchange Format (EDIF). It basically just reads an EDIF file into
// a hierarchical format for later processing.
package main
import (
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"math"
"os"
"sort"
"strconv"
"strings"
"sync"
"unicode"
"unicode/utf8"
)
var g = &grammar{
rules: []*rule{
{
name: "TopLevel",
pos: position{line: 11, col: 1, offset: 274},
expr: &actionExpr{
pos: position{line: 11, col: 13, offset: 286},
run: (*parser).callonTopLevel1,
expr: &seqExpr{
pos: position{line: 11, col: 13, offset: 286},
exprs: []interface{}{
&ruleRefExpr{
pos: position{line: 11, col: 13, offset: 286},
name: "Skip",
},
&labeledExpr{
pos: position{line: 11, col: 18, offset: 291},
label: "s",
expr: &ruleRefExpr{
pos: position{line: 11, col: 20, offset: 293},
name: "SExp",
},
},
&ruleRefExpr{
pos: position{line: 11, col: 25, offset: 298},
name: "Skip",
},
&ruleRefExpr{
pos: position{line: 11, col: 30, offset: 303},
name: "EOF",
},
},
},
},
},
{
name: "Digit",
pos: position{line: 20, col: 1, offset: 507},
expr: &charClassMatcher{
pos: position{line: 20, col: 10, offset: 516},
val: "[\\p{Nd}]",
classes: []*unicode.RangeTable{rangeTable("Nd")},
ignoreCase: false,
inverted: false,
},
},
{
name: "Whitespace",
pos: position{line: 23, col: 1, offset: 591},
expr: &charClassMatcher{
pos: position{line: 23, col: 15, offset: 605},
val: "[\\p{Zs}\\n\\r\\t]",
chars: []rune{'\n', '\r', '\t'},
classes: []*unicode.RangeTable{rangeTable("Zs")},
ignoreCase: false,
inverted: false,
},
},
{
name: "Skip",
pos: position{line: 26, col: 1, offset: 700},
expr: &zeroOrMoreExpr{
pos: position{line: 26, col: 9, offset: 708},
expr: &ruleRefExpr{
pos: position{line: 26, col: 9, offset: 708},
name: "Whitespace",
},
},
},
{
name: "Symbol",
pos: position{line: 30, col: 1, offset: 862},
expr: &actionExpr{
pos: position{line: 30, col: 11, offset: 872},
run: (*parser).callonSymbol1,
expr: &seqExpr{
pos: position{line: 30, col: 11, offset: 872},
exprs: []interface{}{
&charClassMatcher{
pos: position{line: 30, col: 11, offset: 872},
val: "[\\p{Lu}\\p{Ll}_]",
chars: []rune{'_'},
classes: []*unicode.RangeTable{rangeTable("Lu"), rangeTable("Ll")},
ignoreCase: false,
inverted: false,
},
&zeroOrMoreExpr{
pos: position{line: 30, col: 27, offset: 888},
expr: &charClassMatcher{
pos: position{line: 30, col: 27, offset: 888},
val: "[^()\\p{Zs}\\n\\r\\t]",
chars: []rune{'(', ')', '\n', '\r', '\t'},
classes: []*unicode.RangeTable{rangeTable("Zs")},
ignoreCase: false,
inverted: true,
},
},
},
},
},
},
{
name: "Integer",
pos: position{line: 35, col: 1, offset: 982},
expr: &actionExpr{
pos: position{line: 35, col: 12, offset: 993},
run: (*parser).callonInteger1,
expr: &seqExpr{
pos: position{line: 35, col: 12, offset: 993},
exprs: []interface{}{
&zeroOrOneExpr{
pos: position{line: 35, col: 12, offset: 993},
expr: &charClassMatcher{
pos: position{line: 35, col: 12, offset: 993},
val: "[-+]",
chars: []rune{'-', '+'},
ignoreCase: false,
inverted: false,
},
},
&oneOrMoreExpr{
pos: position{line: 35, col: 18, offset: 999},
expr: &ruleRefExpr{
pos: position{line: 35, col: 18, offset: 999},
name: "Digit",
},
},
},
},
},
},
{
name: "String",
pos: position{line: 45, col: 1, offset: 1255},
expr: &choiceExpr{
pos: position{line: 45, col: 11, offset: 1265},
alternatives: []interface{}{
&actionExpr{
pos: position{line: 45, col: 11, offset: 1265},
run: (*parser).callonString2,
expr: &seqExpr{
pos: position{line: 45, col: 11, offset: 1265},
exprs: []interface{}{
&litMatcher{
pos: position{line: 45, col: 11, offset: 1265},
val: "\"",
ignoreCase: false,
want: "\"\\\"\"",
},
&litMatcher{
pos: position{line: 45, col: 15, offset: 1269},
val: "\\",
ignoreCase: false,
want: "\"\\\\\"",
},
&zeroOrMoreExpr{
pos: position{line: 45, col: 20, offset: 1274},
expr: &charClassMatcher{
pos: position{line: 45, col: 20, offset: 1274},
val: "[^\"]",
chars: []rune{'"'},
ignoreCase: false,
inverted: true,
},
},
&litMatcher{
pos: position{line: 45, col: 26, offset: 1280},
val: "\"",
ignoreCase: false,
want: "\"\\\"\"",
},
},
},
},
&actionExpr{
pos: position{line: 48, col: 5, offset: 1395},
run: (*parser).callonString9,
expr: &seqExpr{
pos: position{line: 48, col: 5, offset: 1395},
exprs: []interface{}{
&litMatcher{
pos: position{line: 48, col: 5, offset: 1395},
val: "\"",
ignoreCase: false,
want: "\"\\\"\"",
},
&zeroOrMoreExpr{
pos: position{line: 48, col: 9, offset: 1399},
expr: &choiceExpr{
pos: position{line: 48, col: 10, offset: 1400},
alternatives: []interface{}{
&ruleRefExpr{
pos: position{line: 48, col: 10, offset: 1400},
name: "EscapedChar",
},
&charClassMatcher{
pos: position{line: 48, col: 24, offset: 1414},
val: "[^\"]",
chars: []rune{'"'},
ignoreCase: false,
inverted: true,
},
},
},
},
&litMatcher{
pos: position{line: 48, col: 31, offset: 1421},
val: "\"",
ignoreCase: false,
want: "\"\\\"\"",
},
},
},
},
},
},
},
{
name: "EscapedChar",
pos: position{line: 55, col: 1, offset: 1627},
expr: &actionExpr{
pos: position{line: 55, col: 16, offset: 1642},
run: (*parser).callonEscapedChar1,
expr: &seqExpr{
pos: position{line: 55, col: 16, offset: 1642},
exprs: []interface{}{
&litMatcher{
pos: position{line: 55, col: 16, offset: 1642},
val: "\\",
ignoreCase: false,
want: "\"\\\\\"",
},
&anyMatcher{
line: 55, col: 21, offset: 1647,
},
},
},
},
},
{
name: "List",
pos: position{line: 71, col: 1, offset: 2068},
expr: &actionExpr{
pos: position{line: 71, col: 9, offset: 2076},
run: (*parser).callonList1,
expr: &seqExpr{
pos: position{line: 71, col: 9, offset: 2076},
exprs: []interface{}{
&litMatcher{
pos: position{line: 71, col: 9, offset: 2076},
val: "(",
ignoreCase: false,
want: "\"(\"",
},
&ruleRefExpr{
pos: position{line: 71, col: 13, offset: 2080},
name: "Skip",
},
&labeledExpr{
pos: position{line: 71, col: 18, offset: 2085},
label: "ss",
expr: &zeroOrOneExpr{
pos: position{line: 71, col: 21, offset: 2088},
expr: &seqExpr{
pos: position{line: 71, col: 22, offset: 2089},
exprs: []interface{}{
&ruleRefExpr{
pos: position{line: 71, col: 22, offset: 2089},
name: "SExp",
},
&zeroOrMoreExpr{
pos: position{line: 71, col: 27, offset: 2094},
expr: &ruleRefExpr{
pos: position{line: 71, col: 27, offset: 2094},
name: "AnotherSExp",
},
},
},
},
},
},
&ruleRefExpr{
pos: position{line: 71, col: 42, offset: 2109},
name: "Skip",
},
&litMatcher{
pos: position{line: 71, col: 47, offset: 2114},
val: ")",
ignoreCase: false,
want: "\")\"",
},
},
},
},
},
{
name: "SExp",
pos: position{line: 120, col: 1, offset: 3902},
expr: &choiceExpr{
pos: position{line: 120, col: 9, offset: 3910},
alternatives: []interface{}{
&ruleRefExpr{
pos: position{line: 120, col: 9, offset: 3910},
name: "Symbol",
},
&ruleRefExpr{
pos: position{line: 120, col: 18, offset: 3919},
name: "String",
},
&ruleRefExpr{
pos: position{line: 120, col: 27, offset: 3928},
name: "Integer",
},
&ruleRefExpr{
pos: position{line: 120, col: 37, offset: 3938},
name: "List",
},
},
},
},
{
name: "AnotherSExp",
pos: position{line: 123, col: 1, offset: 4007},
expr: &actionExpr{
pos: position{line: 123, col: 16, offset: 4022},
run: (*parser).callonAnotherSExp1,
expr: &seqExpr{
pos: position{line: 123, col: 16, offset: 4022},
exprs: []interface{}{
&oneOrMoreExpr{
pos: position{line: 123, col: 16, offset: 4022},
expr: &ruleRefExpr{
pos: position{line: 123, col: 16, offset: 4022},
name: "Whitespace",
},
},
&labeledExpr{
pos: position{line: 123, col: 28, offset: 4034},
label: "s",
expr: &ruleRefExpr{
pos: position{line: 123, col: 30, offset: 4036},
name: "SExp",
},
},
},
},
},
},
{
name: "EOF",
pos: position{line: 132, col: 1, offset: 4235},
expr: ¬Expr{
pos: position{line: 132, col: 8, offset: 4242},
expr: &anyMatcher{
line: 132, col: 9, offset: 4243,
},
},
},
},
}
func (c *current) onTopLevel1(s interface{}) (interface{}, error) {
sexp, ok := s.(EdifSExp)
if !ok {
return nil, fmt.Errorf("Failed to parse %q", c.text)
}
return sexp, nil
}
func (p *parser) callonTopLevel1() (interface{}, error) {
stack := p.vstack[len(p.vstack)-1]
_ = stack
return p.cur.onTopLevel1(stack["s"])
}
func (c *current) onSymbol1() (interface{}, error) {
return EdifSymbol(c.text), nil
}
func (p *parser) callonSymbol1() (interface{}, error) {
stack := p.vstack[len(p.vstack)-1]
_ = stack
return p.cur.onSymbol1()
}
func (c *current) onInteger1() (interface{}, error) {
num, err := strconv.Atoi(string(c.text))
if err != nil {
return nil, err
}
return EdifInteger(num), nil
}
func (p *parser) callonInteger1() (interface{}, error) {
stack := p.vstack[len(p.vstack)-1]
_ = stack
return p.cur.onInteger1()
}
func (c *current) onString2() (interface{}, error) {
// Verilog symbol beginning with a "\"
return EdifString(c.text[1 : len(c.text)-1]), nil
}
func (p *parser) callonString2() (interface{}, error) {
stack := p.vstack[len(p.vstack)-1]
_ = stack
return p.cur.onString2()
}
func (c *current) onString9() (interface{}, error) {
// String with ordinary character escapes
return EdifString(c.text[1 : len(c.text)-1]), nil
}
func (p *parser) callonString9() (interface{}, error) {
stack := p.vstack[len(p.vstack)-1]
_ = stack
return p.cur.onString9()
}
func (c *current) onEscapedChar1() (interface{}, error) {
switch c.text[1] {
case '\\', '"':
return c.text[1], nil
case 'n':
return '\n', nil
case 't':
return '\t', nil
case 'r':
return '\r', nil
default:
return "", fmt.Errorf("Unrecognized escape sequence \"\\%c\"", c.text[1])
}
}
func (p *parser) callonEscapedChar1() (interface{}, error) {
stack := p.vstack[len(p.vstack)-1]
_ = stack
return p.cur.onEscapedChar1()
}
func (c *current) onList1(ss interface{}) (interface{}, error) {
// Handle the trivial case first.
if ss == nil {
// Zero-element list
return make(EdifList, 0), nil
}
// On a failed assertion in the remaining cases, return an internal
// error to our parent.
return func() (data interface{}, err error) {
// Set up error handling.
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("Internal error parsing %q", c.text)
}
}()
var ok bool
checkAssert := func() {
if !ok {
panic("Internal edif.go parse error")
}
}
// We expect to have either a one- or two-element list of
// s-expressions.
ssList, ok := ss.([]interface{})
checkAssert()
if len(ssList) == 0 {
return nil, fmt.Errorf("Internal error: unexpected zero-element list")
}
ssHead, ok := ssList[0].(EdifSExp)
checkAssert()
if len(ssList) == 1 {
// One-element list
return []EdifSExp{ssHead}, nil
}
ssList, ok = ssList[1].([]interface{})
checkAssert()
sexps := make(EdifList, len(ssList)+1)
sexps[0] = ssHead
for i, s := range ssList {
sexps[i+1], ok = s.(EdifSExp)
checkAssert()
}
return sexps, nil
}()
}
func (p *parser) callonList1() (interface{}, error) {
stack := p.vstack[len(p.vstack)-1]
_ = stack
return p.cur.onList1(stack["ss"])
}
func (c *current) onAnotherSExp1(s interface{}) (interface{}, error) {
sexp, ok := s.(EdifSExp)
if !ok {
return nil, fmt.Errorf("Internal error parsing %#v", s)
}
return sexp, nil
}
func (p *parser) callonAnotherSExp1() (interface{}, error) {
stack := p.vstack[len(p.vstack)-1]
_ = stack
return p.cur.onAnotherSExp1(stack["s"])
}
var (
// errNoRule is returned when the grammar to parse has no rule.
errNoRule = errors.New("grammar has no rule")
// errInvalidEntrypoint is returned when the specified entrypoint rule
// does not exit.
errInvalidEntrypoint = errors.New("invalid entrypoint")
// errInvalidEncoding is returned when the source is not properly
// utf8-encoded.
errInvalidEncoding = errors.New("invalid encoding")
// errMaxExprCnt is used to signal that the maximum number of
// expressions have been parsed.
errMaxExprCnt = errors.New("max number of expresssions parsed")
)
// 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
// MaxExpressions creates an Option to stop parsing after the provided
// number of expressions have been parsed, if the value is 0 then the parser will
// parse for as many steps as needed (possibly an infinite number).
//
// The default for maxExprCnt is 0.
func MaxExpressions(maxExprCnt uint64) Option {
return func(p *parser) Option {
oldMaxExprCnt := p.maxExprCnt
p.maxExprCnt = maxExprCnt
return MaxExpressions(oldMaxExprCnt)
}
}
// Entrypoint creates an Option to set the rule name to use as entrypoint.
// The rule name must have been specified in the -alternate-entrypoints
// if generating the parser with the -optimize-grammar flag, otherwise
// it may have been optimized out. Passing an empty string sets the
// entrypoint to the first rule in the grammar.
//
// The default is to start parsing at the first rule in the grammar.
func Entrypoint(ruleName string) Option {
return func(p *parser) Option {
oldEntrypoint := p.entrypoint
p.entrypoint = ruleName
if ruleName == "" {
p.entrypoint = g.rules[0].name
}
return Entrypoint(oldEntrypoint)
}
}
// Statistics adds a user provided Stats struct to the parser to allow
// the user to process the results after the parsing has finished.
// Also the key for the "no match" counter is set.
//
// Example usage:
//
// input := "input"
// stats := Stats{}
// _, err := Parse("input-file", []byte(input), Statistics(&stats, "no match"))
// if err != nil {
// log.Panicln(err)
// }
// b, err := json.MarshalIndent(stats.ChoiceAltCnt, "", " ")
// if err != nil {
// log.Panicln(err)
// }
// fmt.Println(string(b))
//
func Statistics(stats *Stats, choiceNoMatch string) Option {
return func(p *parser) Option {
oldStats := p.Stats
p.Stats = stats
oldChoiceNoMatch := p.choiceNoMatch
p.choiceNoMatch = choiceNoMatch
if p.Stats.ChoiceAltCnt == nil {
p.Stats.ChoiceAltCnt = make(map[string]map[string]int)
}
return Statistics(oldStats, oldChoiceNoMatch)
}
}
// 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)
}
}
// AllowInvalidUTF8 creates an Option to allow invalid UTF-8 bytes.
// Every invalid UTF-8 byte is treated as a utf8.RuneError (U+FFFD)
// by character class matchers and is matched by the any matcher.
// The returned matched value, c.text and c.offset are NOT affected.
//
// The default is false.
func AllowInvalidUTF8(b bool) Option {
return func(p *parser) Option {
old := p.allowInvalidUTF8
p.allowInvalidUTF8 = b
return AllowInvalidUTF8(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)
}
}
// GlobalStore creates an Option to set a key to a certain value in
// the globalStore.
func GlobalStore(key string, value interface{}) Option {
return func(p *parser) Option {
old := p.cur.globalStore[key]
p.cur.globalStore[key] = value
return GlobalStore(key, old)
}
}
// InitState creates an Option to set a key to a certain value in
// the global "state" store.
func InitState(key string, value interface{}) Option {
return func(p *parser) Option {
old := p.cur.state[key]
p.cur.state[key] = value
return InitState(key, old)
}
}
// ParseFile parses the file identified by filename.
func ParseFile(filename string, opts ...Option) (i interface{}, err error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer func() {
if closeErr := f.Close(); closeErr != nil {
err = closeErr
}
}()
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 strconv.Itoa(p.line) + ":" + strconv.Itoa(p.col) + " [" + strconv.Itoa(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
// state is a store for arbitrary key,value pairs that the user wants to be
// tied to the backtracking of the parser.
// This is always rolled back if a parsing rule fails.
state storeDict
// globalStore is a general store for the user to store arbitrary key-value
// pairs that they need to manage and that they do not want tied to the
// backtracking of the parser. This is only modified by the user and never
// rolled back by the parser. It is always up to the user to keep this in a
// consistent state.
globalStore storeDict
}
type storeDict map[string]interface{}
// 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 recoveryExpr struct {
pos position
expr interface{}
recoverExpr interface{}
failureLabel []string
}
type seqExpr struct {
pos position
exprs []interface{}
}
type throwExpr struct {
pos position
label string
}
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 stateCodeExpr struct {
pos position
run func(*parser) error
}
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
want string
}
type charClassMatcher struct {
pos position
val string
basicLatinChars [128]bool
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
expected []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 {
stats := Stats{
ChoiceAltCnt: make(map[string]map[string]int),
}
p := &parser{
filename: filename,
errs: new(errList),
data: b,
pt: savepoint{position: position{line: 1}},
recover: true,
cur: current{
state: make(storeDict),
globalStore: make(storeDict),
},
maxFailPos: position{col: 1, line: 1},
maxFailExpected: make([]string, 0, 20),
Stats: &stats,
// start rule is rule [0] unless an alternate entrypoint is specified
entrypoint: g.rules[0].name,
}
p.setOptions(opts)
if p.maxExprCnt == 0 {
p.maxExprCnt = math.MaxUint64
}
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
}
const choiceNoMatch = -1
// Stats stores some statistics, gathered during parsing
type Stats struct {
// ExprCnt counts the number of expressions processed during parsing
// This value is compared to the maximum number of expressions allowed
// (set by the MaxExpressions option).
ExprCnt uint64
// ChoiceAltCnt is used to count for each ordered choice expression,
// which alternative is used how may times.
// These numbers allow to optimize the order of the ordered choice expression
// to increase the performance of the parser
//
// The outer key of ChoiceAltCnt is composed of the name of the rule as well
// as the line and the column of the ordered choice.
// The inner key of ChoiceAltCnt is the number (one-based) of the matching alternative.
// For each alternative the number of matches are counted. If an ordered choice does not
// match, a special counter is incremented. The name of this counter is set with
// the parser option Statistics.
// For an alternative to be included in ChoiceAltCnt, it has to match at least once.
ChoiceAltCnt map[string]map[string]int
}
type parser struct {
filename string
pt savepoint
cur current
data []byte
errs *errList
depth int
recover bool
debug bool
memoize bool
// memoization table for the packrat algorithm:
// map[offset in source] map[expression or rule] {value, match}