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