1
2
3
4
5 package syntax
6
7 import (
8 "fmt"
9 "go/build/constraint"
10 "io"
11 "strconv"
12 "strings"
13 )
14
15 const debug = false
16 const trace = false
17
18 type parser struct {
19 file *PosBase
20 errh ErrorHandler
21 mode Mode
22 pragh PragmaHandler
23 scanner
24
25 base *PosBase
26 first error
27 errcnt int
28 pragma Pragma
29 goVersion string
30
31 top bool
32 fnest int
33 xnest int
34 indent []byte
35 }
36
37 func (p *parser) init(file *PosBase, r io.Reader, errh ErrorHandler, pragh PragmaHandler, mode Mode) {
38 p.top = true
39 p.file = file
40 p.errh = errh
41 p.mode = mode
42 p.pragh = pragh
43 p.scanner.init(
44 r,
45
46
47
48
49
50 func(line, col uint, msg string) {
51 if msg[0] != '/' {
52 p.errorAt(p.posAt(line, col), msg)
53 return
54 }
55
56
57
58
59 text := commentText(msg)
60 if (col == colbase || msg[1] == '*') && strings.HasPrefix(text, "line ") {
61 var pos Pos
62 if msg[1] == '/' {
63
64 pos = MakePos(p.file, line+1, colbase)
65 } else {
66
67
68
69
70 pos = MakePos(p.file, line, col+uint(len(msg)))
71 }
72 p.updateBase(pos, line, col+2+5, text[5:])
73 return
74 }
75
76
77 if strings.HasPrefix(text, "go:") {
78 if p.top && strings.HasPrefix(msg, "//go:build") {
79 if x, err := constraint.Parse(msg); err == nil {
80 p.goVersion = constraint.GoVersion(x)
81 }
82 }
83 if pragh != nil {
84 p.pragma = pragh(p.posAt(line, col+2), p.scanner.blank, text, p.pragma)
85 }
86 }
87 },
88 directives,
89 )
90
91 p.base = file
92 p.first = nil
93 p.errcnt = 0
94 p.pragma = nil
95
96 p.fnest = 0
97 p.xnest = 0
98 p.indent = nil
99 }
100
101
102
103 func (p *parser) takePragma() Pragma {
104 prag := p.pragma
105 p.pragma = nil
106 return prag
107 }
108
109
110
111
112
113 func (p *parser) clearPragma() {
114 if p.pragma != nil {
115 p.pragh(p.pos(), p.scanner.blank, "", p.pragma)
116 p.pragma = nil
117 }
118 }
119
120
121
122
123 func (p *parser) updateBase(pos Pos, tline, tcol uint, text string) {
124 i, n, ok := trailingDigits(text)
125 if i == 0 {
126 return
127 }
128
129
130 if !ok {
131
132 p.errorAt(p.posAt(tline, tcol+i), "invalid line number: "+text[i:])
133 return
134 }
135
136 var line, col uint
137 i2, n2, ok2 := trailingDigits(text[:i-1])
138 if ok2 {
139
140 i, i2 = i2, i
141 line, col = n2, n
142 if col == 0 || col > PosMax {
143 p.errorAt(p.posAt(tline, tcol+i2), "invalid column number: "+text[i2:])
144 return
145 }
146 text = text[:i2-1]
147 } else {
148
149 line = n
150 }
151
152 if line == 0 || line > PosMax {
153 p.errorAt(p.posAt(tline, tcol+i), "invalid line number: "+text[i:])
154 return
155 }
156
157
158
159 filename := text[:i-1]
160 trimmed := false
161 if filename == "" && ok2 {
162 filename = p.base.Filename()
163 trimmed = p.base.Trimmed()
164 }
165
166 p.base = NewLineBase(pos, filename, trimmed, line, col)
167 }
168
169 func commentText(s string) string {
170 if s[:2] == "/*" {
171 return s[2 : len(s)-2]
172 }
173
174
175
176 i := len(s)
177 if s[i-1] == '\r' {
178 i--
179 }
180 return s[2:i]
181 }
182
183 func trailingDigits(text string) (uint, uint, bool) {
184 i := strings.LastIndexByte(text, ':')
185 if i < 0 {
186 return 0, 0, false
187 }
188
189 n, err := strconv.ParseUint(text[i+1:], 10, 0)
190 return uint(i + 1), uint(n), err == nil
191 }
192
193 func (p *parser) got(tok token) bool {
194 if p.tok == tok {
195 p.next()
196 return true
197 }
198 return false
199 }
200
201 func (p *parser) want(tok token) {
202 if !p.got(tok) {
203 p.syntaxError("expected " + tokstring(tok))
204 p.advance()
205 }
206 }
207
208
209
210 func (p *parser) gotAssign() bool {
211 switch p.tok {
212 case _Define:
213 p.syntaxError("expected =")
214 fallthrough
215 case _Assign:
216 p.next()
217 return true
218 }
219 return false
220 }
221
222
223
224
225
226 func (p *parser) posAt(line, col uint) Pos {
227 return MakePos(p.base, line, col)
228 }
229
230
231 func (p *parser) errorAt(pos Pos, msg string) {
232 err := Error{pos, msg}
233 if p.first == nil {
234 p.first = err
235 }
236 p.errcnt++
237 if p.errh == nil {
238 panic(p.first)
239 }
240 p.errh(err)
241 }
242
243
244 func (p *parser) syntaxErrorAt(pos Pos, msg string) {
245 if trace {
246 p.print("syntax error: " + msg)
247 }
248
249 if p.tok == _EOF && p.first != nil {
250 return
251 }
252
253
254 switch {
255 case msg == "":
256
257 case strings.HasPrefix(msg, "in "), strings.HasPrefix(msg, "at "), strings.HasPrefix(msg, "after "):
258 msg = " " + msg
259 case strings.HasPrefix(msg, "expected "):
260 msg = ", " + msg
261 default:
262
263 p.errorAt(pos, "syntax error: "+msg)
264 return
265 }
266
267
268 var tok string
269 switch p.tok {
270 case _Name:
271 tok = "name " + p.lit
272 case _Semi:
273 tok = p.lit
274 case _Literal:
275 tok = "literal " + p.lit
276 case _Operator:
277 tok = p.op.String()
278 case _AssignOp:
279 tok = p.op.String() + "="
280 case _IncOp:
281 tok = p.op.String()
282 tok += tok
283 default:
284 tok = tokstring(p.tok)
285 }
286
287
288
289 p.errorAt(pos, "syntax error: unexpected "+tok+msg)
290 }
291
292
293
294
295
296 func tokstring(tok token) string {
297 switch tok {
298 case _Comma:
299 return "comma"
300 case _Semi:
301 return "semicolon or newline"
302 }
303 s := tok.String()
304 if _Break <= tok && tok <= _Var {
305 return "keyword " + s
306 }
307 return s
308 }
309
310
311 func (p *parser) pos() Pos { return p.posAt(p.line, p.col) }
312 func (p *parser) error(msg string) { p.errorAt(p.pos(), msg) }
313 func (p *parser) syntaxError(msg string) { p.syntaxErrorAt(p.pos(), msg) }
314
315
316
317
318 const stopset uint64 = 1<<_Break |
319 1<<_Const |
320 1<<_Continue |
321 1<<_Defer |
322 1<<_Fallthrough |
323 1<<_For |
324 1<<_Go |
325 1<<_Goto |
326 1<<_If |
327 1<<_Return |
328 1<<_Select |
329 1<<_Switch |
330 1<<_Type |
331 1<<_Var
332
333
334
335
336
337 func (p *parser) advance(followlist ...token) {
338 if trace {
339 p.print(fmt.Sprintf("advance %s", followlist))
340 }
341
342
343
344 var followset uint64 = 1 << _EOF
345 if len(followlist) > 0 {
346 if p.fnest > 0 {
347 followset |= stopset
348 }
349 for _, tok := range followlist {
350 followset |= 1 << tok
351 }
352 }
353
354 for !contains(followset, p.tok) {
355 if trace {
356 p.print("skip " + p.tok.String())
357 }
358 p.next()
359 if len(followlist) == 0 {
360 break
361 }
362 }
363
364 if trace {
365 p.print("next " + p.tok.String())
366 }
367 }
368
369
370 func (p *parser) trace(msg string) func() {
371 p.print(msg + " (")
372 const tab = ". "
373 p.indent = append(p.indent, tab...)
374 return func() {
375 p.indent = p.indent[:len(p.indent)-len(tab)]
376 if x := recover(); x != nil {
377 panic(x)
378 }
379 p.print(")")
380 }
381 }
382
383 func (p *parser) print(msg string) {
384 fmt.Printf("%5d: %s%s\n", p.line, p.indent, msg)
385 }
386
387
388
389
390
391
392
393
394
395
396
397
398 func (p *parser) fileOrNil() *File {
399 if trace {
400 defer p.trace("file")()
401 }
402
403 f := new(File)
404 f.pos = p.pos()
405
406
407 f.GoVersion = p.goVersion
408 p.top = false
409 if !p.got(_Package) {
410 p.syntaxError("package statement must be first")
411 return nil
412 }
413 f.Pragma = p.takePragma()
414 f.PkgName = p.name()
415 p.want(_Semi)
416
417
418 if p.first != nil {
419 return nil
420 }
421
422
423
424 prev := _Import
425 for p.tok != _EOF {
426 if p.tok == _Import && prev != _Import {
427 p.syntaxError("imports must appear before other declarations")
428 }
429 prev = p.tok
430
431 switch p.tok {
432 case _Import:
433 p.next()
434 f.DeclList = p.appendGroup(f.DeclList, p.importDecl)
435
436 case _Const:
437 p.next()
438 f.DeclList = p.appendGroup(f.DeclList, p.constDecl)
439
440 case _Type:
441 p.next()
442 f.DeclList = p.appendGroup(f.DeclList, p.typeDecl)
443
444 case _Var:
445 p.next()
446 f.DeclList = p.appendGroup(f.DeclList, p.varDecl)
447
448 case _Func:
449 p.next()
450 if d := p.funcDeclOrNil(); d != nil {
451 f.DeclList = append(f.DeclList, d)
452 }
453
454 default:
455 if p.tok == _Lbrace && len(f.DeclList) > 0 && isEmptyFuncDecl(f.DeclList[len(f.DeclList)-1]) {
456
457 p.syntaxError("unexpected semicolon or newline before {")
458 } else {
459 p.syntaxError("non-declaration statement outside function body")
460 }
461 p.advance(_Import, _Const, _Type, _Var, _Func)
462 continue
463 }
464
465
466
467 p.clearPragma()
468
469 if p.tok != _EOF && !p.got(_Semi) {
470 p.syntaxError("after top level declaration")
471 p.advance(_Import, _Const, _Type, _Var, _Func)
472 }
473 }
474
475
476 p.clearPragma()
477 f.EOF = p.pos()
478
479 return f
480 }
481
482 func isEmptyFuncDecl(dcl Decl) bool {
483 f, ok := dcl.(*FuncDecl)
484 return ok && f.Body == nil
485 }
486
487
488
489
490
491
492
493
494
495
496
497
498
499 func (p *parser) list(context string, sep, close token, f func() bool) Pos {
500 if debug && (sep != _Comma && sep != _Semi || close != _Rparen && close != _Rbrace && close != _Rbrack) {
501 panic("invalid sep or close argument for list")
502 }
503
504 done := false
505 for p.tok != _EOF && p.tok != close && !done {
506 done = f()
507
508 if !p.got(sep) && p.tok != close {
509 p.syntaxError(fmt.Sprintf("in %s; possibly missing %s or %s", context, tokstring(sep), tokstring(close)))
510 p.advance(_Rparen, _Rbrack, _Rbrace)
511 if p.tok != close {
512
513 return p.pos()
514 }
515 }
516 }
517
518 pos := p.pos()
519 p.want(close)
520 return pos
521 }
522
523
524 func (p *parser) appendGroup(list []Decl, f func(*Group) Decl) []Decl {
525 if p.tok == _Lparen {
526 g := new(Group)
527 p.clearPragma()
528 p.next()
529 p.list("grouped declaration", _Semi, _Rparen, func() bool {
530 if x := f(g); x != nil {
531 list = append(list, x)
532 }
533 return false
534 })
535 } else {
536 if x := f(nil); x != nil {
537 list = append(list, x)
538 }
539 }
540 return list
541 }
542
543
544
545 func (p *parser) importDecl(group *Group) Decl {
546 if trace {
547 defer p.trace("importDecl")()
548 }
549
550 d := new(ImportDecl)
551 d.pos = p.pos()
552 d.Group = group
553 d.Pragma = p.takePragma()
554
555 switch p.tok {
556 case _Name:
557 d.LocalPkgName = p.name()
558 case _Dot:
559 d.LocalPkgName = NewName(p.pos(), ".")
560 p.next()
561 }
562 d.Path = p.oliteral()
563 if d.Path == nil {
564 p.syntaxError("missing import path")
565 p.advance(_Semi, _Rparen)
566 return d
567 }
568 if !d.Path.Bad && d.Path.Kind != StringLit {
569 p.syntaxErrorAt(d.Path.Pos(), "import path must be a string")
570 d.Path.Bad = true
571 }
572
573
574 return d
575 }
576
577
578 func (p *parser) constDecl(group *Group) Decl {
579 if trace {
580 defer p.trace("constDecl")()
581 }
582
583 d := new(ConstDecl)
584 d.pos = p.pos()
585 d.Group = group
586 d.Pragma = p.takePragma()
587
588 d.NameList = p.nameList(p.name())
589 if p.tok != _EOF && p.tok != _Semi && p.tok != _Rparen {
590 d.Type = p.typeOrNil()
591 if p.gotAssign() {
592 d.Values = p.exprList()
593 }
594 }
595
596 return d
597 }
598
599
600 func (p *parser) typeDecl(group *Group) Decl {
601 if trace {
602 defer p.trace("typeDecl")()
603 }
604
605 d := new(TypeDecl)
606 d.pos = p.pos()
607 d.Group = group
608 d.Pragma = p.takePragma()
609
610 d.Name = p.name()
611 if p.tok == _Lbrack {
612
613
614 pos := p.pos()
615 p.next()
616 switch p.tok {
617 case _Name:
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633 var x Expr = p.name()
634 if p.tok != _Lbrack {
635
636
637
638 p.xnest++
639 x = p.binaryExpr(p.pexpr(x, false), 0)
640 p.xnest--
641 }
642
643
644
645
646
647
648
649 if pname, ptype := extractName(x, p.tok == _Comma); pname != nil && (ptype != nil || p.tok != _Rbrack) {
650
651
652
653 d.TParamList = p.paramList(pname, ptype, _Rbrack, true)
654 d.Alias = p.gotAssign()
655 d.Type = p.typeOrNil()
656 } else {
657
658
659 d.Type = p.arrayType(pos, x)
660 }
661 case _Rbrack:
662
663 p.next()
664 d.Type = p.sliceType(pos)
665 default:
666
667 d.Type = p.arrayType(pos, nil)
668 }
669 } else {
670 d.Alias = p.gotAssign()
671 d.Type = p.typeOrNil()
672 }
673
674 if d.Type == nil {
675 d.Type = p.badExpr()
676 p.syntaxError("in type declaration")
677 p.advance(_Semi, _Rparen)
678 }
679
680 return d
681 }
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701 func extractName(x Expr, force bool) (*Name, Expr) {
702 switch x := x.(type) {
703 case *Name:
704 return x, nil
705 case *Operation:
706 if x.Y == nil {
707 break
708 }
709 switch x.Op {
710 case Mul:
711 if name, _ := x.X.(*Name); name != nil && (force || isTypeElem(x.Y)) {
712
713 op := *x
714 op.X, op.Y = op.Y, nil
715 return name, &op
716 }
717 case Or:
718 if name, lhs := extractName(x.X, force || isTypeElem(x.Y)); name != nil && lhs != nil {
719
720 op := *x
721 op.X = lhs
722 return name, &op
723 }
724 }
725 case *CallExpr:
726 if name, _ := x.Fun.(*Name); name != nil {
727 if len(x.ArgList) == 1 && !x.HasDots && (force || isTypeElem(x.ArgList[0])) {
728
729
730
731 const keep_parens = false
732 if keep_parens {
733
734 px := new(ParenExpr)
735 px.pos = x.pos
736 px.X = x.ArgList[0]
737 return name, px
738 } else {
739
740 return name, Unparen(x.ArgList[0])
741 }
742 }
743 }
744 }
745 return nil, x
746 }
747
748
749
750 func isTypeElem(x Expr) bool {
751 switch x := x.(type) {
752 case *ArrayType, *StructType, *FuncType, *InterfaceType, *SliceType, *MapType, *ChanType:
753 return true
754 case *Operation:
755 return isTypeElem(x.X) || (x.Y != nil && isTypeElem(x.Y)) || x.Op == Tilde
756 case *ParenExpr:
757 return isTypeElem(x.X)
758 }
759 return false
760 }
761
762
763 func (p *parser) varDecl(group *Group) Decl {
764 if trace {
765 defer p.trace("varDecl")()
766 }
767
768 d := new(VarDecl)
769 d.pos = p.pos()
770 d.Group = group
771 d.Pragma = p.takePragma()
772
773 d.NameList = p.nameList(p.name())
774 if p.gotAssign() {
775 d.Values = p.exprList()
776 } else {
777 d.Type = p.type_()
778 if p.gotAssign() {
779 d.Values = p.exprList()
780 }
781 }
782
783 return d
784 }
785
786
787
788
789
790
791 func (p *parser) funcDeclOrNil() *FuncDecl {
792 if trace {
793 defer p.trace("funcDecl")()
794 }
795
796 f := new(FuncDecl)
797 f.pos = p.pos()
798 f.Pragma = p.takePragma()
799
800 var context string
801 if p.got(_Lparen) {
802 context = "method"
803 rcvr := p.paramList(nil, nil, _Rparen, false)
804 switch len(rcvr) {
805 case 0:
806 p.error("method has no receiver")
807 default:
808 p.error("method has multiple receivers")
809 fallthrough
810 case 1:
811 f.Recv = rcvr[0]
812 }
813 }
814
815 if p.tok == _Name {
816 f.Name = p.name()
817 f.TParamList, f.Type = p.funcType(context)
818 } else {
819 f.Name = NewName(p.pos(), "_")
820 f.Type = new(FuncType)
821 f.Type.pos = p.pos()
822 msg := "expected name or ("
823 if context != "" {
824 msg = "expected name"
825 }
826 p.syntaxError(msg)
827 p.advance(_Lbrace, _Semi)
828 }
829
830 if p.tok == _Lbrace {
831 f.Body = p.funcBody()
832 }
833
834 return f
835 }
836
837 func (p *parser) funcBody() *BlockStmt {
838 p.fnest++
839 errcnt := p.errcnt
840 body := p.blockStmt("")
841 p.fnest--
842
843
844
845
846 if p.mode&CheckBranches != 0 && errcnt == p.errcnt {
847 checkBranches(body, p.errh)
848 }
849
850 return body
851 }
852
853
854
855
856 func (p *parser) expr() Expr {
857 if trace {
858 defer p.trace("expr")()
859 }
860
861 return p.binaryExpr(nil, 0)
862 }
863
864
865 func (p *parser) binaryExpr(x Expr, prec int) Expr {
866
867
868 if x == nil {
869 x = p.unaryExpr()
870 }
871 for (p.tok == _Operator || p.tok == _Star) && p.prec > prec {
872 t := new(Operation)
873 t.pos = p.pos()
874 t.Op = p.op
875 tprec := p.prec
876 p.next()
877 t.X = x
878 t.Y = p.binaryExpr(nil, tprec)
879 x = t
880 }
881 return x
882 }
883
884
885 func (p *parser) unaryExpr() Expr {
886 if trace {
887 defer p.trace("unaryExpr")()
888 }
889
890 switch p.tok {
891 case _Operator, _Star:
892 switch p.op {
893 case Mul, Add, Sub, Not, Xor, Tilde:
894 x := new(Operation)
895 x.pos = p.pos()
896 x.Op = p.op
897 p.next()
898 x.X = p.unaryExpr()
899 return x
900
901 case And:
902 x := new(Operation)
903 x.pos = p.pos()
904 x.Op = And
905 p.next()
906
907
908 x.X = Unparen(p.unaryExpr())
909 return x
910 }
911
912 case _Arrow:
913
914 pos := p.pos()
915 p.next()
916
917
918
919
920
921 x := p.unaryExpr()
922
923
924
925
926
927
928
929
930
931
932
933
934 if _, ok := x.(*ChanType); ok {
935
936 dir := SendOnly
937 t := x
938 for dir == SendOnly {
939 c, ok := t.(*ChanType)
940 if !ok {
941 break
942 }
943 dir = c.Dir
944 if dir == RecvOnly {
945
946
947 p.syntaxError("unexpected <-, expected chan")
948
949 }
950 c.Dir = RecvOnly
951 t = c.Elem
952 }
953 if dir == SendOnly {
954
955
956 p.syntaxError(fmt.Sprintf("unexpected %s, expected chan", String(t)))
957
958 }
959 return x
960 }
961
962
963 o := new(Operation)
964 o.pos = pos
965 o.Op = Recv
966 o.X = x
967 return o
968 }
969
970
971
972
973 return p.pexpr(nil, true)
974 }
975
976
977 func (p *parser) callStmt() *CallStmt {
978 if trace {
979 defer p.trace("callStmt")()
980 }
981
982 s := new(CallStmt)
983 s.pos = p.pos()
984 s.Tok = p.tok
985 p.next()
986
987 x := p.pexpr(nil, p.tok == _Lparen)
988 if t := Unparen(x); t != x {
989 p.errorAt(x.Pos(), fmt.Sprintf("expression in %s must not be parenthesized", s.Tok))
990
991 x = t
992 }
993
994 s.Call = x
995 return s
996 }
997
998
999
1000
1001
1002 func (p *parser) operand(keep_parens bool) Expr {
1003 if trace {
1004 defer p.trace("operand " + p.tok.String())()
1005 }
1006
1007 switch p.tok {
1008 case _Name:
1009 return p.name()
1010
1011 case _Literal:
1012 return p.oliteral()
1013
1014 case _Lparen:
1015 pos := p.pos()
1016 p.next()
1017 p.xnest++
1018 x := p.expr()
1019 p.xnest--
1020 p.want(_Rparen)
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030 if p.tok == _Lbrace {
1031 keep_parens = true
1032 }
1033
1034
1035
1036
1037 if keep_parens {
1038 px := new(ParenExpr)
1039 px.pos = pos
1040 px.X = x
1041 x = px
1042 }
1043 return x
1044
1045 case _Func:
1046 pos := p.pos()
1047 p.next()
1048 _, ftyp := p.funcType("function type")
1049 if p.tok == _Lbrace {
1050 p.xnest++
1051
1052 f := new(FuncLit)
1053 f.pos = pos
1054 f.Type = ftyp
1055 f.Body = p.funcBody()
1056
1057 p.xnest--
1058 return f
1059 }
1060 return ftyp
1061
1062 case _Lbrack, _Chan, _Map, _Struct, _Interface:
1063 return p.type_()
1064
1065 default:
1066 x := p.badExpr()
1067 p.syntaxError("expected expression")
1068 p.advance(_Rparen, _Rbrack, _Rbrace)
1069 return x
1070 }
1071
1072
1073
1074
1075
1076 }
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096 func (p *parser) pexpr(x Expr, keep_parens bool) Expr {
1097 if trace {
1098 defer p.trace("pexpr")()
1099 }
1100
1101 if x == nil {
1102 x = p.operand(keep_parens)
1103 }
1104
1105 loop:
1106 for {
1107 pos := p.pos()
1108 switch p.tok {
1109 case _Dot:
1110 p.next()
1111 switch p.tok {
1112 case _Name:
1113
1114 t := new(SelectorExpr)
1115 t.pos = pos
1116 t.X = x
1117 t.Sel = p.name()
1118 x = t
1119
1120 case _Lparen:
1121 p.next()
1122 if p.got(_Type) {
1123 t := new(TypeSwitchGuard)
1124
1125 t.pos = pos
1126 t.X = x
1127 x = t
1128 } else {
1129 t := new(AssertExpr)
1130 t.pos = pos
1131 t.X = x
1132 t.Type = p.type_()
1133 x = t
1134 }
1135 p.want(_Rparen)
1136
1137 default:
1138 p.syntaxError("expected name or (")
1139 p.advance(_Semi, _Rparen)
1140 }
1141
1142 case _Lbrack:
1143 p.next()
1144
1145 var i Expr
1146 if p.tok != _Colon {
1147 var comma bool
1148 if p.tok == _Rbrack {
1149
1150 p.syntaxError("expected operand")
1151 i = p.badExpr()
1152 } else {
1153 i, comma = p.typeList(false)
1154 }
1155 if comma || p.tok == _Rbrack {
1156 p.want(_Rbrack)
1157
1158 t := new(IndexExpr)
1159 t.pos = pos
1160 t.X = x
1161 t.Index = i
1162 x = t
1163 break
1164 }
1165 }
1166
1167
1168
1169 if !p.got(_Colon) {
1170 p.syntaxError("expected comma, : or ]")
1171 p.advance(_Comma, _Colon, _Rbrack)
1172 }
1173 p.xnest++
1174 t := new(SliceExpr)
1175 t.pos = pos
1176 t.X = x
1177 t.Index[0] = i
1178 if p.tok != _Colon && p.tok != _Rbrack {
1179
1180 t.Index[1] = p.expr()
1181 }
1182 if p.tok == _Colon {
1183 t.Full = true
1184
1185 if t.Index[1] == nil {
1186 p.error("middle index required in 3-index slice")
1187 t.Index[1] = p.badExpr()
1188 }
1189 p.next()
1190 if p.tok != _Rbrack {
1191
1192 t.Index[2] = p.expr()
1193 } else {
1194 p.error("final index required in 3-index slice")
1195 t.Index[2] = p.badExpr()
1196 }
1197 }
1198 p.xnest--
1199 p.want(_Rbrack)
1200 x = t
1201
1202 case _Lparen:
1203 t := new(CallExpr)
1204 t.pos = pos
1205 p.next()
1206 t.Fun = x
1207 t.ArgList, t.HasDots = p.argList()
1208 x = t
1209
1210 case _Lbrace:
1211
1212
1213 t := Unparen(x)
1214
1215 complit_ok := false
1216 switch t.(type) {
1217 case *Name, *SelectorExpr:
1218 if p.xnest >= 0 {
1219
1220 complit_ok = true
1221 }
1222 case *IndexExpr:
1223 if p.xnest >= 0 && !isValue(t) {
1224
1225 complit_ok = true
1226 }
1227 case *ArrayType, *SliceType, *StructType, *MapType:
1228
1229 complit_ok = true
1230 }
1231 if !complit_ok {
1232 break loop
1233 }
1234 if t != x {
1235 p.syntaxError("cannot parenthesize type in composite literal")
1236
1237 }
1238 n := p.complitexpr()
1239 n.Type = x
1240 x = n
1241
1242 default:
1243 break loop
1244 }
1245 }
1246
1247 return x
1248 }
1249
1250
1251 func isValue(x Expr) bool {
1252 switch x := x.(type) {
1253 case *BasicLit, *CompositeLit, *FuncLit, *SliceExpr, *AssertExpr, *TypeSwitchGuard, *CallExpr:
1254 return true
1255 case *Operation:
1256 return x.Op != Mul || x.Y != nil
1257 case *ParenExpr:
1258 return isValue(x.X)
1259 case *IndexExpr:
1260 return isValue(x.X) || isValue(x.Index)
1261 }
1262 return false
1263 }
1264
1265
1266 func (p *parser) bare_complitexpr() Expr {
1267 if trace {
1268 defer p.trace("bare_complitexpr")()
1269 }
1270
1271 if p.tok == _Lbrace {
1272
1273 return p.complitexpr()
1274 }
1275
1276 return p.expr()
1277 }
1278
1279
1280 func (p *parser) complitexpr() *CompositeLit {
1281 if trace {
1282 defer p.trace("complitexpr")()
1283 }
1284
1285 x := new(CompositeLit)
1286 x.pos = p.pos()
1287
1288 p.xnest++
1289 p.want(_Lbrace)
1290 x.Rbrace = p.list("composite literal", _Comma, _Rbrace, func() bool {
1291
1292 e := p.bare_complitexpr()
1293 if p.tok == _Colon {
1294
1295 l := new(KeyValueExpr)
1296 l.pos = p.pos()
1297 p.next()
1298 l.Key = e
1299 l.Value = p.bare_complitexpr()
1300 e = l
1301 x.NKeys++
1302 }
1303 x.ElemList = append(x.ElemList, e)
1304 return false
1305 })
1306 p.xnest--
1307
1308 return x
1309 }
1310
1311
1312
1313
1314 func (p *parser) type_() Expr {
1315 if trace {
1316 defer p.trace("type_")()
1317 }
1318
1319 typ := p.typeOrNil()
1320 if typ == nil {
1321 typ = p.badExpr()
1322 p.syntaxError("expected type")
1323 p.advance(_Comma, _Colon, _Semi, _Rparen, _Rbrack, _Rbrace)
1324 }
1325
1326 return typ
1327 }
1328
1329 func newIndirect(pos Pos, typ Expr) Expr {
1330 o := new(Operation)
1331 o.pos = pos
1332 o.Op = Mul
1333 o.X = typ
1334 return o
1335 }
1336
1337
1338
1339
1340
1341
1342
1343
1344 func (p *parser) typeOrNil() Expr {
1345 if trace {
1346 defer p.trace("typeOrNil")()
1347 }
1348
1349 pos := p.pos()
1350 switch p.tok {
1351 case _Star:
1352
1353 p.next()
1354 return newIndirect(pos, p.type_())
1355
1356 case _Arrow:
1357
1358 p.next()
1359 p.want(_Chan)
1360 t := new(ChanType)
1361 t.pos = pos
1362 t.Dir = RecvOnly
1363 t.Elem = p.chanElem()
1364 return t
1365
1366 case _Func:
1367
1368 p.next()
1369 _, t := p.funcType("function type")
1370 return t
1371
1372 case _Lbrack:
1373
1374
1375 p.next()
1376 if p.got(_Rbrack) {
1377 return p.sliceType(pos)
1378 }
1379 return p.arrayType(pos, nil)
1380
1381 case _Chan:
1382
1383
1384 p.next()
1385 t := new(ChanType)
1386 t.pos = pos
1387 if p.got(_Arrow) {
1388 t.Dir = SendOnly
1389 }
1390 t.Elem = p.chanElem()
1391 return t
1392
1393 case _Map:
1394
1395 p.next()
1396 p.want(_Lbrack)
1397 t := new(MapType)
1398 t.pos = pos
1399 t.Key = p.type_()
1400 p.want(_Rbrack)
1401 t.Value = p.type_()
1402 return t
1403
1404 case _Struct:
1405 return p.structType()
1406
1407 case _Interface:
1408 return p.interfaceType()
1409
1410 case _Name:
1411 return p.qualifiedName(nil)
1412
1413 case _Lparen:
1414 p.next()
1415 t := p.type_()
1416 p.want(_Rparen)
1417
1418
1419
1420 const keep_parens = false
1421 if keep_parens {
1422 px := new(ParenExpr)
1423 px.pos = pos
1424 px.X = t
1425 t = px
1426 }
1427 return t
1428 }
1429
1430 return nil
1431 }
1432
1433 func (p *parser) typeInstance(typ Expr) Expr {
1434 if trace {
1435 defer p.trace("typeInstance")()
1436 }
1437
1438 pos := p.pos()
1439 p.want(_Lbrack)
1440 x := new(IndexExpr)
1441 x.pos = pos
1442 x.X = typ
1443 if p.tok == _Rbrack {
1444 p.syntaxError("expected type argument list")
1445 x.Index = p.badExpr()
1446 } else {
1447 x.Index, _ = p.typeList(true)
1448 }
1449 p.want(_Rbrack)
1450 return x
1451 }
1452
1453
1454 func (p *parser) funcType(context string) ([]*Field, *FuncType) {
1455 if trace {
1456 defer p.trace("funcType")()
1457 }
1458
1459 typ := new(FuncType)
1460 typ.pos = p.pos()
1461
1462 var tparamList []*Field
1463 if p.got(_Lbrack) {
1464 if context != "" {
1465
1466 p.syntaxErrorAt(typ.pos, context+" must have no type parameters")
1467 }
1468 if p.tok == _Rbrack {
1469 p.syntaxError("empty type parameter list")
1470 p.next()
1471 } else {
1472 tparamList = p.paramList(nil, nil, _Rbrack, true)
1473 }
1474 }
1475
1476 p.want(_Lparen)
1477 typ.ParamList = p.paramList(nil, nil, _Rparen, false)
1478 typ.ResultList = p.funcResult()
1479
1480 return tparamList, typ
1481 }
1482
1483
1484
1485 func (p *parser) arrayType(pos Pos, len Expr) Expr {
1486 if trace {
1487 defer p.trace("arrayType")()
1488 }
1489
1490 if len == nil && !p.got(_DotDotDot) {
1491 p.xnest++
1492 len = p.expr()
1493 p.xnest--
1494 }
1495 if p.tok == _Comma {
1496
1497
1498
1499 p.syntaxError("unexpected comma; expected ]")
1500 p.next()
1501 }
1502 p.want(_Rbrack)
1503 t := new(ArrayType)
1504 t.pos = pos
1505 t.Len = len
1506 t.Elem = p.type_()
1507 return t
1508 }
1509
1510
1511 func (p *parser) sliceType(pos Pos) Expr {
1512 t := new(SliceType)
1513 t.pos = pos
1514 t.Elem = p.type_()
1515 return t
1516 }
1517
1518 func (p *parser) chanElem() Expr {
1519 if trace {
1520 defer p.trace("chanElem")()
1521 }
1522
1523 typ := p.typeOrNil()
1524 if typ == nil {
1525 typ = p.badExpr()
1526 p.syntaxError("missing channel element type")
1527
1528 }
1529
1530 return typ
1531 }
1532
1533
1534 func (p *parser) structType() *StructType {
1535 if trace {
1536 defer p.trace("structType")()
1537 }
1538
1539 typ := new(StructType)
1540 typ.pos = p.pos()
1541
1542 p.want(_Struct)
1543 p.want(_Lbrace)
1544 p.list("struct type", _Semi, _Rbrace, func() bool {
1545 p.fieldDecl(typ)
1546 return false
1547 })
1548
1549 return typ
1550 }
1551
1552
1553 func (p *parser) interfaceType() *InterfaceType {
1554 if trace {
1555 defer p.trace("interfaceType")()
1556 }
1557
1558 typ := new(InterfaceType)
1559 typ.pos = p.pos()
1560
1561 p.want(_Interface)
1562 p.want(_Lbrace)
1563 p.list("interface type", _Semi, _Rbrace, func() bool {
1564 var f *Field
1565 if p.tok == _Name {
1566 f = p.methodDecl()
1567 }
1568 if f == nil || f.Name == nil {
1569 f = p.embeddedElem(f)
1570 }
1571 typ.MethodList = append(typ.MethodList, f)
1572 return false
1573 })
1574
1575 return typ
1576 }
1577
1578
1579 func (p *parser) funcResult() []*Field {
1580 if trace {
1581 defer p.trace("funcResult")()
1582 }
1583
1584 if p.got(_Lparen) {
1585 return p.paramList(nil, nil, _Rparen, false)
1586 }
1587
1588 pos := p.pos()
1589 if typ := p.typeOrNil(); typ != nil {
1590 f := new(Field)
1591 f.pos = pos
1592 f.Type = typ
1593 return []*Field{f}
1594 }
1595
1596 return nil
1597 }
1598
1599 func (p *parser) addField(styp *StructType, pos Pos, name *Name, typ Expr, tag *BasicLit) {
1600 if tag != nil {
1601 for i := len(styp.FieldList) - len(styp.TagList); i > 0; i-- {
1602 styp.TagList = append(styp.TagList, nil)
1603 }
1604 styp.TagList = append(styp.TagList, tag)
1605 }
1606
1607 f := new(Field)
1608 f.pos = pos
1609 f.Name = name
1610 f.Type = typ
1611 styp.FieldList = append(styp.FieldList, f)
1612
1613 if debug && tag != nil && len(styp.FieldList) != len(styp.TagList) {
1614 panic("inconsistent struct field list")
1615 }
1616 }
1617
1618
1619
1620
1621 func (p *parser) fieldDecl(styp *StructType) {
1622 if trace {
1623 defer p.trace("fieldDecl")()
1624 }
1625
1626 pos := p.pos()
1627 switch p.tok {
1628 case _Name:
1629 name := p.name()
1630 if p.tok == _Dot || p.tok == _Literal || p.tok == _Semi || p.tok == _Rbrace {
1631
1632 typ := p.qualifiedName(name)
1633 tag := p.oliteral()
1634 p.addField(styp, pos, nil, typ, tag)
1635 break
1636 }
1637
1638
1639 names := p.nameList(name)
1640 var typ Expr
1641
1642
1643
1644 if len(names) == 1 && p.tok == _Lbrack {
1645 typ = p.arrayOrTArgs()
1646 if typ, ok := typ.(*IndexExpr); ok {
1647
1648 typ.X = name
1649 tag := p.oliteral()
1650 p.addField(styp, pos, nil, typ, tag)
1651 break
1652 }
1653 } else {
1654
1655 typ = p.type_()
1656 }
1657
1658 tag := p.oliteral()
1659
1660 for _, name := range names {
1661 p.addField(styp, name.Pos(), name, typ, tag)
1662 }
1663
1664 case _Star:
1665 p.next()
1666 var typ Expr
1667 if p.tok == _Lparen {
1668
1669 p.syntaxError("cannot parenthesize embedded type")
1670 p.next()
1671 typ = p.qualifiedName(nil)
1672 p.got(_Rparen)
1673 } else {
1674
1675 typ = p.qualifiedName(nil)
1676 }
1677 tag := p.oliteral()
1678 p.addField(styp, pos, nil, newIndirect(pos, typ), tag)
1679
1680 case _Lparen:
1681 p.syntaxError("cannot parenthesize embedded type")
1682 p.next()
1683 var typ Expr
1684 if p.tok == _Star {
1685
1686 pos := p.pos()
1687 p.next()
1688 typ = newIndirect(pos, p.qualifiedName(nil))
1689 } else {
1690
1691 typ = p.qualifiedName(nil)
1692 }
1693 p.got(_Rparen)
1694 tag := p.oliteral()
1695 p.addField(styp, pos, nil, typ, tag)
1696
1697 default:
1698 p.syntaxError("expected field name or embedded type")
1699 p.advance(_Semi, _Rbrace)
1700 }
1701 }
1702
1703 func (p *parser) arrayOrTArgs() Expr {
1704 if trace {
1705 defer p.trace("arrayOrTArgs")()
1706 }
1707
1708 pos := p.pos()
1709 p.want(_Lbrack)
1710 if p.got(_Rbrack) {
1711 return p.sliceType(pos)
1712 }
1713
1714
1715 n, comma := p.typeList(false)
1716 p.want(_Rbrack)
1717 if !comma {
1718 if elem := p.typeOrNil(); elem != nil {
1719
1720 t := new(ArrayType)
1721 t.pos = pos
1722 t.Len = n
1723 t.Elem = elem
1724 return t
1725 }
1726 }
1727
1728
1729 t := new(IndexExpr)
1730 t.pos = pos
1731
1732 t.Index = n
1733 return t
1734 }
1735
1736 func (p *parser) oliteral() *BasicLit {
1737 if p.tok == _Literal {
1738 b := new(BasicLit)
1739 b.pos = p.pos()
1740 b.Value = p.lit
1741 b.Kind = p.kind
1742 b.Bad = p.bad
1743 p.next()
1744 return b
1745 }
1746 return nil
1747 }
1748
1749
1750
1751
1752 func (p *parser) methodDecl() *Field {
1753 if trace {
1754 defer p.trace("methodDecl")()
1755 }
1756
1757 f := new(Field)
1758 f.pos = p.pos()
1759 name := p.name()
1760
1761 const context = "interface method"
1762
1763 switch p.tok {
1764 case _Lparen:
1765
1766 f.Name = name
1767 _, f.Type = p.funcType(context)
1768
1769 case _Lbrack:
1770
1771
1772
1773 pos := p.pos()
1774 p.next()
1775
1776
1777
1778 if p.tok == _Rbrack {
1779
1780 pos := p.pos()
1781 p.next()
1782 if p.tok == _Lparen {
1783
1784 p.errorAt(pos, "empty type parameter list")
1785 f.Name = name
1786 _, f.Type = p.funcType(context)
1787 } else {
1788 p.errorAt(pos, "empty type argument list")
1789 f.Type = name
1790 }
1791 break
1792 }
1793
1794
1795
1796 list := p.paramList(nil, nil, _Rbrack, false)
1797 if len(list) == 0 {
1798
1799
1800
1801 if p.tok == _Lparen {
1802 f.Name = name
1803 _, f.Type = p.funcType(context)
1804 } else {
1805 f.Type = name
1806 }
1807 break
1808 }
1809
1810
1811 if list[0].Name != nil {
1812
1813 f.Name = name
1814 _, f.Type = p.funcType(context)
1815 p.errorAt(pos, "interface method must have no type parameters")
1816 break
1817 }
1818
1819
1820 t := new(IndexExpr)
1821 t.pos = pos
1822 t.X = name
1823 if len(list) == 1 {
1824 t.Index = list[0].Type
1825 } else {
1826
1827 l := new(ListExpr)
1828 l.pos = list[0].Pos()
1829 l.ElemList = make([]Expr, len(list))
1830 for i := range list {
1831 l.ElemList[i] = list[i].Type
1832 }
1833 t.Index = l
1834 }
1835 f.Type = t
1836
1837 default:
1838
1839 f.Type = p.qualifiedName(name)
1840 }
1841
1842 return f
1843 }
1844
1845
1846 func (p *parser) embeddedElem(f *Field) *Field {
1847 if trace {
1848 defer p.trace("embeddedElem")()
1849 }
1850
1851 if f == nil {
1852 f = new(Field)
1853 f.pos = p.pos()
1854 f.Type = p.embeddedTerm()
1855 }
1856
1857 for p.tok == _Operator && p.op == Or {
1858 t := new(Operation)
1859 t.pos = p.pos()
1860 t.Op = Or
1861 p.next()
1862 t.X = f.Type
1863 t.Y = p.embeddedTerm()
1864 f.Type = t
1865 }
1866
1867 return f
1868 }
1869
1870
1871 func (p *parser) embeddedTerm() Expr {
1872 if trace {
1873 defer p.trace("embeddedTerm")()
1874 }
1875
1876 if p.tok == _Operator && p.op == Tilde {
1877 t := new(Operation)
1878 t.pos = p.pos()
1879 t.Op = Tilde
1880 p.next()
1881 t.X = p.type_()
1882 return t
1883 }
1884
1885 t := p.typeOrNil()
1886 if t == nil {
1887 t = p.badExpr()
1888 p.syntaxError("expected ~ term or type")
1889 p.advance(_Operator, _Semi, _Rparen, _Rbrack, _Rbrace)
1890 }
1891
1892 return t
1893 }
1894
1895
1896 func (p *parser) paramDeclOrNil(name *Name, follow token) *Field {
1897 if trace {
1898 defer p.trace("paramDeclOrNil")()
1899 }
1900
1901
1902 typeSetsOk := follow == _Rbrack
1903
1904 pos := p.pos()
1905 if name != nil {
1906 pos = name.pos
1907 } else if typeSetsOk && p.tok == _Operator && p.op == Tilde {
1908
1909 return p.embeddedElem(nil)
1910 }
1911
1912 f := new(Field)
1913 f.pos = pos
1914
1915 if p.tok == _Name || name != nil {
1916
1917 if name == nil {
1918 name = p.name()
1919 }
1920
1921 if p.tok == _Lbrack {
1922
1923 f.Type = p.arrayOrTArgs()
1924 if typ, ok := f.Type.(*IndexExpr); ok {
1925
1926 typ.X = name
1927 } else {
1928
1929 f.Name = name
1930 }
1931 if typeSetsOk && p.tok == _Operator && p.op == Or {
1932
1933
1934 f = p.embeddedElem(f)
1935 }
1936 return f
1937 }
1938
1939 if p.tok == _Dot {
1940
1941 f.Type = p.qualifiedName(name)
1942 if typeSetsOk && p.tok == _Operator && p.op == Or {
1943
1944 f = p.embeddedElem(f)
1945 }
1946 return f
1947 }
1948
1949 if typeSetsOk && p.tok == _Operator && p.op == Or {
1950
1951 f.Type = name
1952 return p.embeddedElem(f)
1953 }
1954
1955 f.Name = name
1956 }
1957
1958 if p.tok == _DotDotDot {
1959
1960 t := new(DotsType)
1961 t.pos = p.pos()
1962 p.next()
1963 t.Elem = p.typeOrNil()
1964 if t.Elem == nil {
1965 t.Elem = p.badExpr()
1966 p.syntaxError("... is missing type")
1967 }
1968 f.Type = t
1969 return f
1970 }
1971
1972 if typeSetsOk && p.tok == _Operator && p.op == Tilde {
1973
1974 f.Type = p.embeddedElem(nil).Type
1975 return f
1976 }
1977
1978 f.Type = p.typeOrNil()
1979 if typeSetsOk && p.tok == _Operator && p.op == Or && f.Type != nil {
1980
1981 f = p.embeddedElem(f)
1982 }
1983 if f.Name != nil || f.Type != nil {
1984 return f
1985 }
1986
1987 p.syntaxError("expected " + tokstring(follow))
1988 p.advance(_Comma, follow)
1989 return nil
1990 }
1991
1992
1993
1994
1995
1996
1997
1998 func (p *parser) paramList(name *Name, typ Expr, close token, requireNames bool) (list []*Field) {
1999 if trace {
2000 defer p.trace("paramList")()
2001 }
2002
2003
2004
2005 if name != nil && typ != nil && p.tok == close {
2006 p.next()
2007 par := new(Field)
2008 par.pos = name.pos
2009 par.Name = name
2010 par.Type = typ
2011 return []*Field{par}
2012 }
2013
2014 var named int
2015 var typed int
2016 end := p.list("parameter list", _Comma, close, func() bool {
2017 var par *Field
2018 if typ != nil {
2019 if debug && name == nil {
2020 panic("initial type provided without name")
2021 }
2022 par = new(Field)
2023 par.pos = name.pos
2024 par.Name = name
2025 par.Type = typ
2026 } else {
2027 par = p.paramDeclOrNil(name, close)
2028 }
2029 name = nil
2030 typ = nil
2031 if par != nil {
2032 if debug && par.Name == nil && par.Type == nil {
2033 panic("parameter without name or type")
2034 }
2035 if par.Name != nil && par.Type != nil {
2036 named++
2037 }
2038 if par.Type != nil {
2039 typed++
2040 }
2041 list = append(list, par)
2042 }
2043 return false
2044 })
2045
2046 if len(list) == 0 {
2047 return
2048 }
2049
2050
2051 if named == 0 && !requireNames {
2052
2053 for _, par := range list {
2054 if typ := par.Name; typ != nil {
2055 par.Type = typ
2056 par.Name = nil
2057 }
2058 }
2059 } else if named != len(list) {
2060
2061 var errPos Pos
2062 var typ Expr
2063 for i := len(list) - 1; i >= 0; i-- {
2064 par := list[i]
2065 if par.Type != nil {
2066 typ = par.Type
2067 if par.Name == nil {
2068 errPos = StartPos(typ)
2069 par.Name = NewName(errPos, "_")
2070 }
2071 } else if typ != nil {
2072 par.Type = typ
2073 } else {
2074
2075 errPos = par.Name.Pos()
2076 t := p.badExpr()
2077 t.pos = errPos
2078 par.Type = t
2079 }
2080 }
2081 if errPos.IsKnown() {
2082
2083
2084
2085
2086
2087
2088
2089 var msg string
2090 if named == typed {
2091 errPos = end
2092 if requireNames {
2093 msg = "missing type constraint"
2094 } else {
2095 msg = "missing parameter type"
2096 }
2097 } else {
2098 if requireNames {
2099 msg = "missing type parameter name"
2100
2101 if len(list) == 1 {
2102 msg += " or invalid array length"
2103 }
2104 } else {
2105 msg = "missing parameter name"
2106 }
2107 }
2108 p.syntaxErrorAt(errPos, msg)
2109 }
2110 }
2111
2112 return
2113 }
2114
2115 func (p *parser) badExpr() *BadExpr {
2116 b := new(BadExpr)
2117 b.pos = p.pos()
2118 return b
2119 }
2120
2121
2122
2123
2124
2125 func (p *parser) simpleStmt(lhs Expr, keyword token) SimpleStmt {
2126 if trace {
2127 defer p.trace("simpleStmt")()
2128 }
2129
2130 if keyword == _For && p.tok == _Range {
2131
2132 if debug && lhs != nil {
2133 panic("invalid call of simpleStmt")
2134 }
2135 return p.newRangeClause(nil, false)
2136 }
2137
2138 if lhs == nil {
2139 lhs = p.exprList()
2140 }
2141
2142 if _, ok := lhs.(*ListExpr); !ok && p.tok != _Assign && p.tok != _Define {
2143
2144 pos := p.pos()
2145 switch p.tok {
2146 case _AssignOp:
2147
2148 op := p.op
2149 p.next()
2150 return p.newAssignStmt(pos, op, lhs, p.expr())
2151
2152 case _IncOp:
2153
2154 op := p.op
2155 p.next()
2156 return p.newAssignStmt(pos, op, lhs, nil)
2157
2158 case _Arrow:
2159
2160 s := new(SendStmt)
2161 s.pos = pos
2162 p.next()
2163 s.Chan = lhs
2164 s.Value = p.expr()
2165 return s
2166
2167 default:
2168
2169 s := new(ExprStmt)
2170 s.pos = lhs.Pos()
2171 s.X = lhs
2172 return s
2173 }
2174 }
2175
2176
2177 switch p.tok {
2178 case _Assign, _Define:
2179 pos := p.pos()
2180 var op Operator
2181 if p.tok == _Define {
2182 op = Def
2183 }
2184 p.next()
2185
2186 if keyword == _For && p.tok == _Range {
2187
2188 return p.newRangeClause(lhs, op == Def)
2189 }
2190
2191
2192 rhs := p.exprList()
2193
2194 if x, ok := rhs.(*TypeSwitchGuard); ok && keyword == _Switch && op == Def {
2195 if lhs, ok := lhs.(*Name); ok {
2196
2197 x.Lhs = lhs
2198 s := new(ExprStmt)
2199 s.pos = x.Pos()
2200 s.X = x
2201 return s
2202 }
2203 }
2204
2205 return p.newAssignStmt(pos, op, lhs, rhs)
2206
2207 default:
2208 p.syntaxError("expected := or = or comma")
2209 p.advance(_Semi, _Rbrace)
2210
2211 if x, ok := lhs.(*ListExpr); ok {
2212 lhs = x.ElemList[0]
2213 }
2214 s := new(ExprStmt)
2215 s.pos = lhs.Pos()
2216 s.X = lhs
2217 return s
2218 }
2219 }
2220
2221 func (p *parser) newRangeClause(lhs Expr, def bool) *RangeClause {
2222 r := new(RangeClause)
2223 r.pos = p.pos()
2224 p.next()
2225 r.Lhs = lhs
2226 r.Def = def
2227 r.X = p.expr()
2228 return r
2229 }
2230
2231 func (p *parser) newAssignStmt(pos Pos, op Operator, lhs, rhs Expr) *AssignStmt {
2232 a := new(AssignStmt)
2233 a.pos = pos
2234 a.Op = op
2235 a.Lhs = lhs
2236 a.Rhs = rhs
2237 return a
2238 }
2239
2240 func (p *parser) labeledStmtOrNil(label *Name) Stmt {
2241 if trace {
2242 defer p.trace("labeledStmt")()
2243 }
2244
2245 s := new(LabeledStmt)
2246 s.pos = p.pos()
2247 s.Label = label
2248
2249 p.want(_Colon)
2250
2251 if p.tok == _Rbrace {
2252
2253
2254
2255 e := new(EmptyStmt)
2256 e.pos = p.pos()
2257 s.Stmt = e
2258 return s
2259 }
2260
2261 s.Stmt = p.stmtOrNil()
2262 if s.Stmt != nil {
2263 return s
2264 }
2265
2266
2267 p.syntaxErrorAt(s.pos, "missing statement after label")
2268
2269 return nil
2270 }
2271
2272
2273 func (p *parser) blockStmt(context string) *BlockStmt {
2274 if trace {
2275 defer p.trace("blockStmt")()
2276 }
2277
2278 s := new(BlockStmt)
2279 s.pos = p.pos()
2280
2281
2282 if !p.got(_Lbrace) {
2283 p.syntaxError("expected { after " + context)
2284 p.advance(_Name, _Rbrace)
2285 s.Rbrace = p.pos()
2286 if p.got(_Rbrace) {
2287 return s
2288 }
2289 }
2290
2291 s.List = p.stmtList()
2292 s.Rbrace = p.pos()
2293 p.want(_Rbrace)
2294
2295 return s
2296 }
2297
2298 func (p *parser) declStmt(f func(*Group) Decl) *DeclStmt {
2299 if trace {
2300 defer p.trace("declStmt")()
2301 }
2302
2303 s := new(DeclStmt)
2304 s.pos = p.pos()
2305
2306 p.next()
2307 s.DeclList = p.appendGroup(nil, f)
2308
2309 return s
2310 }
2311
2312 func (p *parser) forStmt() Stmt {
2313 if trace {
2314 defer p.trace("forStmt")()
2315 }
2316
2317 s := new(ForStmt)
2318 s.pos = p.pos()
2319
2320 s.Init, s.Cond, s.Post = p.header(_For)
2321 s.Body = p.blockStmt("for clause")
2322
2323 return s
2324 }
2325
2326 func (p *parser) header(keyword token) (init SimpleStmt, cond Expr, post SimpleStmt) {
2327 p.want(keyword)
2328
2329 if p.tok == _Lbrace {
2330 if keyword == _If {
2331 p.syntaxError("missing condition in if statement")
2332 cond = p.badExpr()
2333 }
2334 return
2335 }
2336
2337
2338 outer := p.xnest
2339 p.xnest = -1
2340
2341 if p.tok != _Semi {
2342
2343 if p.got(_Var) {
2344 p.syntaxError(fmt.Sprintf("var declaration not allowed in %s initializer", keyword.String()))
2345 }
2346 init = p.simpleStmt(nil, keyword)
2347
2348 if _, ok := init.(*RangeClause); ok {
2349 p.xnest = outer
2350 return
2351 }
2352 }
2353
2354 var condStmt SimpleStmt
2355 var semi struct {
2356 pos Pos
2357 lit string
2358 }
2359 if p.tok != _Lbrace {
2360 if p.tok == _Semi {
2361 semi.pos = p.pos()
2362 semi.lit = p.lit
2363 p.next()
2364 } else {
2365
2366 p.want(_Lbrace)
2367 if p.tok != _Lbrace {
2368 p.advance(_Lbrace, _Rbrace)
2369 }
2370 }
2371 if keyword == _For {
2372 if p.tok != _Semi {
2373 if p.tok == _Lbrace {
2374 p.syntaxError("expected for loop condition")
2375 goto done
2376 }
2377 condStmt = p.simpleStmt(nil, 0 )
2378 }
2379 p.want(_Semi)
2380 if p.tok != _Lbrace {
2381 post = p.simpleStmt(nil, 0 )
2382 if a, _ := post.(*AssignStmt); a != nil && a.Op == Def {
2383 p.syntaxErrorAt(a.Pos(), "cannot declare in post statement of for loop")
2384 }
2385 }
2386 } else if p.tok != _Lbrace {
2387 condStmt = p.simpleStmt(nil, keyword)
2388 }
2389 } else {
2390 condStmt = init
2391 init = nil
2392 }
2393
2394 done:
2395
2396 switch s := condStmt.(type) {
2397 case nil:
2398 if keyword == _If && semi.pos.IsKnown() {
2399 if semi.lit != "semicolon" {
2400 p.syntaxErrorAt(semi.pos, fmt.Sprintf("unexpected %s, expected { after if clause", semi.lit))
2401 } else {
2402 p.syntaxErrorAt(semi.pos, "missing condition in if statement")
2403 }
2404 b := new(BadExpr)
2405 b.pos = semi.pos
2406 cond = b
2407 }
2408 case *ExprStmt:
2409 cond = s.X
2410 default:
2411
2412
2413
2414
2415 var str string
2416 if as, ok := s.(*AssignStmt); ok && as.Op == 0 {
2417
2418 str = "assignment " + emphasize(as.Lhs) + " = " + emphasize(as.Rhs)
2419 } else {
2420 str = String(s)
2421 }
2422 p.syntaxErrorAt(s.Pos(), fmt.Sprintf("cannot use %s as value", str))
2423 }
2424
2425 p.xnest = outer
2426 return
2427 }
2428
2429
2430
2431 func emphasize(x Expr) string {
2432 s := String(x)
2433 if op, _ := x.(*Operation); op != nil && op.Y != nil {
2434
2435 return "(" + s + ")"
2436 }
2437 return s
2438 }
2439
2440 func (p *parser) ifStmt() *IfStmt {
2441 if trace {
2442 defer p.trace("ifStmt")()
2443 }
2444
2445 s := new(IfStmt)
2446 s.pos = p.pos()
2447
2448 s.Init, s.Cond, _ = p.header(_If)
2449 s.Then = p.blockStmt("if clause")
2450
2451 if p.got(_Else) {
2452 switch p.tok {
2453 case _If:
2454 s.Else = p.ifStmt()
2455 case _Lbrace:
2456 s.Else = p.blockStmt("")
2457 default:
2458 p.syntaxError("else must be followed by if or statement block")
2459 p.advance(_Name, _Rbrace)
2460 }
2461 }
2462
2463 return s
2464 }
2465
2466 func (p *parser) switchStmt() *SwitchStmt {
2467 if trace {
2468 defer p.trace("switchStmt")()
2469 }
2470
2471 s := new(SwitchStmt)
2472 s.pos = p.pos()
2473
2474 s.Init, s.Tag, _ = p.header(_Switch)
2475
2476 if !p.got(_Lbrace) {
2477 p.syntaxError("missing { after switch clause")
2478 p.advance(_Case, _Default, _Rbrace)
2479 }
2480 for p.tok != _EOF && p.tok != _Rbrace {
2481 s.Body = append(s.Body, p.caseClause())
2482 }
2483 s.Rbrace = p.pos()
2484 p.want(_Rbrace)
2485
2486 return s
2487 }
2488
2489 func (p *parser) selectStmt() *SelectStmt {
2490 if trace {
2491 defer p.trace("selectStmt")()
2492 }
2493
2494 s := new(SelectStmt)
2495 s.pos = p.pos()
2496
2497 p.want(_Select)
2498 if !p.got(_Lbrace) {
2499 p.syntaxError("missing { after select clause")
2500 p.advance(_Case, _Default, _Rbrace)
2501 }
2502 for p.tok != _EOF && p.tok != _Rbrace {
2503 s.Body = append(s.Body, p.commClause())
2504 }
2505 s.Rbrace = p.pos()
2506 p.want(_Rbrace)
2507
2508 return s
2509 }
2510
2511 func (p *parser) caseClause() *CaseClause {
2512 if trace {
2513 defer p.trace("caseClause")()
2514 }
2515
2516 c := new(CaseClause)
2517 c.pos = p.pos()
2518
2519 switch p.tok {
2520 case _Case:
2521 p.next()
2522 c.Cases = p.exprList()
2523
2524 case _Default:
2525 p.next()
2526
2527 default:
2528 p.syntaxError("expected case or default or }")
2529 p.advance(_Colon, _Case, _Default, _Rbrace)
2530 }
2531
2532 c.Colon = p.pos()
2533 p.want(_Colon)
2534 c.Body = p.stmtList()
2535
2536 return c
2537 }
2538
2539 func (p *parser) commClause() *CommClause {
2540 if trace {
2541 defer p.trace("commClause")()
2542 }
2543
2544 c := new(CommClause)
2545 c.pos = p.pos()
2546
2547 switch p.tok {
2548 case _Case:
2549 p.next()
2550 c.Comm = p.simpleStmt(nil, 0)
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562 case _Default:
2563 p.next()
2564
2565 default:
2566 p.syntaxError("expected case or default or }")
2567 p.advance(_Colon, _Case, _Default, _Rbrace)
2568 }
2569
2570 c.Colon = p.pos()
2571 p.want(_Colon)
2572 c.Body = p.stmtList()
2573
2574 return c
2575 }
2576
2577
2578
2579
2580
2581
2582
2583
2584 func (p *parser) stmtOrNil() Stmt {
2585 if trace {
2586 defer p.trace("stmt " + p.tok.String())()
2587 }
2588
2589
2590
2591 if p.tok == _Name {
2592 p.clearPragma()
2593 lhs := p.exprList()
2594 if label, ok := lhs.(*Name); ok && p.tok == _Colon {
2595 return p.labeledStmtOrNil(label)
2596 }
2597 return p.simpleStmt(lhs, 0)
2598 }
2599
2600 switch p.tok {
2601 case _Var:
2602 return p.declStmt(p.varDecl)
2603
2604 case _Const:
2605 return p.declStmt(p.constDecl)
2606
2607 case _Type:
2608 return p.declStmt(p.typeDecl)
2609 }
2610
2611 p.clearPragma()
2612
2613 switch p.tok {
2614 case _Lbrace:
2615 return p.blockStmt("")
2616
2617 case _Operator, _Star:
2618 switch p.op {
2619 case Add, Sub, Mul, And, Xor, Not:
2620 return p.simpleStmt(nil, 0)
2621 }
2622
2623 case _Literal, _Func, _Lparen,
2624 _Lbrack, _Struct, _Map, _Chan, _Interface,
2625 _Arrow:
2626 return p.simpleStmt(nil, 0)
2627
2628 case _For:
2629 return p.forStmt()
2630
2631 case _Switch:
2632 return p.switchStmt()
2633
2634 case _Select:
2635 return p.selectStmt()
2636
2637 case _If:
2638 return p.ifStmt()
2639
2640 case _Fallthrough:
2641 s := new(BranchStmt)
2642 s.pos = p.pos()
2643 p.next()
2644 s.Tok = _Fallthrough
2645 return s
2646
2647 case _Break, _Continue:
2648 s := new(BranchStmt)
2649 s.pos = p.pos()
2650 s.Tok = p.tok
2651 p.next()
2652 if p.tok == _Name {
2653 s.Label = p.name()
2654 }
2655 return s
2656
2657 case _Go, _Defer:
2658 return p.callStmt()
2659
2660 case _Goto:
2661 s := new(BranchStmt)
2662 s.pos = p.pos()
2663 s.Tok = _Goto
2664 p.next()
2665 s.Label = p.name()
2666 return s
2667
2668 case _Return:
2669 s := new(ReturnStmt)
2670 s.pos = p.pos()
2671 p.next()
2672 if p.tok != _Semi && p.tok != _Rbrace {
2673 s.Results = p.exprList()
2674 }
2675 return s
2676
2677 case _Semi:
2678 s := new(EmptyStmt)
2679 s.pos = p.pos()
2680 return s
2681 }
2682
2683 return nil
2684 }
2685
2686
2687 func (p *parser) stmtList() (l []Stmt) {
2688 if trace {
2689 defer p.trace("stmtList")()
2690 }
2691
2692 for p.tok != _EOF && p.tok != _Rbrace && p.tok != _Case && p.tok != _Default {
2693 s := p.stmtOrNil()
2694 p.clearPragma()
2695 if s == nil {
2696 break
2697 }
2698 l = append(l, s)
2699
2700 if !p.got(_Semi) && p.tok != _Rbrace {
2701 p.syntaxError("at end of statement")
2702 p.advance(_Semi, _Rbrace, _Case, _Default)
2703 p.got(_Semi)
2704 }
2705 }
2706 return
2707 }
2708
2709
2710
2711
2712
2713
2714 func (p *parser) argList() (list []Expr, hasDots bool) {
2715 if trace {
2716 defer p.trace("argList")()
2717 }
2718
2719 p.xnest++
2720 p.list("argument list", _Comma, _Rparen, func() bool {
2721 list = append(list, p.expr())
2722 hasDots = p.got(_DotDotDot)
2723 return hasDots
2724 })
2725 p.xnest--
2726
2727 return
2728 }
2729
2730
2731
2732
2733 func (p *parser) name() *Name {
2734
2735
2736 if p.tok == _Name {
2737 n := NewName(p.pos(), p.lit)
2738 p.next()
2739 return n
2740 }
2741
2742 n := NewName(p.pos(), "_")
2743 p.syntaxError("expected name")
2744 p.advance()
2745 return n
2746 }
2747
2748
2749
2750 func (p *parser) nameList(first *Name) []*Name {
2751 if trace {
2752 defer p.trace("nameList")()
2753 }
2754
2755 if debug && first == nil {
2756 panic("first name not provided")
2757 }
2758
2759 l := []*Name{first}
2760 for p.got(_Comma) {
2761 l = append(l, p.name())
2762 }
2763
2764 return l
2765 }
2766
2767
2768 func (p *parser) qualifiedName(name *Name) Expr {
2769 if trace {
2770 defer p.trace("qualifiedName")()
2771 }
2772
2773 var x Expr
2774 switch {
2775 case name != nil:
2776 x = name
2777 case p.tok == _Name:
2778 x = p.name()
2779 default:
2780 x = NewName(p.pos(), "_")
2781 p.syntaxError("expected name")
2782 p.advance(_Dot, _Semi, _Rbrace)
2783 }
2784
2785 if p.tok == _Dot {
2786 s := new(SelectorExpr)
2787 s.pos = p.pos()
2788 p.next()
2789 s.X = x
2790 s.Sel = p.name()
2791 x = s
2792 }
2793
2794 if p.tok == _Lbrack {
2795 x = p.typeInstance(x)
2796 }
2797
2798 return x
2799 }
2800
2801
2802 func (p *parser) exprList() Expr {
2803 if trace {
2804 defer p.trace("exprList")()
2805 }
2806
2807 x := p.expr()
2808 if p.got(_Comma) {
2809 list := []Expr{x, p.expr()}
2810 for p.got(_Comma) {
2811 list = append(list, p.expr())
2812 }
2813 t := new(ListExpr)
2814 t.pos = x.Pos()
2815 t.ElemList = list
2816 x = t
2817 }
2818 return x
2819 }
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829 func (p *parser) typeList(strict bool) (x Expr, comma bool) {
2830 if trace {
2831 defer p.trace("typeList")()
2832 }
2833
2834 p.xnest++
2835 if strict {
2836 x = p.type_()
2837 } else {
2838 x = p.expr()
2839 }
2840 if p.got(_Comma) {
2841 comma = true
2842 if t := p.typeOrNil(); t != nil {
2843 list := []Expr{x, t}
2844 for p.got(_Comma) {
2845 if t = p.typeOrNil(); t == nil {
2846 break
2847 }
2848 list = append(list, t)
2849 }
2850 l := new(ListExpr)
2851 l.pos = x.Pos()
2852 l.ElemList = list
2853 x = l
2854 }
2855 }
2856 p.xnest--
2857 return
2858 }
2859
2860
2861 func Unparen(x Expr) Expr {
2862 for {
2863 p, ok := x.(*ParenExpr)
2864 if !ok {
2865 break
2866 }
2867 x = p.X
2868 }
2869 return x
2870 }
2871
2872
2873 func UnpackListExpr(x Expr) []Expr {
2874 switch x := x.(type) {
2875 case nil:
2876 return nil
2877 case *ListExpr:
2878 return x.ElemList
2879 default:
2880 return []Expr{x}
2881 }
2882 }
2883
View as plain text