Source file src/pkg/go/parser/parser.go
1
2
3
4
5
6
7
8
9
10 package parser
11
12 import (
13 "fmt"
14 "go/ast"
15 "go/scanner"
16 "go/token"
17 "strconv"
18 "strings"
19 "unicode"
20 )
21
22
23 type parser struct {
24 file *token.File
25 errors scanner.ErrorList
26 scanner scanner.Scanner
27
28
29 mode Mode
30 trace bool
31 indent int
32
33
34 comments []*ast.CommentGroup
35 leadComment *ast.CommentGroup
36 lineComment *ast.CommentGroup
37
38
39 pos token.Pos
40 tok token.Token
41 lit string
42
43
44
45
46
47 syncPos token.Pos
48 syncCnt int
49
50
51 exprLev int
52 inRhs bool
53
54
55 pkgScope *ast.Scope
56 topScope *ast.Scope
57 unresolved []*ast.Ident
58 imports []*ast.ImportSpec
59
60
61
62 labelScope *ast.Scope
63 targetStack [][]*ast.Ident
64 }
65
66 func (p *parser) init(fset *token.FileSet, filename string, src []byte, mode Mode) {
67 p.file = fset.AddFile(filename, fset.Base(), len(src))
68 var m scanner.Mode
69 if mode&ParseComments != 0 {
70 m = scanner.ScanComments
71 }
72 eh := func(pos token.Position, msg string) { p.errors.Add(pos, msg) }
73 p.scanner.Init(p.file, src, eh, m)
74
75 p.mode = mode
76 p.trace = mode&Trace != 0
77
78 p.next()
79 }
80
81
82
83
84 func (p *parser) openScope() {
85 p.topScope = ast.NewScope(p.topScope)
86 }
87
88 func (p *parser) closeScope() {
89 p.topScope = p.topScope.Outer
90 }
91
92 func (p *parser) openLabelScope() {
93 p.labelScope = ast.NewScope(p.labelScope)
94 p.targetStack = append(p.targetStack, nil)
95 }
96
97 func (p *parser) closeLabelScope() {
98
99 n := len(p.targetStack) - 1
100 scope := p.labelScope
101 for _, ident := range p.targetStack[n] {
102 ident.Obj = scope.Lookup(ident.Name)
103 if ident.Obj == nil && p.mode&DeclarationErrors != 0 {
104 p.error(ident.Pos(), fmt.Sprintf("label %s undefined", ident.Name))
105 }
106 }
107
108 p.targetStack = p.targetStack[0:n]
109 p.labelScope = p.labelScope.Outer
110 }
111
112 func (p *parser) declare(decl, data interface{}, scope *ast.Scope, kind ast.ObjKind, idents ...*ast.Ident) {
113 for _, ident := range idents {
114 assert(ident.Obj == nil, "identifier already declared or resolved")
115 obj := ast.NewObj(kind, ident.Name)
116
117
118 obj.Decl = decl
119 obj.Data = data
120 ident.Obj = obj
121 if ident.Name != "_" {
122 if alt := scope.Insert(obj); alt != nil && p.mode&DeclarationErrors != 0 {
123 prevDecl := ""
124 if pos := alt.Pos(); pos.IsValid() {
125 prevDecl = fmt.Sprintf("\n\tprevious declaration at %s", p.file.Position(pos))
126 }
127 p.error(ident.Pos(), fmt.Sprintf("%s redeclared in this block%s", ident.Name, prevDecl))
128 }
129 }
130 }
131 }
132
133 func (p *parser) shortVarDecl(decl *ast.AssignStmt, list []ast.Expr) {
134
135
136
137 n := 0
138 for _, x := range list {
139 if ident, isIdent := x.(*ast.Ident); isIdent {
140 assert(ident.Obj == nil, "identifier already declared or resolved")
141 obj := ast.NewObj(ast.Var, ident.Name)
142
143 obj.Decl = decl
144 ident.Obj = obj
145 if ident.Name != "_" {
146 if alt := p.topScope.Insert(obj); alt != nil {
147 ident.Obj = alt
148 } else {
149 n++
150 }
151 }
152 } else {
153 p.errorExpected(x.Pos(), "identifier on left side of :=")
154 }
155 }
156 if n == 0 && p.mode&DeclarationErrors != 0 {
157 p.error(list[0].Pos(), "no new variables on left side of :=")
158 }
159 }
160
161
162
163
164 var unresolved = new(ast.Object)
165
166
167
168
169
170
171 func (p *parser) tryResolve(x ast.Expr, collectUnresolved bool) {
172
173 ident, _ := x.(*ast.Ident)
174 if ident == nil {
175 return
176 }
177 assert(ident.Obj == nil, "identifier already declared or resolved")
178 if ident.Name == "_" {
179 return
180 }
181
182 for s := p.topScope; s != nil; s = s.Outer {
183 if obj := s.Lookup(ident.Name); obj != nil {
184 ident.Obj = obj
185 return
186 }
187 }
188
189
190
191
192 if collectUnresolved {
193 ident.Obj = unresolved
194 p.unresolved = append(p.unresolved, ident)
195 }
196 }
197
198 func (p *parser) resolve(x ast.Expr) {
199 p.tryResolve(x, true)
200 }
201
202
203
204
205 func (p *parser) printTrace(a ...interface{}) {
206 const dots = ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
207 const n = len(dots)
208 pos := p.file.Position(p.pos)
209 fmt.Printf("%5d:%3d: ", pos.Line, pos.Column)
210 i := 2 * p.indent
211 for i > n {
212 fmt.Print(dots)
213 i -= n
214 }
215
216 fmt.Print(dots[0:i])
217 fmt.Println(a...)
218 }
219
220 func trace(p *parser, msg string) *parser {
221 p.printTrace(msg, "(")
222 p.indent++
223 return p
224 }
225
226
227 func un(p *parser) {
228 p.indent--
229 p.printTrace(")")
230 }
231
232
233 func (p *parser) next0() {
234
235
236
237
238 if p.trace && p.pos.IsValid() {
239 s := p.tok.String()
240 switch {
241 case p.tok.IsLiteral():
242 p.printTrace(s, p.lit)
243 case p.tok.IsOperator(), p.tok.IsKeyword():
244 p.printTrace("\"" + s + "\"")
245 default:
246 p.printTrace(s)
247 }
248 }
249
250 p.pos, p.tok, p.lit = p.scanner.Scan()
251 }
252
253
254 func (p *parser) consumeComment() (comment *ast.Comment, endline int) {
255
256
257 endline = p.file.Line(p.pos)
258 if p.lit[1] == '*' {
259
260 for i := 0; i < len(p.lit); i++ {
261 if p.lit[i] == '\n' {
262 endline++
263 }
264 }
265 }
266
267 comment = &ast.Comment{Slash: p.pos, Text: p.lit}
268 p.next0()
269
270 return
271 }
272
273
274
275
276
277
278 func (p *parser) consumeCommentGroup(n int) (comments *ast.CommentGroup, endline int) {
279 var list []*ast.Comment
280 endline = p.file.Line(p.pos)
281 for p.tok == token.COMMENT && p.file.Line(p.pos) <= endline+n {
282 var comment *ast.Comment
283 comment, endline = p.consumeComment()
284 list = append(list, comment)
285 }
286
287
288 comments = &ast.CommentGroup{List: list}
289 p.comments = append(p.comments, comments)
290
291 return
292 }
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309 func (p *parser) next() {
310 p.leadComment = nil
311 p.lineComment = nil
312 prev := p.pos
313 p.next0()
314
315 if p.tok == token.COMMENT {
316 var comment *ast.CommentGroup
317 var endline int
318
319 if p.file.Line(p.pos) == p.file.Line(prev) {
320
321
322 comment, endline = p.consumeCommentGroup(0)
323 if p.file.Line(p.pos) != endline {
324
325
326 p.lineComment = comment
327 }
328 }
329
330
331 endline = -1
332 for p.tok == token.COMMENT {
333 comment, endline = p.consumeCommentGroup(1)
334 }
335
336 if endline+1 == p.file.Line(p.pos) {
337
338
339 p.leadComment = comment
340 }
341 }
342 }
343
344
345 type bailout struct{}
346
347 func (p *parser) error(pos token.Pos, msg string) {
348 epos := p.file.Position(pos)
349
350
351
352
353 if p.mode&AllErrors == 0 {
354 n := len(p.errors)
355 if n > 0 && p.errors[n-1].Pos.Line == epos.Line {
356 return
357 }
358 if n > 10 {
359 panic(bailout{})
360 }
361 }
362
363 p.errors.Add(epos, msg)
364 }
365
366 func (p *parser) errorExpected(pos token.Pos, msg string) {
367 msg = "expected " + msg
368 if pos == p.pos {
369
370
371 if p.tok == token.SEMICOLON && p.lit == "\n" {
372 msg += ", found newline"
373 } else {
374 msg += ", found '" + p.tok.String() + "'"
375 if p.tok.IsLiteral() {
376 msg += " " + p.lit
377 }
378 }
379 }
380 p.error(pos, msg)
381 }
382
383 func (p *parser) expect(tok token.Token) token.Pos {
384 pos := p.pos
385 if p.tok != tok {
386 p.errorExpected(pos, "'"+tok.String()+"'")
387 }
388 p.next()
389 return pos
390 }
391
392
393
394
395 func (p *parser) expectClosing(tok token.Token, context string) token.Pos {
396 if p.tok != tok && p.tok == token.SEMICOLON && p.lit == "\n" {
397 p.error(p.pos, "missing ',' before newline in "+context)
398 p.next()
399 }
400 return p.expect(tok)
401 }
402
403 func (p *parser) expectSemi() {
404
405 if p.tok != token.RPAREN && p.tok != token.RBRACE {
406 if p.tok == token.SEMICOLON {
407 p.next()
408 } else {
409 p.errorExpected(p.pos, "';'")
410 syncStmt(p)
411 }
412 }
413 }
414
415 func (p *parser) atComma(context string) bool {
416 if p.tok == token.COMMA {
417 return true
418 }
419 if p.tok == token.SEMICOLON && p.lit == "\n" {
420 p.error(p.pos, "missing ',' before newline in "+context)
421 return true
422
423 }
424 return false
425 }
426
427 func assert(cond bool, msg string) {
428 if !cond {
429 panic("go/parser internal error: " + msg)
430 }
431 }
432
433
434
435
436 func syncStmt(p *parser) {
437 for {
438 switch p.tok {
439 case token.BREAK, token.CONST, token.CONTINUE, token.DEFER,
440 token.FALLTHROUGH, token.FOR, token.GO, token.GOTO,
441 token.IF, token.RETURN, token.SELECT, token.SWITCH,
442 token.TYPE, token.VAR:
443
444
445
446
447
448
449
450 if p.pos == p.syncPos && p.syncCnt < 10 {
451 p.syncCnt++
452 return
453 }
454 if p.pos > p.syncPos {
455 p.syncPos = p.pos
456 p.syncCnt = 0
457 return
458 }
459
460
461
462
463
464 case token.EOF:
465 return
466 }
467 p.next()
468 }
469 }
470
471
472
473
474 func syncDecl(p *parser) {
475 for {
476 switch p.tok {
477 case token.CONST, token.TYPE, token.VAR:
478
479 if p.pos == p.syncPos && p.syncCnt < 10 {
480 p.syncCnt++
481 return
482 }
483 if p.pos > p.syncPos {
484 p.syncPos = p.pos
485 p.syncCnt = 0
486 return
487 }
488 case token.EOF:
489 return
490 }
491 p.next()
492 }
493 }
494
495
496
497
498 func (p *parser) parseIdent() *ast.Ident {
499 pos := p.pos
500 name := "_"
501 if p.tok == token.IDENT {
502 name = p.lit
503 p.next()
504 } else {
505 p.expect(token.IDENT)
506 }
507 return &ast.Ident{NamePos: pos, Name: name}
508 }
509
510 func (p *parser) parseIdentList() (list []*ast.Ident) {
511 if p.trace {
512 defer un(trace(p, "IdentList"))
513 }
514
515 list = append(list, p.parseIdent())
516 for p.tok == token.COMMA {
517 p.next()
518 list = append(list, p.parseIdent())
519 }
520
521 return
522 }
523
524
525
526
527
528 func (p *parser) parseExprList(lhs bool) (list []ast.Expr) {
529 if p.trace {
530 defer un(trace(p, "ExpressionList"))
531 }
532
533 list = append(list, p.checkExpr(p.parseExpr(lhs)))
534 for p.tok == token.COMMA {
535 p.next()
536 list = append(list, p.checkExpr(p.parseExpr(lhs)))
537 }
538
539 return
540 }
541
542 func (p *parser) parseLhsList() []ast.Expr {
543 old := p.inRhs
544 p.inRhs = false
545 list := p.parseExprList(true)
546 switch p.tok {
547 case token.DEFINE:
548
549
550
551
552 case token.COLON:
553
554
555
556
557
558
559
560 default:
561
562 for _, x := range list {
563 p.resolve(x)
564 }
565 }
566 p.inRhs = old
567 return list
568 }
569
570 func (p *parser) parseRhsList() []ast.Expr {
571 old := p.inRhs
572 p.inRhs = true
573 list := p.parseExprList(false)
574 p.inRhs = old
575 return list
576 }
577
578
579
580
581 func (p *parser) parseType() ast.Expr {
582 if p.trace {
583 defer un(trace(p, "Type"))
584 }
585
586 typ := p.tryType()
587
588 if typ == nil {
589 pos := p.pos
590 p.errorExpected(pos, "type")
591 p.next()
592 return &ast.BadExpr{From: pos, To: p.pos}
593 }
594
595 return typ
596 }
597
598
599 func (p *parser) parseTypeName() ast.Expr {
600 if p.trace {
601 defer un(trace(p, "TypeName"))
602 }
603
604 ident := p.parseIdent()
605
606
607 if p.tok == token.PERIOD {
608
609 p.next()
610 p.resolve(ident)
611 sel := p.parseIdent()
612 return &ast.SelectorExpr{X: ident, Sel: sel}
613 }
614
615 return ident
616 }
617
618 func (p *parser) parseArrayType() ast.Expr {
619 if p.trace {
620 defer un(trace(p, "ArrayType"))
621 }
622
623 lbrack := p.expect(token.LBRACK)
624 var len ast.Expr
625
626 if p.tok == token.ELLIPSIS {
627 len = &ast.Ellipsis{Ellipsis: p.pos}
628 p.next()
629 } else if p.tok != token.RBRACK {
630 len = p.parseRhs()
631 }
632 p.expect(token.RBRACK)
633 elt := p.parseType()
634
635 return &ast.ArrayType{Lbrack: lbrack, Len: len, Elt: elt}
636 }
637
638 func (p *parser) makeIdentList(list []ast.Expr) []*ast.Ident {
639 idents := make([]*ast.Ident, len(list))
640 for i, x := range list {
641 ident, isIdent := x.(*ast.Ident)
642 if !isIdent {
643 if _, isBad := x.(*ast.BadExpr); !isBad {
644
645 p.errorExpected(x.Pos(), "identifier")
646 }
647 ident = &ast.Ident{NamePos: x.Pos(), Name: "_"}
648 }
649 idents[i] = ident
650 }
651 return idents
652 }
653
654 func (p *parser) parseFieldDecl(scope *ast.Scope) *ast.Field {
655 if p.trace {
656 defer un(trace(p, "FieldDecl"))
657 }
658
659 doc := p.leadComment
660
661
662 list, typ := p.parseVarList(false)
663
664
665 var tag *ast.BasicLit
666 if p.tok == token.STRING {
667 tag = &ast.BasicLit{ValuePos: p.pos, Kind: p.tok, Value: p.lit}
668 p.next()
669 }
670
671
672 var idents []*ast.Ident
673 if typ != nil {
674
675 idents = p.makeIdentList(list)
676 } else {
677
678 typ = list[0]
679 if n := len(list); n > 1 || !isTypeName(deref(typ)) {
680 pos := typ.Pos()
681 p.errorExpected(pos, "anonymous field")
682 typ = &ast.BadExpr{From: pos, To: list[n-1].End()}
683 }
684 }
685
686 p.expectSemi()
687
688 field := &ast.Field{Doc: doc, Names: idents, Type: typ, Tag: tag, Comment: p.lineComment}
689 p.declare(field, nil, scope, ast.Var, idents...)
690 p.resolve(typ)
691
692 return field
693 }
694
695 func (p *parser) parseStructType() *ast.StructType {
696 if p.trace {
697 defer un(trace(p, "StructType"))
698 }
699
700 pos := p.expect(token.STRUCT)
701 lbrace := p.expect(token.LBRACE)
702 scope := ast.NewScope(nil)
703 var list []*ast.Field
704 for p.tok == token.IDENT || p.tok == token.MUL || p.tok == token.LPAREN {
705
706
707
708 list = append(list, p.parseFieldDecl(scope))
709 }
710 rbrace := p.expect(token.RBRACE)
711
712 return &ast.StructType{
713 Struct: pos,
714 Fields: &ast.FieldList{
715 Opening: lbrace,
716 List: list,
717 Closing: rbrace,
718 },
719 }
720 }
721
722 func (p *parser) parsePointerType() *ast.StarExpr {
723 if p.trace {
724 defer un(trace(p, "PointerType"))
725 }
726
727 star := p.expect(token.MUL)
728 base := p.parseType()
729
730 return &ast.StarExpr{Star: star, X: base}
731 }
732
733
734 func (p *parser) tryVarType(isParam bool) ast.Expr {
735 if isParam && p.tok == token.ELLIPSIS {
736 pos := p.pos
737 p.next()
738 typ := p.tryIdentOrType()
739 if typ != nil {
740 p.resolve(typ)
741 } else {
742 p.error(pos, "'...' parameter is missing type")
743 typ = &ast.BadExpr{From: pos, To: p.pos}
744 }
745 return &ast.Ellipsis{Ellipsis: pos, Elt: typ}
746 }
747 return p.tryIdentOrType()
748 }
749
750
751 func (p *parser) parseVarType(isParam bool) ast.Expr {
752 typ := p.tryVarType(isParam)
753 if typ == nil {
754 pos := p.pos
755 p.errorExpected(pos, "type")
756 p.next()
757 typ = &ast.BadExpr{From: pos, To: p.pos}
758 }
759 return typ
760 }
761
762
763 func (p *parser) parseVarList(isParam bool) (list []ast.Expr, typ ast.Expr) {
764 if p.trace {
765 defer un(trace(p, "VarList"))
766 }
767
768
769
770
771
772
773 for typ := p.parseVarType(isParam); typ != nil; {
774 list = append(list, typ)
775 if p.tok != token.COMMA {
776 break
777 }
778 p.next()
779 typ = p.tryVarType(isParam)
780 }
781
782
783 typ = p.tryVarType(isParam)
784
785 return
786 }
787
788 func (p *parser) parseParameterList(scope *ast.Scope, ellipsisOk bool) (params []*ast.Field) {
789 if p.trace {
790 defer un(trace(p, "ParameterList"))
791 }
792
793
794 list, typ := p.parseVarList(ellipsisOk)
795
796
797 if typ != nil {
798
799 idents := p.makeIdentList(list)
800 field := &ast.Field{Names: idents, Type: typ}
801 params = append(params, field)
802
803
804 p.declare(field, nil, scope, ast.Var, idents...)
805 p.resolve(typ)
806 if p.tok == token.COMMA {
807 p.next()
808 }
809 for p.tok != token.RPAREN && p.tok != token.EOF {
810 idents := p.parseIdentList()
811 typ := p.parseVarType(ellipsisOk)
812 field := &ast.Field{Names: idents, Type: typ}
813 params = append(params, field)
814
815
816 p.declare(field, nil, scope, ast.Var, idents...)
817 p.resolve(typ)
818 if !p.atComma("parameter list") {
819 break
820 }
821 p.next()
822 }
823 } else {
824
825 params = make([]*ast.Field, len(list))
826 for i, typ := range list {
827 p.resolve(typ)
828 params[i] = &ast.Field{Type: typ}
829 }
830 }
831
832 return
833 }
834
835 func (p *parser) parseParameters(scope *ast.Scope, ellipsisOk bool) *ast.FieldList {
836 if p.trace {
837 defer un(trace(p, "Parameters"))
838 }
839
840 var params []*ast.Field
841 lparen := p.expect(token.LPAREN)
842 if p.tok != token.RPAREN {
843 params = p.parseParameterList(scope, ellipsisOk)
844 }
845 rparen := p.expect(token.RPAREN)
846
847 return &ast.FieldList{Opening: lparen, List: params, Closing: rparen}
848 }
849
850 func (p *parser) parseResult(scope *ast.Scope) *ast.FieldList {
851 if p.trace {
852 defer un(trace(p, "Result"))
853 }
854
855 if p.tok == token.LPAREN {
856 return p.parseParameters(scope, false)
857 }
858
859 typ := p.tryType()
860 if typ != nil {
861 list := make([]*ast.Field, 1)
862 list[0] = &ast.Field{Type: typ}
863 return &ast.FieldList{List: list}
864 }
865
866 return nil
867 }
868
869 func (p *parser) parseSignature(scope *ast.Scope) (params, results *ast.FieldList) {
870 if p.trace {
871 defer un(trace(p, "Signature"))
872 }
873
874 params = p.parseParameters(scope, true)
875 results = p.parseResult(scope)
876
877 return
878 }
879
880 func (p *parser) parseFuncType() (*ast.FuncType, *ast.Scope) {
881 if p.trace {
882 defer un(trace(p, "FuncType"))
883 }
884
885 pos := p.expect(token.FUNC)
886 scope := ast.NewScope(p.topScope)
887 params, results := p.parseSignature(scope)
888
889 return &ast.FuncType{Func: pos, Params: params, Results: results}, scope
890 }
891
892 func (p *parser) parseMethodSpec(scope *ast.Scope) *ast.Field {
893 if p.trace {
894 defer un(trace(p, "MethodSpec"))
895 }
896
897 doc := p.leadComment
898 var idents []*ast.Ident
899 var typ ast.Expr
900 x := p.parseTypeName()
901 if ident, isIdent := x.(*ast.Ident); isIdent && p.tok == token.LPAREN {
902
903 idents = []*ast.Ident{ident}
904 scope := ast.NewScope(nil)
905 params, results := p.parseSignature(scope)
906 typ = &ast.FuncType{Func: token.NoPos, Params: params, Results: results}
907 } else {
908
909 typ = x
910 p.resolve(typ)
911 }
912 p.expectSemi()
913
914 spec := &ast.Field{Doc: doc, Names: idents, Type: typ, Comment: p.lineComment}
915 p.declare(spec, nil, scope, ast.Fun, idents...)
916
917 return spec
918 }
919
920 func (p *parser) parseInterfaceType() *ast.InterfaceType {
921 if p.trace {
922 defer un(trace(p, "InterfaceType"))
923 }
924
925 pos := p.expect(token.INTERFACE)
926 lbrace := p.expect(token.LBRACE)
927 scope := ast.NewScope(nil)
928 var list []*ast.Field
929 for p.tok == token.IDENT {
930 list = append(list, p.parseMethodSpec(scope))
931 }
932 rbrace := p.expect(token.RBRACE)
933
934 return &ast.InterfaceType{
935 Interface: pos,
936 Methods: &ast.FieldList{
937 Opening: lbrace,
938 List: list,
939 Closing: rbrace,
940 },
941 }
942 }
943
944 func (p *parser) parseMapType() *ast.MapType {
945 if p.trace {
946 defer un(trace(p, "MapType"))
947 }
948
949 pos := p.expect(token.MAP)
950 p.expect(token.LBRACK)
951 key := p.parseType()
952 p.expect(token.RBRACK)
953 value := p.parseType()
954
955 return &ast.MapType{Map: pos, Key: key, Value: value}
956 }
957
958 func (p *parser) parseChanType() *ast.ChanType {
959 if p.trace {
960 defer un(trace(p, "ChanType"))
961 }
962
963 pos := p.pos
964 dir := ast.SEND | ast.RECV
965 var arrow token.Pos
966 if p.tok == token.CHAN {
967 p.next()
968 if p.tok == token.ARROW {
969 arrow = p.pos
970 p.next()
971 dir = ast.SEND
972 }
973 } else {
974 arrow = p.expect(token.ARROW)
975 p.expect(token.CHAN)
976 dir = ast.RECV
977 }
978 value := p.parseType()
979
980 return &ast.ChanType{Begin: pos, Arrow: arrow, Dir: dir, Value: value}
981 }
982
983
984 func (p *parser) tryIdentOrType() ast.Expr {
985 switch p.tok {
986 case token.IDENT:
987 return p.parseTypeName()
988 case token.LBRACK:
989 return p.parseArrayType()
990 case token.STRUCT:
991 return p.parseStructType()
992 case token.MUL:
993 return p.parsePointerType()
994 case token.FUNC:
995 typ, _ := p.parseFuncType()
996 return typ
997 case token.INTERFACE:
998 return p.parseInterfaceType()
999 case token.MAP:
1000 return p.parseMapType()
1001 case token.CHAN, token.ARROW:
1002 return p.parseChanType()
1003 case token.LPAREN:
1004 lparen := p.pos
1005 p.next()
1006 typ := p.parseType()
1007 rparen := p.expect(token.RPAREN)
1008 return &ast.ParenExpr{Lparen: lparen, X: typ, Rparen: rparen}
1009 }
1010
1011
1012 return nil
1013 }
1014
1015 func (p *parser) tryType() ast.Expr {
1016 typ := p.tryIdentOrType()
1017 if typ != nil {
1018 p.resolve(typ)
1019 }
1020 return typ
1021 }
1022
1023
1024
1025
1026 func (p *parser) parseStmtList() (list []ast.Stmt) {
1027 if p.trace {
1028 defer un(trace(p, "StatementList"))
1029 }
1030
1031 for p.tok != token.CASE && p.tok != token.DEFAULT && p.tok != token.RBRACE && p.tok != token.EOF {
1032 list = append(list, p.parseStmt())
1033 }
1034
1035 return
1036 }
1037
1038 func (p *parser) parseBody(scope *ast.Scope) *ast.BlockStmt {
1039 if p.trace {
1040 defer un(trace(p, "Body"))
1041 }
1042
1043 lbrace := p.expect(token.LBRACE)
1044 p.topScope = scope
1045 p.openLabelScope()
1046 list := p.parseStmtList()
1047 p.closeLabelScope()
1048 p.closeScope()
1049 rbrace := p.expect(token.RBRACE)
1050
1051 return &ast.BlockStmt{Lbrace: lbrace, List: list, Rbrace: rbrace}
1052 }
1053
1054 func (p *parser) parseBlockStmt() *ast.BlockStmt {
1055 if p.trace {
1056 defer un(trace(p, "BlockStmt"))
1057 }
1058
1059 lbrace := p.expect(token.LBRACE)
1060 p.openScope()
1061 list := p.parseStmtList()
1062 p.closeScope()
1063 rbrace := p.expect(token.RBRACE)
1064
1065 return &ast.BlockStmt{Lbrace: lbrace, List: list, Rbrace: rbrace}
1066 }
1067
1068
1069
1070
1071 func (p *parser) parseFuncTypeOrLit() ast.Expr {
1072 if p.trace {
1073 defer un(trace(p, "FuncTypeOrLit"))
1074 }
1075
1076 typ, scope := p.parseFuncType()
1077 if p.tok != token.LBRACE {
1078
1079 return typ
1080 }
1081
1082 p.exprLev++
1083 body := p.parseBody(scope)
1084 p.exprLev--
1085
1086 return &ast.FuncLit{Type: typ, Body: body}
1087 }
1088
1089
1090
1091
1092
1093 func (p *parser) parseOperand(lhs bool) ast.Expr {
1094 if p.trace {
1095 defer un(trace(p, "Operand"))
1096 }
1097
1098 switch p.tok {
1099 case token.IDENT:
1100 x := p.parseIdent()
1101 if !lhs {
1102 p.resolve(x)
1103 }
1104 return x
1105
1106 case token.INT, token.FLOAT, token.IMAG, token.CHAR, token.STRING:
1107 x := &ast.BasicLit{ValuePos: p.pos, Kind: p.tok, Value: p.lit}
1108 p.next()
1109 return x
1110
1111 case token.LPAREN:
1112 lparen := p.pos
1113 p.next()
1114 p.exprLev++
1115 x := p.parseRhsOrType()
1116 p.exprLev--
1117 rparen := p.expect(token.RPAREN)
1118 return &ast.ParenExpr{Lparen: lparen, X: x, Rparen: rparen}
1119
1120 case token.FUNC:
1121 return p.parseFuncTypeOrLit()
1122 }
1123
1124 if typ := p.tryIdentOrType(); typ != nil {
1125
1126 _, isIdent := typ.(*ast.Ident)
1127 assert(!isIdent, "type cannot be identifier")
1128 return typ
1129 }
1130
1131
1132 pos := p.pos
1133 p.errorExpected(pos, "operand")
1134 syncStmt(p)
1135 return &ast.BadExpr{From: pos, To: p.pos}
1136 }
1137
1138 func (p *parser) parseSelector(x ast.Expr) ast.Expr {
1139 if p.trace {
1140 defer un(trace(p, "Selector"))
1141 }
1142
1143 sel := p.parseIdent()
1144
1145 return &ast.SelectorExpr{X: x, Sel: sel}
1146 }
1147
1148 func (p *parser) parseTypeAssertion(x ast.Expr) ast.Expr {
1149 if p.trace {
1150 defer un(trace(p, "TypeAssertion"))
1151 }
1152
1153 p.expect(token.LPAREN)
1154 var typ ast.Expr
1155 if p.tok == token.TYPE {
1156
1157 p.next()
1158 } else {
1159 typ = p.parseType()
1160 }
1161 p.expect(token.RPAREN)
1162
1163 return &ast.TypeAssertExpr{X: x, Type: typ}
1164 }
1165
1166 func (p *parser) parseIndexOrSlice(x ast.Expr) ast.Expr {
1167 if p.trace {
1168 defer un(trace(p, "IndexOrSlice"))
1169 }
1170
1171 lbrack := p.expect(token.LBRACK)
1172 p.exprLev++
1173 var low, high ast.Expr
1174 isSlice := false
1175 if p.tok != token.COLON {
1176 low = p.parseRhs()
1177 }
1178 if p.tok == token.COLON {
1179 isSlice = true
1180 p.next()
1181 if p.tok != token.RBRACK {
1182 high = p.parseRhs()
1183 }
1184 }
1185 p.exprLev--
1186 rbrack := p.expect(token.RBRACK)
1187
1188 if isSlice {
1189 return &ast.SliceExpr{X: x, Lbrack: lbrack, Low: low, High: high, Rbrack: rbrack}
1190 }
1191 return &ast.IndexExpr{X: x, Lbrack: lbrack, Index: low, Rbrack: rbrack}
1192 }
1193
1194 func (p *parser) parseCallOrConversion(fun ast.Expr) *ast.CallExpr {
1195 if p.trace {
1196 defer un(trace(p, "CallOrConversion"))
1197 }
1198
1199 lparen := p.expect(token.LPAREN)
1200 p.exprLev++
1201 var list []ast.Expr
1202 var ellipsis token.Pos
1203 for p.tok != token.RPAREN && p.tok != token.EOF && !ellipsis.IsValid() {
1204 list = append(list, p.parseRhsOrType())
1205 if p.tok == token.ELLIPSIS {
1206 ellipsis = p.pos
1207 p.next()
1208 }
1209 if !p.atComma("argument list") {
1210 break
1211 }
1212 p.next()
1213 }
1214 p.exprLev--
1215 rparen := p.expectClosing(token.RPAREN, "argument list")
1216
1217 return &ast.CallExpr{Fun: fun, Lparen: lparen, Args: list, Ellipsis: ellipsis, Rparen: rparen}
1218 }
1219
1220 func (p *parser) parseElement(keyOk bool) ast.Expr {
1221 if p.trace {
1222 defer un(trace(p, "Element"))
1223 }
1224
1225 if p.tok == token.LBRACE {
1226 return p.parseLiteralValue(nil)
1227 }
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245 x := p.checkExpr(p.parseExpr(keyOk))
1246 if keyOk {
1247 if p.tok == token.COLON {
1248 colon := p.pos
1249 p.next()
1250
1251
1252
1253
1254 p.tryResolve(x, false)
1255 return &ast.KeyValueExpr{Key: x, Colon: colon, Value: p.parseElement(false)}
1256 }
1257 p.resolve(x)
1258 }
1259
1260 return x
1261 }
1262
1263 func (p *parser) parseElementList() (list []ast.Expr) {
1264 if p.trace {
1265 defer un(trace(p, "ElementList"))
1266 }
1267
1268 for p.tok != token.RBRACE && p.tok != token.EOF {
1269 list = append(list, p.parseElement(true))
1270 if !p.atComma("composite literal") {
1271 break
1272 }
1273 p.next()
1274 }
1275
1276 return
1277 }
1278
1279 func (p *parser) parseLiteralValue(typ ast.Expr) ast.Expr {
1280 if p.trace {
1281 defer un(trace(p, "LiteralValue"))
1282 }
1283
1284 lbrace := p.expect(token.LBRACE)
1285 var elts []ast.Expr
1286 p.exprLev++
1287 if p.tok != token.RBRACE {
1288 elts = p.parseElementList()
1289 }
1290 p.exprLev--
1291 rbrace := p.expectClosing(token.RBRACE, "composite literal")
1292 return &ast.CompositeLit{Type: typ, Lbrace: lbrace, Elts: elts, Rbrace: rbrace}
1293 }
1294
1295
1296 func (p *parser) checkExpr(x ast.Expr) ast.Expr {
1297 switch unparen(x).(type) {
1298 case *ast.BadExpr:
1299 case *ast.Ident:
1300 case *ast.BasicLit:
1301 case *ast.FuncLit:
1302 case *ast.CompositeLit:
1303 case *ast.ParenExpr:
1304 panic("unreachable")
1305 case *ast.SelectorExpr:
1306 case *ast.IndexExpr:
1307 case *ast.SliceExpr:
1308 case *ast.TypeAssertExpr:
1309
1310
1311
1312
1313
1314 case *ast.CallExpr:
1315 case *ast.StarExpr:
1316 case *ast.UnaryExpr:
1317 case *ast.BinaryExpr:
1318 default:
1319
1320 p.errorExpected(x.Pos(), "expression")
1321 x = &ast.BadExpr{From: x.Pos(), To: x.End()}
1322 }
1323 return x
1324 }
1325
1326
1327 func isTypeName(x ast.Expr) bool {
1328 switch t := x.(type) {
1329 case *ast.BadExpr:
1330 case *ast.Ident:
1331 case *ast.SelectorExpr:
1332 _, isIdent := t.X.(*ast.Ident)
1333 return isIdent
1334 default:
1335 return false
1336 }
1337 return true
1338 }
1339
1340
1341 func isLiteralType(x ast.Expr) bool {
1342 switch t := x.(type) {
1343 case *ast.BadExpr:
1344 case *ast.Ident:
1345 case *ast.SelectorExpr:
1346 _, isIdent := t.X.(*ast.Ident)
1347 return isIdent
1348 case *ast.ArrayType:
1349 case *ast.StructType:
1350 case *ast.MapType:
1351 default:
1352 return false
1353 }
1354 return true
1355 }
1356
1357
1358 func deref(x ast.Expr) ast.Expr {
1359 if p, isPtr := x.(*ast.StarExpr); isPtr {
1360 x = p.X
1361 }
1362 return x
1363 }
1364
1365
1366 func unparen(x ast.Expr) ast.Expr {
1367 if p, isParen := x.(*ast.ParenExpr); isParen {
1368 x = unparen(p.X)
1369 }
1370 return x
1371 }
1372
1373
1374
1375
1376 func (p *parser) checkExprOrType(x ast.Expr) ast.Expr {
1377 switch t := unparen(x).(type) {
1378 case *ast.ParenExpr:
1379 panic("unreachable")
1380 case *ast.UnaryExpr:
1381 case *ast.ArrayType:
1382 if len, isEllipsis := t.Len.(*ast.Ellipsis); isEllipsis {
1383 p.error(len.Pos(), "expected array length, found '...'")
1384 x = &ast.BadExpr{From: x.Pos(), To: x.End()}
1385 }
1386 }
1387
1388
1389 return x
1390 }
1391
1392
1393 func (p *parser) parsePrimaryExpr(lhs bool) ast.Expr {
1394 if p.trace {
1395 defer un(trace(p, "PrimaryExpr"))
1396 }
1397
1398 x := p.parseOperand(lhs)
1399 L:
1400 for {
1401 switch p.tok {
1402 case token.PERIOD:
1403 p.next()
1404 if lhs {
1405 p.resolve(x)
1406 }
1407 switch p.tok {
1408 case token.IDENT:
1409 x = p.parseSelector(p.checkExpr(x))
1410 case token.LPAREN:
1411 x = p.parseTypeAssertion(p.checkExpr(x))
1412 default:
1413 pos := p.pos
1414 p.errorExpected(pos, "selector or type assertion")
1415 p.next()
1416 x = &ast.BadExpr{From: pos, To: p.pos}
1417 }
1418 case token.LBRACK:
1419 if lhs {
1420 p.resolve(x)
1421 }
1422 x = p.parseIndexOrSlice(p.checkExpr(x))
1423 case token.LPAREN:
1424 if lhs {
1425 p.resolve(x)
1426 }
1427 x = p.parseCallOrConversion(p.checkExprOrType(x))
1428 case token.LBRACE:
1429 if isLiteralType(x) && (p.exprLev >= 0 || !isTypeName(x)) {
1430 if lhs {
1431 p.resolve(x)
1432 }
1433 x = p.parseLiteralValue(x)
1434 } else {
1435 break L
1436 }
1437 default:
1438 break L
1439 }
1440 lhs = false
1441 }
1442
1443 return x
1444 }
1445
1446
1447 func (p *parser) parseUnaryExpr(lhs bool) ast.Expr {
1448 if p.trace {
1449 defer un(trace(p, "UnaryExpr"))
1450 }
1451
1452 switch p.tok {
1453 case token.ADD, token.SUB, token.NOT, token.XOR, token.AND:
1454 pos, op := p.pos, p.tok
1455 p.next()
1456 x := p.parseUnaryExpr(false)
1457 return &ast.UnaryExpr{OpPos: pos, Op: op, X: p.checkExpr(x)}
1458
1459 case token.ARROW:
1460
1461 arrow := p.pos
1462 p.next()
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478 x := p.parseUnaryExpr(false)
1479
1480
1481 if typ, ok := x.(*ast.ChanType); ok {
1482
1483
1484
1485 dir := ast.SEND
1486 for ok && dir == ast.SEND {
1487 if typ.Dir == ast.RECV {
1488
1489 p.errorExpected(typ.Arrow, "'chan'")
1490 }
1491 arrow, typ.Begin, typ.Arrow = typ.Arrow, arrow, arrow
1492 dir, typ.Dir = typ.Dir, ast.RECV
1493 typ, ok = typ.Value.(*ast.ChanType)
1494 }
1495 if dir == ast.SEND {
1496 p.errorExpected(arrow, "channel type")
1497 }
1498
1499 return x
1500 }
1501
1502
1503 return &ast.UnaryExpr{OpPos: arrow, Op: token.ARROW, X: p.checkExpr(x)}
1504
1505 case token.MUL:
1506
1507 pos := p.pos
1508 p.next()
1509 x := p.parseUnaryExpr(false)
1510 return &ast.StarExpr{Star: pos, X: p.checkExprOrType(x)}
1511 }
1512
1513 return p.parsePrimaryExpr(lhs)
1514 }
1515
1516 func (p *parser) tokPrec() (token.Token, int) {
1517 tok := p.tok
1518 if p.inRhs && tok == token.ASSIGN {
1519 tok = token.EQL
1520 }
1521 return tok, tok.Precedence()
1522 }
1523
1524
1525 func (p *parser) parseBinaryExpr(lhs bool, prec1 int) ast.Expr {
1526 if p.trace {
1527 defer un(trace(p, "BinaryExpr"))
1528 }
1529
1530 x := p.parseUnaryExpr(lhs)
1531 for _, prec := p.tokPrec(); prec >= prec1; prec-- {
1532 for {
1533 op, oprec := p.tokPrec()
1534 if oprec != prec {
1535 break
1536 }
1537 pos := p.expect(op)
1538 if lhs {
1539 p.resolve(x)
1540 lhs = false
1541 }
1542 y := p.parseBinaryExpr(false, prec+1)
1543 x = &ast.BinaryExpr{X: p.checkExpr(x), OpPos: pos, Op: op, Y: p.checkExpr(y)}
1544 }
1545 }
1546
1547 return x
1548 }
1549
1550
1551
1552
1553
1554 func (p *parser) parseExpr(lhs bool) ast.Expr {
1555 if p.trace {
1556 defer un(trace(p, "Expression"))
1557 }
1558
1559 return p.parseBinaryExpr(lhs, token.LowestPrec+1)
1560 }
1561
1562 func (p *parser) parseRhs() ast.Expr {
1563 old := p.inRhs
1564 p.inRhs = true
1565 x := p.checkExpr(p.parseExpr(false))
1566 p.inRhs = old
1567 return x
1568 }
1569
1570 func (p *parser) parseRhsOrType() ast.Expr {
1571 old := p.inRhs
1572 p.inRhs = true
1573 x := p.checkExprOrType(p.parseExpr(false))
1574 p.inRhs = old
1575 return x
1576 }
1577
1578
1579
1580
1581
1582 const (
1583 basic = iota
1584 labelOk
1585 rangeOk
1586 )
1587
1588
1589
1590
1591
1592 func (p *parser) parseSimpleStmt(mode int) (ast.Stmt, bool) {
1593 if p.trace {
1594 defer un(trace(p, "SimpleStmt"))
1595 }
1596
1597 x := p.parseLhsList()
1598
1599 switch p.tok {
1600 case
1601 token.DEFINE, token.ASSIGN, token.ADD_ASSIGN,
1602 token.SUB_ASSIGN, token.MUL_ASSIGN, token.QUO_ASSIGN,
1603 token.REM_ASSIGN, token.AND_ASSIGN, token.OR_ASSIGN,
1604 token.XOR_ASSIGN, token.SHL_ASSIGN, token.SHR_ASSIGN, token.AND_NOT_ASSIGN:
1605
1606 pos, tok := p.pos, p.tok
1607 p.next()
1608 var y []ast.Expr
1609 isRange := false
1610 if mode == rangeOk && p.tok == token.RANGE && (tok == token.DEFINE || tok == token.ASSIGN) {
1611 pos := p.pos
1612 p.next()
1613 y = []ast.Expr{&ast.UnaryExpr{OpPos: pos, Op: token.RANGE, X: p.parseRhs()}}
1614 isRange = true
1615 } else {
1616 y = p.parseRhsList()
1617 }
1618 as := &ast.AssignStmt{Lhs: x, TokPos: pos, Tok: tok, Rhs: y}
1619 if tok == token.DEFINE {
1620 p.shortVarDecl(as, x)
1621 }
1622 return as, isRange
1623 }
1624
1625 if len(x) > 1 {
1626 p.errorExpected(x[0].Pos(), "1 expression")
1627
1628 }
1629
1630 switch p.tok {
1631 case token.COLON:
1632
1633 colon := p.pos
1634 p.next()
1635 if label, isIdent := x[0].(*ast.Ident); mode == labelOk && isIdent {
1636
1637
1638
1639 stmt := &ast.LabeledStmt{Label: label, Colon: colon, Stmt: p.parseStmt()}
1640 p.declare(stmt, nil, p.labelScope, ast.Lbl, label)
1641 return stmt, false
1642 }
1643
1644
1645
1646
1647
1648
1649 p.error(colon, "illegal label declaration")
1650 return &ast.BadStmt{From: x[0].Pos(), To: colon + 1}, false
1651
1652 case token.ARROW:
1653
1654 arrow := p.pos
1655 p.next()
1656 y := p.parseRhs()
1657 return &ast.SendStmt{Chan: x[0], Arrow: arrow, Value: y}, false
1658
1659 case token.INC, token.DEC:
1660
1661 s := &ast.IncDecStmt{X: x[0], TokPos: p.pos, Tok: p.tok}
1662 p.next()
1663 return s, false
1664 }
1665
1666
1667 return &ast.ExprStmt{X: x[0]}, false
1668 }
1669
1670 func (p *parser) parseCallExpr() *ast.CallExpr {
1671 x := p.parseRhsOrType()
1672 if call, isCall := x.(*ast.CallExpr); isCall {
1673 return call
1674 }
1675 if _, isBad := x.(*ast.BadExpr); !isBad {
1676
1677 p.errorExpected(x.Pos(), "function/method call")
1678 }
1679 return nil
1680 }
1681
1682 func (p *parser) parseGoStmt() ast.Stmt {
1683 if p.trace {
1684 defer un(trace(p, "GoStmt"))
1685 }
1686
1687 pos := p.expect(token.GO)
1688 call := p.parseCallExpr()
1689 p.expectSemi()
1690 if call == nil {
1691 return &ast.BadStmt{From: pos, To: pos + 2}
1692 }
1693
1694 return &ast.GoStmt{Go: pos, Call: call}
1695 }
1696
1697 func (p *parser) parseDeferStmt() ast.Stmt {
1698 if p.trace {
1699 defer un(trace(p, "DeferStmt"))
1700 }
1701
1702 pos := p.expect(token.DEFER)
1703 call := p.parseCallExpr()
1704 p.expectSemi()
1705 if call == nil {
1706 return &ast.BadStmt{From: pos, To: pos + 5}
1707 }
1708
1709 return &ast.DeferStmt{Defer: pos, Call: call}
1710 }
1711
1712 func (p *parser) parseReturnStmt() *ast.ReturnStmt {
1713 if p.trace {
1714 defer un(trace(p, "ReturnStmt"))
1715 }
1716
1717 pos := p.pos
1718 p.expect(token.RETURN)
1719 var x []ast.Expr
1720 if p.tok != token.SEMICOLON && p.tok != token.RBRACE {
1721 x = p.parseRhsList()
1722 }
1723 p.expectSemi()
1724
1725 return &ast.ReturnStmt{Return: pos, Results: x}
1726 }
1727
1728 func (p *parser) parseBranchStmt(tok token.Token) *ast.BranchStmt {
1729 if p.trace {
1730 defer un(trace(p, "BranchStmt"))
1731 }
1732
1733 pos := p.expect(tok)
1734 var label *ast.Ident
1735 if tok != token.FALLTHROUGH && p.tok == token.IDENT {
1736 label = p.parseIdent()
1737
1738 n := len(p.targetStack) - 1
1739 p.targetStack[n] = append(p.targetStack[n], label)
1740 }
1741 p.expectSemi()
1742
1743 return &ast.BranchStmt{TokPos: pos, Tok: tok, Label: label}
1744 }
1745
1746 func (p *parser) makeExpr(s ast.Stmt) ast.Expr {
1747 if s == nil {
1748 return nil
1749 }
1750 if es, isExpr := s.(*ast.ExprStmt); isExpr {
1751 return p.checkExpr(es.X)
1752 }
1753 p.error(s.Pos(), "expected condition, found simple statement")
1754 return &ast.BadExpr{From: s.Pos(), To: s.End()}
1755 }
1756
1757 func (p *parser) parseIfStmt() *ast.IfStmt {
1758 if p.trace {
1759 defer un(trace(p, "IfStmt"))
1760 }
1761
1762 pos := p.expect(token.IF)
1763 p.openScope()
1764 defer p.closeScope()
1765
1766 var s ast.Stmt
1767 var x ast.Expr
1768 {
1769 prevLev := p.exprLev
1770 p.exprLev = -1
1771 if p.tok == token.SEMICOLON {
1772 p.next()
1773 x = p.parseRhs()
1774 } else {
1775 s, _ = p.parseSimpleStmt(basic)
1776 if p.tok == token.SEMICOLON {
1777 p.next()
1778 x = p.parseRhs()
1779 } else {
1780 x = p.makeExpr(s)
1781 s = nil
1782 }
1783 }
1784 p.exprLev = prevLev
1785 }
1786
1787 body := p.parseBlockStmt()
1788 var else_ ast.Stmt
1789 if p.tok == token.ELSE {
1790 p.next()
1791 else_ = p.parseStmt()
1792 } else {
1793 p.expectSemi()
1794 }
1795
1796 return &ast.IfStmt{If: pos, Init: s, Cond: x, Body: body, Else: else_}
1797 }
1798
1799 func (p *parser) parseTypeList() (list []ast.Expr) {
1800 if p.trace {
1801 defer un(trace(p, "TypeList"))
1802 }
1803
1804 list = append(list, p.parseType())
1805 for p.tok == token.COMMA {
1806 p.next()
1807 list = append(list, p.parseType())
1808 }
1809
1810 return
1811 }
1812
1813 func (p *parser) parseCaseClause(typeSwitch bool) *ast.CaseClause {
1814 if p.trace {
1815 defer un(trace(p, "CaseClause"))
1816 }
1817
1818 pos := p.pos
1819 var list []ast.Expr
1820 if p.tok == token.CASE {
1821 p.next()
1822 if typeSwitch {
1823 list = p.parseTypeList()
1824 } else {
1825 list = p.parseRhsList()
1826 }
1827 } else {
1828 p.expect(token.DEFAULT)
1829 }
1830
1831 colon := p.expect(token.COLON)
1832 p.openScope()
1833 body := p.parseStmtList()
1834 p.closeScope()
1835
1836 return &ast.CaseClause{Case: pos, List: list, Colon: colon, Body: body}
1837 }
1838
1839 func isTypeSwitchAssert(x ast.Expr) bool {
1840 a, ok := x.(*ast.TypeAssertExpr)
1841 return ok && a.Type == nil
1842 }
1843
1844 func isTypeSwitchGuard(s ast.Stmt) bool {
1845 switch t := s.(type) {
1846 case *ast.ExprStmt:
1847
1848 return isTypeSwitchAssert(t.X)
1849 case *ast.AssignStmt:
1850
1851 return len(t.Lhs) == 1 && t.Tok == token.DEFINE && len(t.Rhs) == 1 && isTypeSwitchAssert(t.Rhs[0])
1852 }
1853 return false
1854 }
1855
1856 func (p *parser) parseSwitchStmt() ast.Stmt {
1857 if p.trace {
1858 defer un(trace(p, "SwitchStmt"))
1859 }
1860
1861 pos := p.expect(token.SWITCH)
1862 p.openScope()
1863 defer p.closeScope()
1864
1865 var s1, s2 ast.Stmt
1866 if p.tok != token.LBRACE {
1867 prevLev := p.exprLev
1868 p.exprLev = -1
1869 if p.tok != token.SEMICOLON {
1870 s2, _ = p.parseSimpleStmt(basic)
1871 }
1872 if p.tok == token.SEMICOLON {
1873 p.next()
1874 s1 = s2
1875 s2 = nil
1876 if p.tok != token.LBRACE {
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889 p.openScope()
1890 defer p.closeScope()
1891 s2, _ = p.parseSimpleStmt(basic)
1892 }
1893 }
1894 p.exprLev = prevLev
1895 }
1896
1897 typeSwitch := isTypeSwitchGuard(s2)
1898 lbrace := p.expect(token.LBRACE)
1899 var list []ast.Stmt
1900 for p.tok == token.CASE || p.tok == token.DEFAULT {
1901 list = append(list, p.parseCaseClause(typeSwitch))
1902 }
1903 rbrace := p.expect(token.RBRACE)
1904 p.expectSemi()
1905 body := &ast.BlockStmt{Lbrace: lbrace, List: list, Rbrace: rbrace}
1906
1907 if typeSwitch {
1908 return &ast.TypeSwitchStmt{Switch: pos, Init: s1, Assign: s2, Body: body}
1909 }
1910
1911 return &ast.SwitchStmt{Switch: pos, Init: s1, Tag: p.makeExpr(s2), Body: body}
1912 }
1913
1914 func (p *parser) parseCommClause() *ast.CommClause {
1915 if p.trace {
1916 defer un(trace(p, "CommClause"))
1917 }
1918
1919 p.openScope()
1920 pos := p.pos
1921 var comm ast.Stmt
1922 if p.tok == token.CASE {
1923 p.next()
1924 lhs := p.parseLhsList()
1925 if p.tok == token.ARROW {
1926
1927 if len(lhs) > 1 {
1928 p.errorExpected(lhs[0].Pos(), "1 expression")
1929
1930 }
1931 arrow := p.pos
1932 p.next()
1933 rhs := p.parseRhs()
1934 comm = &ast.SendStmt{Chan: lhs[0], Arrow: arrow, Value: rhs}
1935 } else {
1936
1937 if tok := p.tok; tok == token.ASSIGN || tok == token.DEFINE {
1938
1939 if len(lhs) > 2 {
1940 p.errorExpected(lhs[0].Pos(), "1 or 2 expressions")
1941
1942 lhs = lhs[0:2]
1943 }
1944 pos := p.pos
1945 p.next()
1946 rhs := p.parseRhs()
1947 as := &ast.AssignStmt{Lhs: lhs, TokPos: pos, Tok: tok, Rhs: []ast.Expr{rhs}}
1948 if tok == token.DEFINE {
1949 p.shortVarDecl(as, lhs)
1950 }
1951 comm = as
1952 } else {
1953
1954 if len(lhs) > 1 {
1955 p.errorExpected(lhs[0].Pos(), "1 expression")
1956
1957 }
1958 comm = &ast.ExprStmt{X: lhs[0]}
1959 }
1960 }
1961 } else {
1962 p.expect(token.DEFAULT)
1963 }
1964
1965 colon := p.expect(token.COLON)
1966 body := p.parseStmtList()
1967 p.closeScope()
1968
1969 return &ast.CommClause{Case: pos, Comm: comm, Colon: colon, Body: body}
1970 }
1971
1972 func (p *parser) parseSelectStmt() *ast.SelectStmt {
1973 if p.trace {
1974 defer un(trace(p, "SelectStmt"))
1975 }
1976
1977 pos := p.expect(token.SELECT)
1978 lbrace := p.expect(token.LBRACE)
1979 var list []ast.Stmt
1980 for p.tok == token.CASE || p.tok == token.DEFAULT {
1981 list = append(list, p.parseCommClause())
1982 }
1983 rbrace := p.expect(token.RBRACE)
1984 p.expectSemi()
1985 body := &ast.BlockStmt{Lbrace: lbrace, List: list, Rbrace: rbrace}
1986
1987 return &ast.SelectStmt{Select: pos, Body: body}
1988 }
1989
1990 func (p *parser) parseForStmt() ast.Stmt {
1991 if p.trace {
1992 defer un(trace(p, "ForStmt"))
1993 }
1994
1995 pos := p.expect(token.FOR)
1996 p.openScope()
1997 defer p.closeScope()
1998
1999 var s1, s2, s3 ast.Stmt
2000 var isRange bool
2001 if p.tok != token.LBRACE {
2002 prevLev := p.exprLev
2003 p.exprLev = -1
2004 if p.tok != token.SEMICOLON {
2005 s2, isRange = p.parseSimpleStmt(rangeOk)
2006 }
2007 if !isRange && p.tok == token.SEMICOLON {
2008 p.next()
2009 s1 = s2
2010 s2 = nil
2011 if p.tok != token.SEMICOLON {
2012 s2, _ = p.parseSimpleStmt(basic)
2013 }
2014 p.expectSemi()
2015 if p.tok != token.LBRACE {
2016 s3, _ = p.parseSimpleStmt(basic)
2017 }
2018 }
2019 p.exprLev = prevLev
2020 }
2021
2022 body := p.parseBlockStmt()
2023 p.expectSemi()
2024
2025 if isRange {
2026 as := s2.(*ast.AssignStmt)
2027
2028 var key, value ast.Expr
2029 switch len(as.Lhs) {
2030 case 2:
2031 key, value = as.Lhs[0], as.Lhs[1]
2032 case 1:
2033 key = as.Lhs[0]
2034 default:
2035 p.errorExpected(as.Lhs[0].Pos(), "1 or 2 expressions")
2036 return &ast.BadStmt{From: pos, To: body.End()}
2037 }
2038
2039
2040 x := as.Rhs[0].(*ast.UnaryExpr).X
2041 return &ast.RangeStmt{
2042 For: pos,
2043 Key: key,
2044 Value: value,
2045 TokPos: as.TokPos,
2046 Tok: as.Tok,
2047 X: x,
2048 Body: body,
2049 }
2050 }
2051
2052
2053 return &ast.ForStmt{
2054 For: pos,
2055 Init: s1,
2056 Cond: p.makeExpr(s2),
2057 Post: s3,
2058 Body: body,
2059 }
2060 }
2061
2062 func (p *parser) parseStmt() (s ast.Stmt) {
2063 if p.trace {
2064 defer un(trace(p, "Statement"))
2065 }
2066
2067 switch p.tok {
2068 case token.CONST, token.TYPE, token.VAR:
2069 s = &ast.DeclStmt{Decl: p.parseDecl(syncStmt)}
2070 case
2071
2072 token.IDENT, token.INT, token.FLOAT, token.IMAG, token.CHAR, token.STRING, token.FUNC, token.LPAREN,
2073 token.LBRACK, token.STRUCT,
2074 token.ADD, token.SUB, token.MUL, token.AND, token.XOR, token.ARROW, token.NOT:
2075 s, _ = p.parseSimpleStmt(labelOk)
2076
2077
2078
2079 if _, isLabeledStmt := s.(*ast.LabeledStmt); !isLabeledStmt {
2080 p.expectSemi()
2081 }
2082 case token.GO:
2083 s = p.parseGoStmt()
2084 case token.DEFER:
2085 s = p.parseDeferStmt()
2086 case token.RETURN:
2087 s = p.parseReturnStmt()
2088 case token.BREAK, token.CONTINUE, token.GOTO, token.FALLTHROUGH:
2089 s = p.parseBranchStmt(p.tok)
2090 case token.LBRACE:
2091 s = p.parseBlockStmt()
2092 p.expectSemi()
2093 case token.IF:
2094 s = p.parseIfStmt()
2095 case token.SWITCH:
2096 s = p.parseSwitchStmt()
2097 case token.SELECT:
2098 s = p.parseSelectStmt()
2099 case token.FOR:
2100 s = p.parseForStmt()
2101 case token.SEMICOLON:
2102 s = &ast.EmptyStmt{Semicolon: p.pos}
2103 p.next()
2104 case token.RBRACE:
2105
2106 s = &ast.EmptyStmt{Semicolon: p.pos}
2107 default:
2108
2109 pos := p.pos
2110 p.errorExpected(pos, "statement")
2111 syncStmt(p)
2112 s = &ast.BadStmt{From: pos, To: p.pos}
2113 }
2114
2115 return
2116 }
2117
2118
2119
2120
2121 type parseSpecFunction func(doc *ast.CommentGroup, keyword token.Token, iota int) ast.Spec
2122
2123 func isValidImport(lit string) bool {
2124 const illegalChars = `!"#$%&'()*,:;<=>?[\]^{|}` + "`\uFFFD"
2125 s, _ := strconv.Unquote(lit)
2126 for _, r := range s {
2127 if !unicode.IsGraphic(r) || unicode.IsSpace(r) || strings.ContainsRune(illegalChars, r) {
2128 return false
2129 }
2130 }
2131 return s != ""
2132 }
2133
2134 func (p *parser) parseImportSpec(doc *ast.CommentGroup, _ token.Token, _ int) ast.Spec {
2135 if p.trace {
2136 defer un(trace(p, "ImportSpec"))
2137 }
2138
2139 var ident *ast.Ident
2140 switch p.tok {
2141 case token.PERIOD:
2142 ident = &ast.Ident{NamePos: p.pos, Name: "."}
2143 p.next()
2144 case token.IDENT:
2145 ident = p.parseIdent()
2146 }
2147
2148 var path *ast.BasicLit
2149 if p.tok == token.STRING {
2150 if !isValidImport(p.lit) {
2151 p.error(p.pos, "invalid import path: "+p.lit)
2152 }
2153 path = &ast.BasicLit{ValuePos: p.pos, Kind: p.tok, Value: p.lit}
2154 p.next()
2155 } else {
2156 p.expect(token.STRING)
2157 }
2158 p.expectSemi()
2159
2160
2161 spec := &ast.ImportSpec{
2162 Doc: doc,
2163 Name: ident,
2164 Path: path,
2165 Comment: p.lineComment,
2166 }
2167 p.imports = append(p.imports, spec)
2168
2169 return spec
2170 }
2171
2172 func (p *parser) parseValueSpec(doc *ast.CommentGroup, keyword token.Token, iota int) ast.Spec {
2173 if p.trace {
2174 defer un(trace(p, keyword.String()+"Spec"))
2175 }
2176
2177 idents := p.parseIdentList()
2178 typ := p.tryType()
2179 var values []ast.Expr
2180 if p.tok == token.ASSIGN || keyword == token.CONST && (typ != nil || iota == 0) || keyword == token.VAR && typ == nil {
2181 p.expect(token.ASSIGN)
2182 values = p.parseRhsList()
2183 }
2184 p.expectSemi()
2185
2186
2187
2188
2189
2190 spec := &ast.ValueSpec{
2191 Doc: doc,
2192 Names: idents,
2193 Type: typ,
2194 Values: values,
2195 Comment: p.lineComment,
2196 }
2197 kind := ast.Con
2198 if keyword == token.VAR {
2199 kind = ast.Var
2200 }
2201 p.declare(spec, iota, p.topScope, kind, idents...)
2202
2203 return spec
2204 }
2205
2206 func (p *parser) parseTypeSpec(doc *ast.CommentGroup, _ token.Token, _ int) ast.Spec {
2207 if p.trace {
2208 defer un(trace(p, "TypeSpec"))
2209 }
2210
2211 ident := p.parseIdent()
2212
2213
2214
2215
2216
2217 spec := &ast.TypeSpec{Doc: doc, Name: ident}
2218 p.declare(spec, nil, p.topScope, ast.Typ, ident)
2219
2220 spec.Type = p.parseType()
2221 p.expectSemi()
2222 spec.Comment = p.lineComment
2223
2224 return spec
2225 }
2226
2227 func (p *parser) parseGenDecl(keyword token.Token, f parseSpecFunction) *ast.GenDecl {
2228 if p.trace {
2229 defer un(trace(p, "GenDecl("+keyword.String()+")"))
2230 }
2231
2232 doc := p.leadComment
2233 pos := p.expect(keyword)
2234 var lparen, rparen token.Pos
2235 var list []ast.Spec
2236 if p.tok == token.LPAREN {
2237 lparen = p.pos
2238 p.next()
2239 for iota := 0; p.tok != token.RPAREN && p.tok != token.EOF; iota++ {
2240 list = append(list, f(p.leadComment, keyword, iota))
2241 }
2242 rparen = p.expect(token.RPAREN)
2243 p.expectSemi()
2244 } else {
2245 list = append(list, f(nil, keyword, 0))
2246 }
2247
2248 return &ast.GenDecl{
2249 Doc: doc,
2250 TokPos: pos,
2251 Tok: keyword,
2252 Lparen: lparen,
2253 Specs: list,
2254 Rparen: rparen,
2255 }
2256 }
2257
2258 func (p *parser) parseReceiver(scope *ast.Scope) *ast.FieldList {
2259 if p.trace {
2260 defer un(trace(p, "Receiver"))
2261 }
2262
2263 par := p.parseParameters(scope, false)
2264
2265
2266 if par.NumFields() != 1 {
2267 p.errorExpected(par.Opening, "exactly one receiver")
2268 par.List = []*ast.Field{{Type: &ast.BadExpr{From: par.Opening, To: par.Closing + 1}}}
2269 return par
2270 }
2271
2272
2273 recv := par.List[0]
2274 base := deref(recv.Type)
2275 if _, isIdent := base.(*ast.Ident); !isIdent {
2276 if _, isBad := base.(*ast.BadExpr); !isBad {
2277
2278 p.errorExpected(base.Pos(), "(unqualified) identifier")
2279 }
2280 par.List = []*ast.Field{
2281 {Type: &ast.BadExpr{From: recv.Pos(), To: recv.End()}},
2282 }
2283 }
2284
2285 return par
2286 }
2287
2288 func (p *parser) parseFuncDecl() *ast.FuncDecl {
2289 if p.trace {
2290 defer un(trace(p, "FunctionDecl"))
2291 }
2292
2293 doc := p.leadComment
2294 pos := p.expect(token.FUNC)
2295 scope := ast.NewScope(p.topScope)
2296
2297 var recv *ast.FieldList
2298 if p.tok == token.LPAREN {
2299 recv = p.parseReceiver(scope)
2300 }
2301
2302 ident := p.parseIdent()
2303
2304 params, results := p.parseSignature(scope)
2305
2306 var body *ast.BlockStmt
2307 if p.tok == token.LBRACE {
2308 body = p.parseBody(scope)
2309 }
2310 p.expectSemi()
2311
2312 decl := &ast.FuncDecl{
2313 Doc: doc,
2314 Recv: recv,
2315 Name: ident,
2316 Type: &ast.FuncType{
2317 Func: pos,
2318 Params: params,
2319 Results: results,
2320 },
2321 Body: body,
2322 }
2323 if recv == nil {
2324
2325
2326
2327
2328
2329
2330 if ident.Name != "init" {
2331 p.declare(decl, nil, p.pkgScope, ast.Fun, ident)
2332 }
2333 }
2334
2335 return decl
2336 }
2337
2338 func (p *parser) parseDecl(sync func(*parser)) ast.Decl {
2339 if p.trace {
2340 defer un(trace(p, "Declaration"))
2341 }
2342
2343 var f parseSpecFunction
2344 switch p.tok {
2345 case token.CONST, token.VAR:
2346 f = p.parseValueSpec
2347
2348 case token.TYPE:
2349 f = p.parseTypeSpec
2350
2351 case token.FUNC:
2352 return p.parseFuncDecl()
2353
2354 default:
2355 pos := p.pos
2356 p.errorExpected(pos, "declaration")
2357 sync(p)
2358 return &ast.BadDecl{From: pos, To: p.pos}
2359 }
2360
2361 return p.parseGenDecl(p.tok, f)
2362 }
2363
2364
2365
2366
2367 func (p *parser) parseFile() *ast.File {
2368 if p.trace {
2369 defer un(trace(p, "File"))
2370 }
2371
2372
2373
2374 if p.errors.Len() != 0 {
2375 return nil
2376 }
2377
2378
2379 doc := p.leadComment
2380 pos := p.expect(token.PACKAGE)
2381
2382
2383 ident := p.parseIdent()
2384 if ident.Name == "_" {
2385 p.error(p.pos, "invalid package name _")
2386 }
2387 p.expectSemi()
2388
2389
2390
2391 if p.errors.Len() != 0 {
2392 return nil
2393 }
2394
2395 p.openScope()
2396 p.pkgScope = p.topScope
2397 var decls []ast.Decl
2398 if p.mode&PackageClauseOnly == 0 {
2399
2400 for p.tok == token.IMPORT {
2401 decls = append(decls, p.parseGenDecl(token.IMPORT, p.parseImportSpec))
2402 }
2403
2404 if p.mode&ImportsOnly == 0 {
2405
2406 for p.tok != token.EOF {
2407 decls = append(decls, p.parseDecl(syncDecl))
2408 }
2409 }
2410 }
2411 p.closeScope()
2412 assert(p.topScope == nil, "unbalanced scopes")
2413 assert(p.labelScope == nil, "unbalanced label scopes")
2414
2415
2416 i := 0
2417 for _, ident := range p.unresolved {
2418
2419 assert(ident.Obj == unresolved, "object already resolved")
2420 ident.Obj = p.pkgScope.Lookup(ident.Name)
2421 if ident.Obj == nil {
2422 p.unresolved[i] = ident
2423 i++
2424 }
2425 }
2426
2427 return &ast.File{
2428 Doc: doc,
2429 Package: pos,
2430 Name: ident,
2431 Decls: decls,
2432 Scope: p.pkgScope,
2433 Imports: p.imports,
2434 Unresolved: p.unresolved[0:i],
2435 Comments: p.comments,
2436 }
2437 }
View as plain text