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