This repository was archived by the owner on Nov 22, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
1622 lines (1486 loc) · 36.9 KB
/
main.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 2015 The YY Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Command yy processes yacc source code and produces three output files:
//
// - A Go file containing definitions of AST nodes.
//
// - A Go file containing documentation examples[0] of productions defined by the yacc grammar.
//
// - A new yacc file with automatic actions instantiating the AST nodes.
//
// Installation
//
// To install yy
//
// $ go get [-u] github.com/cznic/yy
//
// Online documentation
//
// http://godoc.org/github.com/cznic/yy
//
// Usage
//
// Invocation:
//
// $ yy [options] <input.y>
//
// Options
//
// Flags handled by the yy command:
//
// -ast string
// Output AST nodes definitions. (default "ast.go")
// -astExamples string
// Output AST examples. (default "ast_test.go")
// -astImport string
// Optional AST file imports.
// -exampleAST string
// Fuction to call to produce example ASTs. (default "exampleAST")
// -kind string
// Default node kind (rule case) field name. (default "kind")
// -namedCases
// Generate typed and named case numbers.
// -node string
// Default non terminal yacc type. (default "node")
// -o string
// Output yacc file. (default "parser.y")
// -pkg string
// Package name of generated Go files. Extract from input when blank.
// -prettyString string
// Fuction to stringify things nicely. (default "prettyString")
// -token string
// Default terminal yacc type. (default "Token")
// -tokenSep string
// AST examples token separator string. (default " ")
// -v string
// create grammar report (default "y.output")
// -yylex string
// Type of yacc's yylex. (default "*lexer")
//
// Changelog
//
// 2017-10-23: Added the case directive.
//
// Examples
//
// A partial example: see the testdata directory and files
//
// input: in.y
// output: ast.go
// output: ast_test.go
// output: out.y
//
// The three output files were generated by
//
// yy -o testdata/out.y -ast testdata/ast.go -astExamples testdata/ast_test.go testdata/in.y
//
// A more complete, working project using yy can be found at http://godoc.org/github.com/cznic/pl0
//
// Concepts
//
// Every rule is turned into a definition of a struct type in ast.go (adjust using the -ast flag). The fields of the type are a sum of all productions (cases) of the rule.
//
// Rule:
// Foo Bar // Case 0
// | Foo Baz // Case 1
//
// The generated type will be something like
//
// type Rule struct {
// Case in // In [0, 1].
// Bar *Bar
// Baz *Baz
// Foo *Foo
// }
//
// In the above, Foo and Bar fields will be non nill when Case is 0 and Foo and Baz fields will be non nil when Case is 1.
//
// The above holds when both Foo and Bar are non terminal symbols. If the production(s) contain also terminal symbols, all those symbols are turned into fields named Token with an optional numeric suffix when more than one non terminal appears in any of the production(s).
//
// Rule:
// Foo '+' Bar
// | Foo '[' NUMBER ']' Bar
//
// The generated type will be like
//
// type Rule struct {
// Case int // In [0, 1].
// Bar *Bar
// Baz *Baz
// Foo *Foo
// Token MyTokenType
// Token2 MyTokenType
// Token3 MyTokenType
// }
//
// In the above, Token will capture '+' when Case is 0. For Case 1, Token will capture '[', Token2 NUMBER and Token3 ']'.
//
// MyTokenType is the type defined in the yacc %union as in
//
// %union {
// node MyNodeType
// Token MyTokenType
// }
//
// It is assumed that the lexer passed as an argument to yyParse instantiantes the lval.Token field with additional token information, like the lexeme value, starting position in the file etc.
//
// Generated actions
//
// There's a direct mapping, though not in the same order, of yacc pseudo variables $1, $2, ... and fields of the generated node types. For every production not disabled by the yy:ignore direction, yy injects code for instantiating the AST node when the production is reduced. For example, this rule from input.y
//
// File:
// Prologue TopLevelDeclList
//
// having no semantic action is turned into
//
// File:
// Prologue TopLevelDeclList
// {
// $$ = &File{
// Prologue: $1.(*Prologue),
// TopLevelDeclList: $2.(*TopLevelDeclList).reverse(),
// }
// }
//
// in output.y. The default yacc type of AST nodes is 'node' and can be changed using the -node flag.
//
// Conventions
//
// Option-like rules, for example as in
//
// BlockOpt:
// | Block
//
// are converted into
//
// BlockOpt:
// /* empty */
// {
// $$ = (*BlockOpt)(nil)
// }
// | Block
// {
// $$ = &BlockOpt{
// Block: $1.(*Block),
// }
// }
//
// in output.y, ie. the empty case does not produce a &RuleOpt{}, but nil instead to conserve space.
//
// Generated examples depend on an user supplied function, by default named exampleAST, with a signature
//
// exampleAST(rule int, src string) interface{}
//
// This function is called with the production number, as assigned by goyacc and an example string generated by yy. exampleAST should parse the example string and return the AST created when production rule is reduced.
//
// When the project's parser is not yet working, a dummy exampleAST function returnin always nil is a workaround.
//
// Magic names
//
// yy inspects rule actions found in the input file. If the action code mentions identifier lx, yy asumes it refers to the yyLexer passed to yyParse. In that case code like
//
// lx := yylex.(*lexer)
//
// is injected near the beginning of the semantic action. The specific type into which the yylex parameter is type asserted is adjustable using the -yylex flag. Similarly, when identifier lhs is mentioned, a short variable definiton of variable lhs, like
//
// lhs := &Foo{...}
// $$ = lhs
//
// is injected into the output.y action, replacing the default generated action (see "Concepts")
//
// For example, an action in input.y
//
// | IdentifierList Type '=' ExpressionList
// {
// lhs.declare(lx.scope)
// }
//
// Produces
//
// {
// lx := yylex.(*lexer)
// lhs := &VarSpec{
// Case: 2,
// IdentifierList: $1.(*IdentifierList).reverse(),
// Type: $2.(*Type),
// Token: $3,
// ExpressionList: $4.(*ExpressionList).reverse(),
// }
// $$ = lhs
// lhs.declare(lx.scope)
// }
//
// in output.y.
//
// The AST examples generator depends on presence of the yy:token directive for all non constant terminal symbols or the presence of the constant token value as in this example
//
// %token /*yy:token "%c" */ IDENTIFIER "identifier"
// %token BREAK "break"
//
// Using fe
//
// The AST examples yy generates must be post processed by using the fe command (http://godoc.org/github.com/cznic/fe), for example
//
// $ go test -run ^Example[^_] | fe
//
// One of the reasons why this is not done automatically by yy is that the above command will succeed only after your project has a _working_ scanner/parser combination. That's not the case in the early stages.
//
// Directives
//
// yy recognizes specially formatted comments within the input as directives. All directive have the format
//
// //yy:command argument
//
// or
//
// /*yy:command argument */
//
// Note that the directive must follow immediately the comment opening. There must be no empty line(s) between the directive and the production it aplies to.
//
// Directive example
//
// For example
//
// //yy:example "foo * bar"
// Rule:
// Foo '*' Bar
// //yy:example "foo / bar"
// | Foo '/' Bar
//
// The argument of the example directive is a doubly quoted Go string. The string is used instead of an automatically generated example.
//
// Directive field
//
// For example
//
// //yy:field count int
// //yy:field flag bool
// Rule: Foo Bar
//
// The argument of the field directive is the text up to the end of the comment. The argument is added to the automatically generated fields of the node type of Rule.
//
// Directive ignore
//
// For example
//
// //yy:ignore
// Rule: Foo Bar
//
// The ignore directive has no arguments. The directive disables generating of the node type of Rule as well as generating code instantiating such node.
//
// Directive list
//
// For example
//
// //yy:list
// Rule:
// Item
// | Rule ',' Item
//
// The list directive has no arguments. yy by default detects all left recursive rules. When such rule has name having suffix 'List', yy automatically generates proper reversing of the rule items. Using the list directive enables the same when such a left recursive rule does not have suffix 'List' in its name.
//
// Directive token
//
// For example
//
// /*yy:token %c*/ IDENT
// /*yy:token %d*/ NUMBER
//
// The argument of the token directive is a doubly quoted Go string. The string is passed to a fmt.Sprinf call with an numeric argument chosen by yy that falls small ASCII letters. The resulting string is used to generate textual token values in examples.
//
// Directive case
//
// For example
//
// //yy:case Foo
// /*yy:case Bar */ NUMBER
//
// The argument of the case directive is an identifier, which is appended to
// the rule name to produce a symbolic and typed case number value. The type
// name is <RuleName>Case.
//
// Links
//
// Referenced from elsewhere:
//
// [0]: https://golang.org/pkg/testing/#hdr-Examples
package main
import (
"bufio"
"bytes"
"flag"
"fmt"
"go/ast"
"go/format"
"go/parser"
"go/scanner"
"go/token"
"io"
"log"
"os"
"sort"
"strconv"
"strings"
"github.com/cznic/mathutil"
yparser "github.com/cznic/parser/yacc"
"github.com/cznic/strutil"
"github.com/cznic/y"
)
const (
caution = "// Code generated by yy. DO NOT EDIT.\n\n"
magicLx = "lx"
magicLHS = "lhs"
)
var (
oAST = flag.String("ast", "ast.go", "Output AST nodes definitions.")
oASTExamples = flag.String("astExamples", "ast_test.go", "Output AST examples.")
oASTImport = flag.String("astImport", "", "Optional AST file imports.")
oExAST = flag.String("exampleAST", "exampleAST", "Fuction to call to produce example ASTs.")
oKind = flag.String("kind", "kind", "Default node kind (rule case) field name.")
oNode = flag.String("node", "node", "Default non terminal yacc type.")
oO = flag.String("o", "parser.y", "Output yacc file.")
oPkg = flag.String("pkg", "", "Package name of generated Go files. Extract from input when blank.")
oPrettyString = flag.String("prettyString", "prettyString", "Fuction to stringify things nicely.")
oReport = flag.String("v", "y.output", "create grammar report")
oToken = flag.String("token", "Token", "Default terminal yacc type.")
oTokenSep = flag.String("tokenSep", " ", "AST examples token separator string.")
oYylex = flag.String("yylex", "*lexer", "Type of yacc's yylex.")
copyright string // Extracted from input.
fset *token.FileSet //
kind = map[*y.Rule]int{} //
nodes = map[string]*node{} // non terminal name: *node
nonTerminals []*y.Symbol // Sorted by name
ruleDirectives = map[*y.Rule][]directive{} //
terminals []*y.Symbol // Sorted by name
tokenDirectives = map[string][]directive{} // symbol name: []directive
typed = map[*y.Symbol]bool{}
ytypes = map[string]string{} // yacc type: Go type
)
type directive struct {
cmd string
arg string
}
func (d directive) field() (nm []string, typ string) {
if d.cmd != "field" {
panic("internal error")
}
s := strings.TrimSpace(d.arg)
i := strings.IndexAny(s, " \t")
if i < 0 {
return nil, s
}
//TODO properly parse
flds := s[:i]
typ = s[i:]
a := strings.Split(flds, ",")
for _, v := range a {
nm = append(nm, strings.TrimSpace(v))
}
return nm, typ
}
func (d *directive) isIgnore() bool { return d.cmd == "ignore" }
func (d *directive) isList() bool { return d.cmd == "list" }
func unquote(s string) string {
s = strings.TrimSpace(s)
if s == "" {
return ""
}
if c := s[0]; c != '"' && c != '\'' {
return s
}
s2, err := strconv.Unquote(s)
if err != nil {
log.Fatalf("unquote %s: %v", s, err)
}
return s2
}
type node struct {
fields map[string]string // name: Go type
ytyp string
typ string // Go type
}
func newNode(ytyp, typ string) *node { return &node{fields: map[string]string{}, ytyp: ytyp, typ: typ} }
func main() {
log.SetFlags(0)
flag.Parse()
checkOptions()
var rep io.Writer
if nm := *oReport; nm != "" {
f, err := os.Create(nm)
if err != nil {
log.Fatal(err)
}
defer f.Close()
w := bufio.NewWriter(f)
defer w.Flush()
rep = w
}
fset = token.NewFileSet()
spec, err := y.ProcessFile(fset, flag.Arg(0), &y.Options{
AllowTypeErrors: true,
Closures: true,
Report: rep,
})
if err != nil {
log.Fatal(err)
}
if *oPkg == "" {
s := extractPkg(spec.Prologue)
if s == "" {
s = "main"
}
*oPkg = s
}
copyright = extractCopyright(spec.Prologue)
union := spec.Union
if union == nil {
log.Fatalf("missing %sunion definition", "%")
}
for _, fields := range union.Fields.List[1:] { // Skip yys int.
for _, nm := range fields.Names {
ytypes[nm.Name] = astString(fields.Type)
}
}
if _, ok := ytypes[*oNode]; !ok {
log.Fatalf("undefined yacc type: %s", *oNode)
}
if _, ok := ytypes[*oToken]; !ok {
log.Fatalf("undefined yacc type: %s", *oToken)
}
var a []string
for _, sym := range spec.Syms {
switch {
case sym.IsTerminal:
s := sym.Name
s0 := s[0]
if s == "error" || s0 > 0x7f || s0 == '#' || s0 == '$' {
continue
}
a = append(a, sym.Name)
default:
if sym.Name[0] == '$' {
break
}
a = append(a, sym.Name)
for i, v := range sym.Rules {
kind[v] = i
}
}
}
sort.Strings(a)
for _, nm := range a {
sym := spec.Syms[nm]
if sym.IsTerminal {
terminals = append(terminals, sym)
continue
}
nonTerminals = append(nonTerminals, sym)
}
checkDirectives(spec)
for _, v := range spec.Rules {
out:
for _, d := range ruleDirectives[v] {
if d.cmd == "case" {
typed[v.Sym] = true
break out
}
}
}
nspec := genY(spec)
genAST(spec)
if *oASTExamples == os.DevNull {
return
}
genASTExamples(nspec)
}
func checkOptions() {
*oAST = strings.TrimSpace(*oAST)
if *oAST == "" {
*oAST = os.DevNull
}
*oASTExamples = strings.TrimSpace(*oASTExamples)
if *oASTExamples == "" {
*oASTExamples = os.DevNull
}
*oASTImport = strings.TrimSpace(*oASTImport)
*oExAST = strings.TrimSpace(*oExAST)
if *oExAST == "" {
log.Fatal("invalid -exampleAST option value.")
}
*oKind = strings.TrimSpace(*oKind)
if *oKind == "" {
log.Fatal("invalid -kind option value.")
}
*oYylex = strings.TrimSpace(*oYylex)
if *oYylex == "" {
log.Fatal("invalid -yylex option value.")
}
*oNode = strings.TrimSpace(*oNode)
if *oNode == "" {
log.Fatal("invalid -node option value.")
}
*oO = strings.TrimSpace(*oO)
if *oO == "" {
*oO = os.DevNull
}
*oPkg = strings.TrimSpace(*oPkg)
*oPrettyString = strings.TrimSpace(*oPrettyString)
if *oPrettyString == "" {
log.Fatal("invalid -prettyString option value.")
}
*oToken = strings.TrimSpace(*oToken)
if *oToken == "" {
log.Fatal("invalid -token option value.")
}
if g, e := flag.NArg(), 1; g != e {
log.Fatalf("expected number of arguments: %v", e)
}
in := flag.Arg(0)
if *oO == in {
log.Fatal("input and output yacc file names are the same.")
}
}
func extractPkg(s string) string {
f, err := parser.ParseFile(token.NewFileSet(), flag.Arg(0), s, parser.PackageClauseOnly)
if err != nil {
return ""
}
return f.Name.Name
}
func extractCopyright(s string) string {
a := strings.Split(s, "\n")
for i, v := range a {
a[i] = strings.TrimSpace(v)
}
for i, v := range a {
if strings.HasPrefix(v, "// Copyright") {
j := i + 1
for ; j < len(a); j++ {
if !strings.HasPrefix(a[j], "//") {
j++
break
}
}
return strings.Join(a[i:j], "\n")
}
}
return ""
}
func astString(node ast.Node) string {
var buf bytes.Buffer
var f func(node ast.Node)
f = func(node ast.Node) {
switch x := node.(type) {
case *ast.Ident:
buf.WriteString(x.Name)
case *ast.InterfaceType:
buf.WriteString("interface{")
for _, v := range x.Methods.List {
f(v)
buf.WriteByte(';')
}
buf.WriteByte('}')
case *ast.SelectorExpr:
f(x.X)
buf.WriteByte('.')
f(x.Sel)
case *ast.StarExpr:
buf.WriteByte('*')
f(x.X)
default:
log.Fatalf("unsupported go/ast.Node type %T", x)
}
}
f(node)
return buf.String()
}
func extractDirectives(tok *yparser.Token) (r []directive) {
for _, s := range tok.Comments {
if strings.HasPrefix(s, "/*") {
if !strings.HasSuffix(s, "*/") {
panic("internal error")
}
s = s[len("/*") : len(s)-len("*/")]
a := strings.Split(s, "\n")
s = "//" + strings.Join(a, "\n//")
a = strings.Split(s, "\n")
r = append(r, extractDirectives(&yparser.Token{Comments: a, File: tok.File, Char: tok.Char})...)
continue
}
if !strings.HasPrefix(s, "//yy:") {
continue
}
s = s[len("//yy:"):]
i := strings.IndexAny(s, " \t")
if i < 0 {
i = len(s)
}
cmd := s[:i]
arg := strings.TrimSpace(s[i:])
if _, ok := isCmd[cmd]; !ok {
log.Fatalf("%v: invalid directive: %s", tok.Position(), cmd)
}
r = append(r, directive{cmd: cmd, arg: arg})
}
return r
}
var isCmd = map[string]struct{}{
"case": {},
"example": {},
"field": {},
"ignore": {},
"list": {},
"token": {},
}
func checkDirectives(spec *y.Parser) {
for _, rule := range spec.Rules[1:] {
if rule.Sym.Name[0] == '$' {
continue
}
d := extractDirectives(rule.Token)
if len(d) == 0 {
continue
}
ruleDirectives[rule] = d
}
for _, def := range spec.Definitions {
if def.Case != 3 || def.ReservedWord.Token.Char.Rune != yparser.TOKEN {
continue
}
for _, nm := range def.Nlist {
d := extractDirectives(nm.Token)
if len(d) == 0 {
continue
}
tokenDirectives[nm.Token.Val] = d
}
}
}
func isIgnored(sym *y.Symbol) bool {
for _, rule := range sym.Rules {
for _, d := range ruleDirectives[rule] {
if d.isIgnore() {
return true
}
}
}
return false
}
func isList(sym *y.Symbol) bool {
if !sym.IsLeftRecursive {
return false
}
if strings.HasSuffix(sym.Name, "List") {
return true
}
for _, rule := range sym.Rules {
for _, d := range ruleDirectives[rule] {
if d.isList() {
return true
}
}
}
return false
}
func genAST(spec *y.Parser) {
f := bytes.NewBuffer(nil)
fmt.Fprintf(f, caution)
if copyright != "" {
fmt.Fprintf(f, "%s\n", copyright)
}
fmt.Fprintf(f, "package %s\n", *oPkg)
if s := *oASTImport; s != "" {
fmt.Fprintf(f, "\nimport(%s)\n", s)
}
var a []string
for nm := range nodes {
a = append(a, nm)
}
sort.Strings(a)
for _, nm := range a {
sym := spec.Syms[nm]
if isIgnored(sym) {
continue
}
if typed[sym] {
fmt.Fprintf(f, "\n// %sCase represents case numbers of production %s\n", nm, nm)
fmt.Fprintf(f, "type %sCase int\n", nm)
fmt.Fprintf(f, "\n// Values of type %sCase\n", nm)
fmt.Fprintf(f, "const (\n")
outer:
for i, rule := range sym.Rules {
for _, d := range ruleDirectives[rule] {
if d.cmd == "case" {
switch {
case i == 0:
fmt.Fprintf(f, "%s%s %sCase = iota\n", nm, d.arg, nm)
default:
fmt.Fprintf(f, "%s%s\n", nm, d.arg)
}
continue outer
}
}
fmt.Fprintln(f, "_")
}
fmt.Fprintf(f, ")\n")
fmt.Fprintf(f, "\n// String implements fmt.Stringer\n")
fmt.Fprintf(f, "func (n %sCase) String() string {\n", nm)
fmt.Fprintf(f, "switch n {\n")
outer2:
for _, rule := range sym.Rules {
for _, d := range ruleDirectives[rule] {
if d.cmd == "case" {
fmt.Fprintf(f, "case %s%s:\nreturn \"%s%s\"\n", nm, d.arg, nm, d.arg)
continue outer2
}
}
}
fmt.Fprintf(f, "default:\nreturn fmt.Sprintf(\"%sCase(%%v)\", int(n))\n", nm)
fmt.Fprintf(f, "}\n")
fmt.Fprintf(f, "}\n")
}
plural := ""
if len(sym.Rules) > 1 {
plural = "s"
}
fmt.Fprintf(f, "\n// %s represents data reduced by production%s:\n//\n%s\n", nm, plural, symDocs(sym))
n := nodes[nm]
fmt.Fprintf(f, "type %s struct{\n", nm)
var a []string
for _, rule := range sym.Rules {
d := ruleDirectives[rule]
for _, d := range d {
if d.cmd == "field" {
fmt.Fprintf(f, "%s\n", d.arg)
}
}
}
for nm := range n.fields {
a = append(a, nm)
}
sort.Strings(a)
for _, nm := range a {
fmt.Fprintf(f, "\t%s %s\n", nm, n.fields[nm])
}
fmt.Fprintf(f, "}\n")
rx := "n"
switch isList(sym) {
case true:
fmt.Fprintf(f, `
func (%[1]s *%[2]s) reverse() *%[2]s {
if %[1]s == nil {
return nil
}
na := %[1]s
nb := na.%[2]s
for nb != nil {
nc := nb.%[2]s
nb.%[2]s = na
na = nb
nb = nc
}
%[1]s.%[2]s = nil
return na
}
func (%[1]s *%[2]s) fragment() interface{} { return %[1]s.reverse() }
`, rx, nm)
default:
fmt.Fprintf(f, `
func (%[1]s *%[2]s) fragment() interface{} { return %[1]s }
`, rx, nm)
}
fmt.Fprintf(f, `// String implements fmt.Stringer.
func (%[1]s *%[2]s) String() string {
return %[3]s(%[1]s)
}
`, rx, nm, *oPrettyString)
fmt.Fprintf(f, `// Pos reports the position of the first component of %[1]s or zero if it's empty.
func (%[1]s *%[2]s) Pos() token.Pos {
`, rx, nm)
cases := map[string][]int{}
isopt := isOpt(sym)
fmt.Fprintf(f, "if %s == nil { return 0 }\n\n", rx)
for i, v := range sym.Rules {
m := map[string]int{}
s := ""
for _, c := range v.Components {
if strings.HasPrefix(c, "$") {
continue
}
isT := false
cs := spec.Syms[c]
if cs.IsTerminal {
c = *oToken
isT = true
}
m[c]++
suffix := ""
if m[c] > 1 {
suffix = strconv.Itoa(m[c])
}
if s != "" {
s += " "
}
s += fmt.Sprintf("%s$%s", c, suffix)
if isT || !cs.DerivesEmpty() {
break
}
}
cases[s] = append(cases[s], i)
}
a = []string{}
for k := range cases {
a = append(a, k)
}
sort.Strings(a)
if len(a) > 1 && !isopt {
fmt.Fprintf(f, "switch %s.%s {\n", rx, *oKind)
}
for _, k := range a {
v := cases[k]
if len(a) > 1 && !isopt {
fmt.Fprintf(f, "case ")
for _, v := range v[:len(v)-1] {
fmt.Fprintf(f, "%d, ", v)
}
fmt.Fprintf(f, "%d", v[len(v)-1])
fmt.Fprintf(f, ":\n")
}
if k == "" {
if !isopt {
fmt.Fprintf(f, "return 0\n")
}
continue
}
a := strings.Split(k, " ")
for _, v := range a[:len(a)-1] {
v = strings.Replace(v, "$", "", -1)
fmt.Fprintf(f, "if p := %s.%s.Pos(); p != 0 { return p }\n\n", rx, v)
}
s := strings.Replace(a[len(a)-1], "$", "", -1)
fmt.Fprintf(f, "return %s.%s.Pos()\n", rx, s)
}
if len(a) > 1 && !isopt {
fmt.Fprintf(f, "default:\n")
fmt.Fprintf(f, "panic(\"internal error\")\n")
fmt.Fprintf(f, "}\n")
}
fmt.Fprintf(f, "}\n")
continue
}
b, err := format.Source(f.Bytes())
if err != nil {
b = f.Bytes()
}
file, err := os.Create(*oAST)
if err != nil {
log.Fatal(err)
}
if _, err := file.Write(b); err != nil {
log.Fatal(err)
}
if err := file.Close(); err != nil {
log.Fatal(err)
}
}
func genNodes(spec *y.Parser) {
for _, sym := range terminals {
if sym.Type == "" {
sym.Type = *oToken
}
}
for _, sym := range nonTerminals {
if sym.Type == "" {
sym.Type = *oNode
}
}
for _, sym := range nonTerminals {
nm := sym.Name
n := nodes[nm]
if n == nil {
ytyp := sym.Type
if ytyp == "" {
ytyp = *oNode
}
typ := fmt.Sprintf("*%s", nm)
if ytyp != *oNode {
typ = ytypes[ytyp]
}
n = newNode(ytyp, typ)
if len(sym.Rules) > 1 && !isOpt(sym) {
typ := "int"
if typed[sym] {
typ = fmt.Sprintf("%sCase", nm)
}
n.fields[*oKind] = typ