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