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