/
parser.go
3506 lines (2967 loc) · 71 KB
/
parser.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gc
// The recursive-descent parser is built around a slighty modified grammar
// of Go to accomodate for the constraints imposed by strict one token look-
// ahead, and for better error handling. Subsequent checks of the constructed
// syntax tree restrict the language accepted by the compiler to proper Go.
//
// Semicolons are inserted by the lexer. The parser uses one-token look-ahead
// to handle optional commas and semicolons before a closing ) or } .
import (
"fmt"
"strconv"
"strings"
)
const trace = false // if set, parse tracing can be enabled with -x
// TODO(gri) Once we handle imports w/o redirecting the underlying
// source of the lexer we can get rid of these. They are here for
// compatibility with the existing yacc-based parser setup (issue 13242).
var thenewparser parser // the parser in use
var savedstate []parser // saved parser state, used during import
func push_parser() {
// Indentation (for tracing) must be preserved across parsers
// since we are changing the lexer source (and parser state)
// under foot, in the middle of productions. This won't be
// needed anymore once we fix issue 13242, but neither will
// be the push/pop_parser functionality.
// (Instead we could just use a global variable indent, but
// but eventually indent should be parser-specific anyway.)
indent := thenewparser.indent
savedstate = append(savedstate, thenewparser)
thenewparser = parser{indent: indent} // preserve indentation
thenewparser.next()
}
func pop_parser() {
indent := thenewparser.indent
n := len(savedstate) - 1
thenewparser = savedstate[n]
thenewparser.indent = indent // preserve indentation
savedstate = savedstate[:n]
}
// parse_file sets up a new parser and parses a single Go source file.
func parse_file() {
thenewparser = parser{}
thenewparser.loadsys()
thenewparser.next()
thenewparser.file()
}
// loadsys loads the definitions for the low-level runtime functions,
// so that the compiler can generate calls to them,
// but does not make the name "runtime" visible as a package.
func (p *parser) loadsys() {
if trace && Debug['x'] != 0 {
defer p.trace("loadsys")()
}
importpkg = Runtimepkg
if Debug['A'] != 0 {
cannedimports("runtime.Builtin", "package runtime\n\n$$\n\n")
} else {
cannedimports("runtime.Builtin", runtimeimport)
}
curio.importsafe = true
p.import_package()
p.import_there()
importpkg = nil
}
type parser struct {
tok int32 // next token (one-token look-ahead)
op Op // valid if tok == LASOP
val Val // valid if tok == LLITERAL
sym_ *Sym // valid if tok == LNAME
fnest int // function nesting level (for error handling)
xnest int // expression nesting level (for complit ambiguity resolution)
yy yySymType // for temporary use by next
indent []byte // tracing support
}
func (p *parser) next() {
p.tok = yylex(&p.yy)
p.op = p.yy.op
p.val = p.yy.val
p.sym_ = p.yy.sym
}
func (p *parser) got(tok int32) bool {
if p.tok == tok {
p.next()
return true
}
return false
}
func (p *parser) want(tok int32) {
if !p.got(tok) {
p.syntax_error("expecting " + tokstring(tok))
p.advance()
}
}
// ----------------------------------------------------------------------------
// Syntax error handling
func (p *parser) syntax_error(msg string) {
if trace && Debug['x'] != 0 {
defer p.trace("syntax_error (" + msg + ")")()
}
if p.tok == EOF && nerrors > 0 {
return // avoid meaningless follow-up errors
}
// add punctuation etc. as needed to msg
switch {
case msg == "":
// nothing to do
case strings.HasPrefix(msg, "in"), strings.HasPrefix(msg, "at"), strings.HasPrefix(msg, "after"):
msg = " " + msg
case strings.HasPrefix(msg, "expecting"):
msg = ", " + msg
default:
// plain error - we don't care about current token
Yyerror("syntax error: %s", msg)
return
}
// determine token string
var tok string
switch p.tok {
case LLITERAL:
tok = litbuf
case LNAME:
if p.sym_ != nil && p.sym_.Name != "" {
tok = p.sym_.Name
} else {
tok = "name"
}
case LASOP:
tok = goopnames[p.op] + "="
default:
tok = tokstring(p.tok)
}
Yyerror("syntax error: unexpected %s", tok+msg)
}
// Like syntax_error, but reports error at given line rather than current lexer line.
func (p *parser) syntax_error_at(lineno int32, msg string) {
defer func(lineno int32) {
lexlineno = lineno
}(lexlineno)
lexlineno = lineno
p.syntax_error(msg)
}
// The stoplist contains keywords that start a statement.
// They are good synchronization points in case of syntax
// errors and (usually) shouldn't be skipped over.
var stoplist = map[int32]bool{
LBREAK: true,
LCONST: true,
LCONTINUE: true,
LDEFER: true,
LFALL: true,
LFOR: true,
LFUNC: true,
LGO: true,
LGOTO: true,
LIF: true,
LRETURN: true,
LSELECT: true,
LSWITCH: true,
LTYPE: true,
LVAR: true,
}
// Advance consumes tokens until it finds a token of the stop- or followlist.
// The stoplist is only considered if we are inside a function (p.fnest > 0).
// The followlist is the list of valid tokens that can follow a production;
// if it is empty, exactly one token is consumed to ensure progress.
func (p *parser) advance(followlist ...int32) {
if len(followlist) == 0 {
p.next()
return
}
for p.tok != EOF {
if p.fnest > 0 && stoplist[p.tok] {
return
}
for _, follow := range followlist {
if p.tok == follow {
return
}
}
p.next()
}
}
func tokstring(tok int32) string {
switch tok {
case EOF:
return "EOF"
case ',':
return "comma"
case ';':
return "semicolon or newline"
}
if 0 <= tok && tok < 128 {
// get invisibles properly backslashed
s := strconv.QuoteRune(tok)
if n := len(s); n > 0 && s[0] == '\'' && s[n-1] == '\'' {
s = s[1 : n-1]
}
return s
}
if s := tokstrings[tok]; s != "" {
return s
}
// catchall
return fmt.Sprintf("tok-%v", tok)
}
var tokstrings = map[int32]string{
LLITERAL: "LLITERAL",
LASOP: "op=",
LCOLAS: ":=",
LBREAK: "break",
LCASE: "case",
LCHAN: "chan",
LCONST: "const",
LCONTINUE: "continue",
LDDD: "...",
LDEFAULT: "default",
LDEFER: "defer",
LELSE: "else",
LFALL: "fallthrough",
LFOR: "for",
LFUNC: "func",
LGO: "go",
LGOTO: "goto",
LIF: "if",
LIMPORT: "import",
LINTERFACE: "interface",
LMAP: "map",
LNAME: "LNAME",
LPACKAGE: "package",
LRANGE: "range",
LRETURN: "return",
LSELECT: "select",
LSTRUCT: "struct",
LSWITCH: "switch",
LTYPE: "type",
LVAR: "var",
LANDAND: "&&",
LANDNOT: "&^",
LCOMM: "<-",
LDEC: "--",
LEQ: "==",
LGE: ">=",
LGT: ">",
LIGNORE: "LIGNORE", // we should never see this one
LINC: "++",
LLE: "<=",
LLSH: "<<",
LLT: "<",
LNE: "!=",
LOROR: "||",
LRSH: ">>",
}
// usage: defer p.trace(msg)()
func (p *parser) trace(msg string) func() {
fmt.Printf("%5d: %s%s (\n", lineno, p.indent, msg)
const tab = ". "
p.indent = append(p.indent, tab...)
return func() {
p.indent = p.indent[:len(p.indent)-len(tab)]
if x := recover(); x != nil {
panic(x) // skip print_trace
}
fmt.Printf("%5d: %s)\n", lineno, p.indent)
}
}
// ----------------------------------------------------------------------------
// Parsing package files
//
// Parse methods are annotated with matching Go productions as appropriate.
// The annotations are intended as guidelines only since a single Go grammar
// rule may be covered by multiple parse methods and vice versa.
// SourceFile = PackageClause ";" { ImportDecl ";" } { TopLevelDecl ";" } .
func (p *parser) file() {
if trace && Debug['x'] != 0 {
defer p.trace("file")()
}
p.package_()
p.want(';')
for p.tok == LIMPORT {
p.import_()
p.want(';')
}
xtop = concat(xtop, p.xdcl_list())
p.want(EOF)
}
// PackageClause = "package" PackageName .
// PackageName = identifier .
func (p *parser) package_() {
if trace && Debug['x'] != 0 {
defer p.trace("package_")()
}
if p.got(LPACKAGE) {
mkpackage(p.sym().Name)
} else {
prevlineno = lineno // see issue #13267
p.syntax_error("package statement must be first")
errorexit()
}
}
// ImportDecl = "import" ( ImportSpec | "(" { ImportSpec ";" } ")" ) .
func (p *parser) import_() {
if trace && Debug['x'] != 0 {
defer p.trace("import_")()
}
p.want(LIMPORT)
if p.got('(') {
for p.tok != EOF && p.tok != ')' {
p.import_stmt()
if !p.osemi(')') {
break
}
}
p.want(')')
} else {
p.import_stmt()
}
}
func (p *parser) import_stmt() {
if trace && Debug['x'] != 0 {
defer p.trace("import_stmt")()
}
line := int32(p.import_here())
if p.tok == LPACKAGE {
p.import_package()
p.import_there()
ipkg := importpkg
my := importmyname
importpkg = nil
importmyname = nil
if my == nil {
my = Lookup(ipkg.Name)
}
pack := Nod(OPACK, nil, nil)
pack.Sym = my
pack.Name.Pkg = ipkg
pack.Lineno = line
if strings.HasPrefix(my.Name, ".") {
importdot(ipkg, pack)
return
}
if my.Name == "init" {
lineno = line
Yyerror("cannot import package as init - init must be a func")
return
}
if my.Name == "_" {
return
}
if my.Def != nil {
lineno = line
redeclare(my, "as imported package name")
}
my.Def = pack
my.Lastlineno = line
my.Block = 1 // at top level
return
}
p.import_there()
// When an invalid import path is passed to importfile,
// it calls Yyerror and then sets up a fake import with
// no package statement. This allows us to test more
// than one invalid import statement in a single file.
if nerrors == 0 {
Fatalf("phase error in import")
}
}
// ImportSpec = [ "." | PackageName ] ImportPath .
// ImportPath = string_lit .
//
// import_here switches the underlying lexed source to the export data
// of the imported package.
func (p *parser) import_here() int {
if trace && Debug['x'] != 0 {
defer p.trace("import_here")()
}
importmyname = nil
switch p.tok {
case LNAME, '@', '?':
// import with given name
importmyname = p.sym()
case '.':
// import into my name space
importmyname = Lookup(".")
p.next()
}
var path Val
if p.tok == LLITERAL {
path = p.val
p.next()
} else {
p.syntax_error("missing import path; require quoted string")
p.advance(';', ')')
}
line := parserline()
importfile(&path, line)
return line
}
// import_package parses the header of an imported package as exported
// in textual format from another package.
func (p *parser) import_package() {
if trace && Debug['x'] != 0 {
defer p.trace("import_package")()
}
p.want(LPACKAGE)
var name string
if p.tok == LNAME {
name = p.sym_.Name
p.next()
} else {
p.import_error()
}
if p.tok == LNAME {
if p.sym_.Name == "safe" {
curio.importsafe = true
}
p.next()
}
p.want(';')
if importpkg.Name == "" {
importpkg.Name = name
numImport[name]++
} else if importpkg.Name != name {
Yyerror("conflicting names %s and %s for package %q", importpkg.Name, name, importpkg.Path)
}
if incannedimport == 0 {
importpkg.Direct = true
}
importpkg.Safe = curio.importsafe
if safemode != 0 && !curio.importsafe {
Yyerror("cannot import unsafe package %q", importpkg.Path)
}
}
// import_there parses the imported package definitions and then switches
// the underlying lexed source back to the importing package.
func (p *parser) import_there() {
if trace && Debug['x'] != 0 {
defer p.trace("import_there")()
}
defercheckwidth()
p.hidden_import_list()
p.want('$')
// don't read past 2nd '$'
if p.tok != '$' {
p.import_error()
}
resumecheckwidth()
unimportfile()
}
// Declaration = ConstDecl | TypeDecl | VarDecl .
// ConstDecl = "const" ( ConstSpec | "(" { ConstSpec ";" } ")" ) .
// TypeDecl = "type" ( TypeSpec | "(" { TypeSpec ";" } ")" ) .
// VarDecl = "var" ( VarSpec | "(" { VarSpec ";" } ")" ) .
func (p *parser) common_dcl() *NodeList {
if trace && Debug['x'] != 0 {
defer p.trace("common_dcl")()
}
var dcl func() *NodeList
switch p.tok {
case LVAR:
dcl = p.vardcl
case LCONST:
iota_ = 0
dcl = p.constdcl
case LTYPE:
dcl = p.typedcl
default:
panic("unreachable")
}
p.next()
var l *NodeList
if p.got('(') {
for p.tok != EOF && p.tok != ')' {
l = concat(l, dcl())
if !p.osemi(')') {
break
}
}
p.want(')')
} else {
l = dcl()
}
iota_ = -100000
lastconst = nil
return l
}
// VarSpec = IdentifierList ( Type [ "=" ExpressionList ] | "=" ExpressionList ) .
func (p *parser) vardcl() *NodeList {
if trace && Debug['x'] != 0 {
defer p.trace("vardcl")()
}
names := p.dcl_name_list()
var typ *Node
var exprs *NodeList
if p.got('=') {
exprs = p.expr_list()
} else {
typ = p.ntype()
if p.got('=') {
exprs = p.expr_list()
}
}
return variter(names, typ, exprs)
}
// ConstSpec = IdentifierList [ [ Type ] "=" ExpressionList ] .
func (p *parser) constdcl() *NodeList {
if trace && Debug['x'] != 0 {
defer p.trace("constdcl")()
}
names := p.dcl_name_list()
var typ *Node
var exprs *NodeList
if p.tok != EOF && p.tok != ';' && p.tok != ')' {
typ = p.try_ntype()
if p.got('=') {
exprs = p.expr_list()
}
}
return constiter(names, typ, exprs)
}
// TypeSpec = identifier Type .
func (p *parser) typedcl() *NodeList {
if trace && Debug['x'] != 0 {
defer p.trace("typedcl")()
}
name := typedcl0(p.sym())
typ := p.try_ntype()
// handle case where type is missing
if typ == nil {
p.syntax_error("in type declaration")
p.advance(';', ')')
}
return list1(typedcl1(name, typ, true))
}
// SimpleStmt = EmptyStmt | ExpressionStmt | SendStmt | IncDecStmt | Assignment | ShortVarDecl .
//
// simple_stmt may return missing_stmt if labelOk is set.
func (p *parser) simple_stmt(labelOk, rangeOk bool) *Node {
if trace && Debug['x'] != 0 {
defer p.trace("simple_stmt")()
}
if rangeOk && p.got(LRANGE) {
// LRANGE expr
r := Nod(ORANGE, nil, p.expr())
r.Etype = 0 // := flag
return r
}
lhs := p.expr_list()
if count(lhs) == 1 && p.tok != '=' && p.tok != LCOLAS && p.tok != LRANGE {
// expr
lhs := lhs.N
switch p.tok {
case LASOP:
// expr LASOP expr
op := p.op
p.next()
rhs := p.expr()
stmt := Nod(OASOP, lhs, rhs)
stmt.Etype = EType(op) // rathole to pass opcode
return stmt
case LINC:
// expr LINC
p.next()
stmt := Nod(OASOP, lhs, Nodintconst(1))
stmt.Implicit = true
stmt.Etype = EType(OADD)
return stmt
case LDEC:
// expr LDEC
p.next()
stmt := Nod(OASOP, lhs, Nodintconst(1))
stmt.Implicit = true
stmt.Etype = EType(OSUB)
return stmt
case ':':
// labelname ':' stmt
if labelOk {
// If we have a labelname, it was parsed by operand
// (calling p.name()) and given an ONAME, ONONAME, OTYPE, OPACK, or OLITERAL node.
// We only have a labelname if there is a symbol (was issue 14006).
switch lhs.Op {
case ONAME, ONONAME, OTYPE, OPACK, OLITERAL:
if lhs.Sym != nil {
lhs = newname(lhs.Sym)
break
}
fallthrough
default:
p.syntax_error("expecting semicolon or newline or }")
// we already progressed, no need to advance
}
lhs := Nod(OLABEL, lhs, nil)
lhs.Sym = dclstack // context, for goto restrictions
p.next() // consume ':' after making label node for correct lineno
return p.labeled_stmt(lhs)
}
fallthrough
default:
// expr
// Since a bare name used as an expression is an error,
// introduce a wrapper node where necessary to give the
// correct line.
return wrapname(lhs)
}
}
// expr_list
switch p.tok {
case '=':
p.next()
if rangeOk && p.got(LRANGE) {
// expr_list '=' LRANGE expr
r := Nod(ORANGE, nil, p.expr())
r.List = lhs
r.Etype = 0 // := flag
return r
}
// expr_list '=' expr_list
rhs := p.expr_list()
if lhs.Next == nil && rhs.Next == nil {
// simple
return Nod(OAS, lhs.N, rhs.N)
}
// multiple
stmt := Nod(OAS2, nil, nil)
stmt.List = lhs
stmt.Rlist = rhs
return stmt
case LCOLAS:
lno := lineno
p.next()
if rangeOk && p.got(LRANGE) {
// expr_list LCOLAS LRANGE expr
r := Nod(ORANGE, nil, p.expr())
r.List = lhs
r.Colas = true
colasdefn(lhs, r)
return r
}
// expr_list LCOLAS expr_list
rhs := p.expr_list()
if rhs.N.Op == OTYPESW {
ts := Nod(OTYPESW, nil, rhs.N.Right)
if rhs.Next != nil {
Yyerror("expr.(type) must be alone in list")
}
if lhs.Next != nil {
Yyerror("argument count mismatch: %d = %d", count(lhs), 1)
} else if (lhs.N.Op != ONAME && lhs.N.Op != OTYPE && lhs.N.Op != ONONAME && (lhs.N.Op != OLITERAL || lhs.N.Name == nil)) || isblank(lhs.N) {
Yyerror("invalid variable name %s in type switch", lhs.N)
} else {
ts.Left = dclname(lhs.N.Sym)
} // it's a colas, so must not re-use an oldname
return ts
}
return colas(lhs, rhs, int32(lno))
default:
p.syntax_error("expecting := or = or comma")
p.advance(';', '}')
return nil
}
}
// LabeledStmt = Label ":" Statement .
// Label = identifier .
func (p *parser) labeled_stmt(label *Node) *Node {
if trace && Debug['x'] != 0 {
defer p.trace("labeled_stmt")()
}
var ls *Node // labeled statement
if p.tok != '}' && p.tok != EOF {
ls = p.stmt()
if ls == missing_stmt {
// report error at line of ':' token
p.syntax_error_at(prevlineno, "missing statement after label")
// we are already at the end of the labeled statement - no need to advance
return missing_stmt
}
}
label.Name.Defn = ls
l := list1(label)
if ls != nil {
l = list(l, ls)
}
return liststmt(l)
}
// case_ parses a superset of switch and select statement cases.
// Later checks restrict the syntax to valid forms.
//
// ExprSwitchCase = "case" ExpressionList | "default" .
// TypeSwitchCase = "case" TypeList | "default" .
// TypeList = Type { "," Type } .
// CommCase = "case" ( SendStmt | RecvStmt ) | "default" .
// RecvStmt = [ ExpressionList "=" | IdentifierList ":=" ] RecvExpr .
// RecvExpr = Expression .
func (p *parser) case_(tswitch *Node) *Node {
if trace && Debug['x'] != 0 {
defer p.trace("case_")()
}
switch p.tok {
case LCASE:
p.next()
cases := p.expr_list() // expr_or_type_list
switch p.tok {
case ':':
// LCASE expr_or_type_list ':'
// will be converted to OCASE
// right will point to next case
// done in casebody()
markdcl() // matching popdcl in caseblock
stmt := Nod(OXCASE, nil, nil)
stmt.List = cases
if tswitch != nil {
if n := tswitch.Left; n != nil {
// type switch - declare variable
nn := newname(n.Sym)
declare(nn, dclcontext)
stmt.Rlist = list1(nn)
// keep track of the instances for reporting unused
nn.Name.Defn = tswitch
}
}
p.next() // consume ':' after declaring type switch var for correct lineno
return stmt
case '=':
// LCASE expr_or_type_list '=' expr ':'
p.next()
rhs := p.expr()
// will be converted to OCASE
// right will point to next case
// done in casebody()
markdcl() // matching popdcl in caseblock
stmt := Nod(OXCASE, nil, nil)
var n *Node
if cases.Next == nil {
n = Nod(OAS, cases.N, rhs)
} else {
n = Nod(OAS2, nil, nil)
n.List = cases
n.Rlist = list1(rhs)
}
stmt.List = list1(n)
p.want(':') // consume ':' after declaring select cases for correct lineno
return stmt
case LCOLAS:
// LCASE expr_or_type_list LCOLAS expr ':'
lno := lineno
p.next()
rhs := p.expr()
// will be converted to OCASE
// right will point to next case
// done in casebody()
markdcl() // matching popdcl in caseblock
stmt := Nod(OXCASE, nil, nil)
stmt.List = list1(colas(cases, list1(rhs), int32(lno)))
p.want(':') // consume ':' after declaring select cases for correct lineno
return stmt
default:
markdcl() // for matching popdcl in caseblock
stmt := Nod(OXCASE, nil, nil) // don't return nil
p.syntax_error("expecting := or = or : or comma")
p.advance(LCASE, LDEFAULT, '}')
return stmt
}
case LDEFAULT:
// LDEFAULT ':'
p.next()
markdcl() // matching popdcl in caseblock
stmt := Nod(OXCASE, nil, nil)
if tswitch != nil {
if n := tswitch.Left; n != nil {
// type switch - declare variable
nn := newname(n.Sym)
declare(nn, dclcontext)
stmt.Rlist = list1(nn)
// keep track of the instances for reporting unused
nn.Name.Defn = tswitch
}
}
p.want(':') // consume ':' after declaring type switch var for correct lineno
return stmt
default:
markdcl() // matching popdcl in caseblock
stmt := Nod(OXCASE, nil, nil) // don't return nil
p.syntax_error("expecting case or default or }")
p.advance(LCASE, LDEFAULT, '}')
return stmt
}
}
// Block = "{" StatementList "}" .
// StatementList = { Statement ";" } .
func (p *parser) compound_stmt(else_clause bool) *Node {
if trace && Debug['x'] != 0 {
defer p.trace("compound_stmt")()
}
markdcl()
if p.got('{') {
// ok
} else if else_clause {
p.syntax_error("else must be followed by if or statement block")
p.advance(LNAME, '}')
} else {
panic("unreachable")
}
l := p.stmt_list()
p.want('}')
var stmt *Node
if l == nil {
stmt = Nod(OEMPTY, nil, nil)
} else {
stmt = liststmt(l)
}
popdcl()
return stmt
}
// caseblock parses a superset of switch and select clauses.
//
// ExprCaseClause = ExprSwitchCase ":" StatementList .
// TypeCaseClause = TypeSwitchCase ":" StatementList .
// CommClause = CommCase ":" StatementList .
func (p *parser) caseblock(tswitch *Node) *Node {
if trace && Debug['x'] != 0 {
defer p.trace("caseblock")()
}
stmt := p.case_(tswitch) // does markdcl
stmt.Xoffset = int64(block)
stmt.Nbody = p.stmt_list()
popdcl()
return stmt
}
// caseblock_list parses a superset of switch and select clause lists.
func (p *parser) caseblock_list(tswitch *Node) (l *NodeList) {
if trace && Debug['x'] != 0 {
defer p.trace("caseblock_list")()
}
if !p.got('{') {
p.syntax_error("missing { after switch clause")
p.advance(LCASE, LDEFAULT, '}')
}
for p.tok != EOF && p.tok != '}' {
l = list(l, p.caseblock(tswitch))
}
p.want('}')
return
}
// loop_body parses if and for statement bodies.
func (p *parser) loop_body(context string) *NodeList {
if trace && Debug['x'] != 0 {
defer p.trace("loop_body")()
}
markdcl()
if !p.got('{') {
p.syntax_error("missing { after " + context)
p.advance(LNAME, '}')
}
body := p.stmt_list()
popdcl()
p.want('}')
return body
}
// for_header parses the header portion of a for statement.
//
// ForStmt = "for" [ Condition | ForClause | RangeClause ] Block .
// Condition = Expression .
func (p *parser) for_header() *Node {