f1746e04055060dad812c2cc839e433b5791178e
[platform/upstream/gcc.git] / libgo / go / go / parser / parser.go
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // A parser for Go source files. Input may be provided in a variety of
6 // forms (see the various Parse* functions); the output is an abstract
7 // syntax tree (AST) representing the Go source. The parser is invoked
8 // through one of the Parse* functions.
9 //
10 package parser
11
12 import (
13         "fmt"
14         "go/ast"
15         "go/scanner"
16         "go/token"
17 )
18
19
20 // noPos is used when there is no corresponding source position for a token.
21 var noPos token.Position
22
23
24 // The mode parameter to the Parse* functions is a set of flags (or 0).
25 // They control the amount of source code parsed and other optional
26 // parser functionality.
27 //
28 const (
29         PackageClauseOnly uint = 1 << iota // parsing stops after package clause
30         ImportsOnly                        // parsing stops after import declarations
31         ParseComments                      // parse comments and add them to AST
32         Trace                              // print a trace of parsed productions
33 )
34
35
36 // The parser structure holds the parser's internal state.
37 type parser struct {
38         file *token.File
39         scanner.ErrorVector
40         scanner scanner.Scanner
41
42         // Tracing/debugging
43         mode   uint // parsing mode
44         trace  bool // == (mode & Trace != 0)
45         indent uint // indentation used for tracing output
46
47         // Comments
48         comments    []*ast.CommentGroup
49         leadComment *ast.CommentGroup // the last lead comment
50         lineComment *ast.CommentGroup // the last line comment
51
52         // Next token
53         pos token.Pos   // token position
54         tok token.Token // one token look-ahead
55         lit []byte      // token literal
56
57         // Non-syntactic parser control
58         exprLev int // < 0: in control clause, >= 0: in expression
59 }
60
61
62 // scannerMode returns the scanner mode bits given the parser's mode bits.
63 func scannerMode(mode uint) uint {
64         var m uint = scanner.InsertSemis
65         if mode&ParseComments != 0 {
66                 m |= scanner.ScanComments
67         }
68         return m
69 }
70
71
72 func (p *parser) init(fset *token.FileSet, filename string, src []byte, mode uint) {
73         p.file = fset.AddFile(filename, fset.Base(), len(src))
74         p.scanner.Init(p.file, src, p, scannerMode(mode))
75         p.mode = mode
76         p.trace = mode&Trace != 0 // for convenience (p.trace is used frequently)
77         p.next()
78 }
79
80
81 // ----------------------------------------------------------------------------
82 // Parsing support
83
84 func (p *parser) printTrace(a ...interface{}) {
85         const dots = ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . " +
86                 ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
87         const n = uint(len(dots))
88         pos := p.file.Position(p.pos)
89         fmt.Printf("%5d:%3d: ", pos.Line, pos.Column)
90         i := 2 * p.indent
91         for ; i > n; i -= n {
92                 fmt.Print(dots)
93         }
94         fmt.Print(dots[0:i])
95         fmt.Println(a...)
96 }
97
98
99 func trace(p *parser, msg string) *parser {
100         p.printTrace(msg, "(")
101         p.indent++
102         return p
103 }
104
105
106 // Usage pattern: defer un(trace(p, "..."));
107 func un(p *parser) {
108         p.indent--
109         p.printTrace(")")
110 }
111
112
113 // Advance to the next token.
114 func (p *parser) next0() {
115         // Because of one-token look-ahead, print the previous token
116         // when tracing as it provides a more readable output. The
117         // very first token (!p.pos.IsValid()) is not initialized
118         // (it is token.ILLEGAL), so don't print it .
119         if p.trace && p.pos.IsValid() {
120                 s := p.tok.String()
121                 switch {
122                 case p.tok.IsLiteral():
123                         p.printTrace(s, string(p.lit))
124                 case p.tok.IsOperator(), p.tok.IsKeyword():
125                         p.printTrace("\"" + s + "\"")
126                 default:
127                         p.printTrace(s)
128                 }
129         }
130
131         p.pos, p.tok, p.lit = p.scanner.Scan()
132 }
133
134 // Consume a comment and return it and the line on which it ends.
135 func (p *parser) consumeComment() (comment *ast.Comment, endline int) {
136         // /*-style comments may end on a different line than where they start.
137         // Scan the comment for '\n' chars and adjust endline accordingly.
138         endline = p.file.Line(p.pos)
139         if p.lit[1] == '*' {
140                 for _, b := range p.lit {
141                         if b == '\n' {
142                                 endline++
143                         }
144                 }
145         }
146
147         comment = &ast.Comment{p.pos, p.lit}
148         p.next0()
149
150         return
151 }
152
153
154 // Consume a group of adjacent comments, add it to the parser's
155 // comments list, and return it together with the line at which
156 // the last comment in the group ends. An empty line or non-comment
157 // token terminates a comment group.
158 //
159 func (p *parser) consumeCommentGroup() (comments *ast.CommentGroup, endline int) {
160         var list []*ast.Comment
161         endline = p.file.Line(p.pos)
162         for p.tok == token.COMMENT && endline+1 >= p.file.Line(p.pos) {
163                 var comment *ast.Comment
164                 comment, endline = p.consumeComment()
165                 list = append(list, comment)
166         }
167
168         // add comment group to the comments list
169         comments = &ast.CommentGroup{list}
170         p.comments = append(p.comments, comments)
171
172         return
173 }
174
175
176 // Advance to the next non-comment token. In the process, collect
177 // any comment groups encountered, and remember the last lead and
178 // and line comments.
179 //
180 // A lead comment is a comment group that starts and ends in a
181 // line without any other tokens and that is followed by a non-comment
182 // token on the line immediately after the comment group.
183 //
184 // A line comment is a comment group that follows a non-comment
185 // token on the same line, and that has no tokens after it on the line
186 // where it ends.
187 //
188 // Lead and line comments may be considered documentation that is
189 // stored in the AST.
190 //
191 func (p *parser) next() {
192         p.leadComment = nil
193         p.lineComment = nil
194         line := p.file.Line(p.pos) // current line
195         p.next0()
196
197         if p.tok == token.COMMENT {
198                 var comment *ast.CommentGroup
199                 var endline int
200
201                 if p.file.Line(p.pos) == line {
202                         // The comment is on same line as previous token; it
203                         // cannot be a lead comment but may be a line comment.
204                         comment, endline = p.consumeCommentGroup()
205                         if p.file.Line(p.pos) != endline {
206                                 // The next token is on a different line, thus
207                                 // the last comment group is a line comment.
208                                 p.lineComment = comment
209                         }
210                 }
211
212                 // consume successor comments, if any
213                 endline = -1
214                 for p.tok == token.COMMENT {
215                         comment, endline = p.consumeCommentGroup()
216                 }
217
218                 if endline+1 == p.file.Line(p.pos) {
219                         // The next token is following on the line immediately after the
220                         // comment group, thus the last comment group is a lead comment.
221                         p.leadComment = comment
222                 }
223         }
224 }
225
226
227 func (p *parser) error(pos token.Pos, msg string) {
228         p.Error(p.file.Position(pos), msg)
229 }
230
231
232 func (p *parser) errorExpected(pos token.Pos, msg string) {
233         msg = "expected " + msg
234         if pos == p.pos {
235                 // the error happened at the current position;
236                 // make the error message more specific
237                 if p.tok == token.SEMICOLON && p.lit[0] == '\n' {
238                         msg += ", found newline"
239                 } else {
240                         msg += ", found '" + p.tok.String() + "'"
241                         if p.tok.IsLiteral() {
242                                 msg += " " + string(p.lit)
243                         }
244                 }
245         }
246         p.error(pos, msg)
247 }
248
249
250 func (p *parser) expect(tok token.Token) token.Pos {
251         pos := p.pos
252         if p.tok != tok {
253                 p.errorExpected(pos, "'"+tok.String()+"'")
254         }
255         p.next() // make progress
256         return pos
257 }
258
259
260 func (p *parser) expectSemi() {
261         if p.tok != token.RPAREN && p.tok != token.RBRACE {
262                 p.expect(token.SEMICOLON)
263         }
264 }
265
266
267 // ----------------------------------------------------------------------------
268 // Identifiers
269
270 func (p *parser) parseIdent() *ast.Ident {
271         pos := p.pos
272         name := "_"
273         if p.tok == token.IDENT {
274                 name = string(p.lit)
275                 p.next()
276         } else {
277                 p.expect(token.IDENT) // use expect() error handling
278         }
279         return &ast.Ident{pos, name, nil}
280 }
281
282
283 func (p *parser) parseIdentList() (list []*ast.Ident) {
284         if p.trace {
285                 defer un(trace(p, "IdentList"))
286         }
287
288         list = append(list, p.parseIdent())
289         for p.tok == token.COMMA {
290                 p.next()
291                 list = append(list, p.parseIdent())
292         }
293
294         return
295 }
296
297
298 // ----------------------------------------------------------------------------
299 // Common productions
300
301 func (p *parser) parseExprList() (list []ast.Expr) {
302         if p.trace {
303                 defer un(trace(p, "ExpressionList"))
304         }
305
306         list = append(list, p.parseExpr())
307         for p.tok == token.COMMA {
308                 p.next()
309                 list = append(list, p.parseExpr())
310         }
311
312         return
313 }
314
315
316 // ----------------------------------------------------------------------------
317 // Types
318
319 func (p *parser) parseType() ast.Expr {
320         if p.trace {
321                 defer un(trace(p, "Type"))
322         }
323
324         typ := p.tryType()
325
326         if typ == nil {
327                 pos := p.pos
328                 p.errorExpected(pos, "type")
329                 p.next() // make progress
330                 return &ast.BadExpr{pos, p.pos}
331         }
332
333         return typ
334 }
335
336
337 func (p *parser) parseQualifiedIdent() ast.Expr {
338         if p.trace {
339                 defer un(trace(p, "QualifiedIdent"))
340         }
341
342         var x ast.Expr = p.parseIdent()
343         if p.tok == token.PERIOD {
344                 // first identifier is a package identifier
345                 p.next()
346                 sel := p.parseIdent()
347                 x = &ast.SelectorExpr{x, sel}
348         }
349         return x
350 }
351
352
353 func (p *parser) parseTypeName() ast.Expr {
354         if p.trace {
355                 defer un(trace(p, "TypeName"))
356         }
357
358         return p.parseQualifiedIdent()
359 }
360
361
362 func (p *parser) parseArrayType(ellipsisOk bool) ast.Expr {
363         if p.trace {
364                 defer un(trace(p, "ArrayType"))
365         }
366
367         lbrack := p.expect(token.LBRACK)
368         var len ast.Expr
369         if ellipsisOk && p.tok == token.ELLIPSIS {
370                 len = &ast.Ellipsis{p.pos, nil}
371                 p.next()
372         } else if p.tok != token.RBRACK {
373                 len = p.parseExpr()
374         }
375         p.expect(token.RBRACK)
376         elt := p.parseType()
377
378         return &ast.ArrayType{lbrack, len, elt}
379 }
380
381
382 func (p *parser) makeIdentList(list []ast.Expr) []*ast.Ident {
383         idents := make([]*ast.Ident, len(list))
384         for i, x := range list {
385                 ident, isIdent := x.(*ast.Ident)
386                 if !isIdent {
387                         pos := x.(ast.Expr).Pos()
388                         p.errorExpected(pos, "identifier")
389                         ident = &ast.Ident{pos, "_", nil}
390                 }
391                 idents[i] = ident
392         }
393         return idents
394 }
395
396
397 func (p *parser) parseFieldDecl() *ast.Field {
398         if p.trace {
399                 defer un(trace(p, "FieldDecl"))
400         }
401
402         doc := p.leadComment
403
404         // fields
405         list, typ := p.parseVarList(false)
406
407         // optional tag
408         var tag *ast.BasicLit
409         if p.tok == token.STRING {
410                 tag = &ast.BasicLit{p.pos, p.tok, p.lit}
411                 p.next()
412         }
413
414         // analyze case
415         var idents []*ast.Ident
416         if typ != nil {
417                 // IdentifierList Type
418                 idents = p.makeIdentList(list)
419         } else {
420                 // ["*"] TypeName (AnonymousField)
421                 typ = list[0] // we always have at least one element
422                 if n := len(list); n > 1 || !isTypeName(deref(typ)) {
423                         pos := typ.Pos()
424                         p.errorExpected(pos, "anonymous field")
425                         typ = &ast.BadExpr{pos, list[n-1].End()}
426                 }
427         }
428
429         p.expectSemi()
430
431         return &ast.Field{doc, idents, typ, tag, p.lineComment}
432 }
433
434
435 func (p *parser) parseStructType() *ast.StructType {
436         if p.trace {
437                 defer un(trace(p, "StructType"))
438         }
439
440         pos := p.expect(token.STRUCT)
441         lbrace := p.expect(token.LBRACE)
442         var list []*ast.Field
443         for p.tok == token.IDENT || p.tok == token.MUL || p.tok == token.LPAREN {
444                 // a field declaration cannot start with a '(' but we accept
445                 // it here for more robust parsing and better error messages
446                 // (parseFieldDecl will check and complain if necessary)
447                 list = append(list, p.parseFieldDecl())
448         }
449         rbrace := p.expect(token.RBRACE)
450
451         return &ast.StructType{pos, &ast.FieldList{lbrace, list, rbrace}, false}
452 }
453
454
455 func (p *parser) parsePointerType() *ast.StarExpr {
456         if p.trace {
457                 defer un(trace(p, "PointerType"))
458         }
459
460         star := p.expect(token.MUL)
461         base := p.parseType()
462
463         return &ast.StarExpr{star, base}
464 }
465
466
467 func (p *parser) tryVarType(isParam bool) ast.Expr {
468         if isParam && p.tok == token.ELLIPSIS {
469                 pos := p.pos
470                 p.next()
471                 typ := p.tryType() // don't use parseType so we can provide better error message
472                 if typ == nil {
473                         p.error(pos, "'...' parameter is missing type")
474                         typ = &ast.BadExpr{pos, p.pos}
475                 }
476                 if p.tok != token.RPAREN {
477                         p.error(pos, "can use '...' with last parameter type only")
478                 }
479                 return &ast.Ellipsis{pos, typ}
480         }
481         return p.tryType()
482 }
483
484
485 func (p *parser) parseVarType(isParam bool) ast.Expr {
486         typ := p.tryVarType(isParam)
487         if typ == nil {
488                 pos := p.pos
489                 p.errorExpected(pos, "type")
490                 p.next() // make progress
491                 typ = &ast.BadExpr{pos, p.pos}
492         }
493         return typ
494 }
495
496
497 func (p *parser) parseVarList(isParam bool) (list []ast.Expr, typ ast.Expr) {
498         if p.trace {
499                 defer un(trace(p, "VarList"))
500         }
501
502         // a list of identifiers looks like a list of type names
503         for {
504                 // parseVarType accepts any type (including parenthesized ones)
505                 // even though the syntax does not permit them here: we
506                 // accept them all for more robust parsing and complain
507                 // afterwards
508                 list = append(list, p.parseVarType(isParam))
509                 if p.tok != token.COMMA {
510                         break
511                 }
512                 p.next()
513         }
514
515         // if we had a list of identifiers, it must be followed by a type
516         typ = p.tryVarType(isParam)
517
518         return
519 }
520
521
522 func (p *parser) parseParameterList(ellipsisOk bool) (params []*ast.Field) {
523         if p.trace {
524                 defer un(trace(p, "ParameterList"))
525         }
526
527         list, typ := p.parseVarList(ellipsisOk)
528         if typ != nil {
529                 // IdentifierList Type
530                 idents := p.makeIdentList(list)
531                 params = append(params, &ast.Field{nil, idents, typ, nil, nil})
532                 if p.tok == token.COMMA {
533                         p.next()
534                 }
535
536                 for p.tok != token.RPAREN && p.tok != token.EOF {
537                         idents := p.parseIdentList()
538                         typ := p.parseVarType(ellipsisOk)
539                         params = append(params, &ast.Field{nil, idents, typ, nil, nil})
540                         if p.tok != token.COMMA {
541                                 break
542                         }
543                         p.next()
544                 }
545
546         } else {
547                 // Type { "," Type } (anonymous parameters)
548                 params = make([]*ast.Field, len(list))
549                 for i, x := range list {
550                         params[i] = &ast.Field{Type: x}
551                 }
552         }
553
554         return
555 }
556
557
558 func (p *parser) parseParameters(ellipsisOk bool) *ast.FieldList {
559         if p.trace {
560                 defer un(trace(p, "Parameters"))
561         }
562
563         var params []*ast.Field
564         lparen := p.expect(token.LPAREN)
565         if p.tok != token.RPAREN {
566                 params = p.parseParameterList(ellipsisOk)
567         }
568         rparen := p.expect(token.RPAREN)
569
570         return &ast.FieldList{lparen, params, rparen}
571 }
572
573
574 func (p *parser) parseResult() *ast.FieldList {
575         if p.trace {
576                 defer un(trace(p, "Result"))
577         }
578
579         if p.tok == token.LPAREN {
580                 return p.parseParameters(false)
581         }
582
583         typ := p.tryType()
584         if typ != nil {
585                 list := make([]*ast.Field, 1)
586                 list[0] = &ast.Field{Type: typ}
587                 return &ast.FieldList{List: list}
588         }
589
590         return nil
591 }
592
593
594 func (p *parser) parseSignature() (params, results *ast.FieldList) {
595         if p.trace {
596                 defer un(trace(p, "Signature"))
597         }
598
599         params = p.parseParameters(true)
600         results = p.parseResult()
601
602         return
603 }
604
605
606 func (p *parser) parseFuncType() *ast.FuncType {
607         if p.trace {
608                 defer un(trace(p, "FuncType"))
609         }
610
611         pos := p.expect(token.FUNC)
612         params, results := p.parseSignature()
613
614         return &ast.FuncType{pos, params, results}
615 }
616
617
618 func (p *parser) parseMethodSpec() *ast.Field {
619         if p.trace {
620                 defer un(trace(p, "MethodSpec"))
621         }
622
623         doc := p.leadComment
624         var idents []*ast.Ident
625         var typ ast.Expr
626         x := p.parseQualifiedIdent()
627         if ident, isIdent := x.(*ast.Ident); isIdent && p.tok == token.LPAREN {
628                 // method
629                 idents = []*ast.Ident{ident}
630                 params, results := p.parseSignature()
631                 typ = &ast.FuncType{token.NoPos, params, results}
632         } else {
633                 // embedded interface
634                 typ = x
635         }
636         p.expectSemi()
637
638         return &ast.Field{doc, idents, typ, nil, p.lineComment}
639 }
640
641
642 func (p *parser) parseInterfaceType() *ast.InterfaceType {
643         if p.trace {
644                 defer un(trace(p, "InterfaceType"))
645         }
646
647         pos := p.expect(token.INTERFACE)
648         lbrace := p.expect(token.LBRACE)
649         var list []*ast.Field
650         for p.tok == token.IDENT {
651                 list = append(list, p.parseMethodSpec())
652         }
653         rbrace := p.expect(token.RBRACE)
654
655         return &ast.InterfaceType{pos, &ast.FieldList{lbrace, list, rbrace}, false}
656 }
657
658
659 func (p *parser) parseMapType() *ast.MapType {
660         if p.trace {
661                 defer un(trace(p, "MapType"))
662         }
663
664         pos := p.expect(token.MAP)
665         p.expect(token.LBRACK)
666         key := p.parseType()
667         p.expect(token.RBRACK)
668         value := p.parseType()
669
670         return &ast.MapType{pos, key, value}
671 }
672
673
674 func (p *parser) parseChanType() *ast.ChanType {
675         if p.trace {
676                 defer un(trace(p, "ChanType"))
677         }
678
679         pos := p.pos
680         dir := ast.SEND | ast.RECV
681         if p.tok == token.CHAN {
682                 p.next()
683                 if p.tok == token.ARROW {
684                         p.next()
685                         dir = ast.SEND
686                 }
687         } else {
688                 p.expect(token.ARROW)
689                 p.expect(token.CHAN)
690                 dir = ast.RECV
691         }
692         value := p.parseType()
693
694         return &ast.ChanType{pos, dir, value}
695 }
696
697
698 func (p *parser) tryRawType(ellipsisOk bool) ast.Expr {
699         switch p.tok {
700         case token.IDENT:
701                 return p.parseTypeName()
702         case token.LBRACK:
703                 return p.parseArrayType(ellipsisOk)
704         case token.STRUCT:
705                 return p.parseStructType()
706         case token.MUL:
707                 return p.parsePointerType()
708         case token.FUNC:
709                 return p.parseFuncType()
710         case token.INTERFACE:
711                 return p.parseInterfaceType()
712         case token.MAP:
713                 return p.parseMapType()
714         case token.CHAN, token.ARROW:
715                 return p.parseChanType()
716         case token.LPAREN:
717                 lparen := p.pos
718                 p.next()
719                 typ := p.parseType()
720                 rparen := p.expect(token.RPAREN)
721                 return &ast.ParenExpr{lparen, typ, rparen}
722         }
723
724         // no type found
725         return nil
726 }
727
728
729 func (p *parser) tryType() ast.Expr { return p.tryRawType(false) }
730
731
732 // ----------------------------------------------------------------------------
733 // Blocks
734
735 func (p *parser) parseStmtList() (list []ast.Stmt) {
736         if p.trace {
737                 defer un(trace(p, "StatementList"))
738         }
739
740         for p.tok != token.CASE && p.tok != token.DEFAULT && p.tok != token.RBRACE && p.tok != token.EOF {
741                 list = append(list, p.parseStmt())
742         }
743
744         return
745 }
746
747
748 func (p *parser) parseBody() *ast.BlockStmt {
749         if p.trace {
750                 defer un(trace(p, "Body"))
751         }
752
753         lbrace := p.expect(token.LBRACE)
754         list := p.parseStmtList()
755         rbrace := p.expect(token.RBRACE)
756
757         return &ast.BlockStmt{lbrace, list, rbrace}
758 }
759
760
761 func (p *parser) parseBlockStmt() *ast.BlockStmt {
762         if p.trace {
763                 defer un(trace(p, "BlockStmt"))
764         }
765
766         lbrace := p.expect(token.LBRACE)
767         list := p.parseStmtList()
768         rbrace := p.expect(token.RBRACE)
769
770         return &ast.BlockStmt{lbrace, list, rbrace}
771 }
772
773
774 // ----------------------------------------------------------------------------
775 // Expressions
776
777 func (p *parser) parseFuncTypeOrLit() ast.Expr {
778         if p.trace {
779                 defer un(trace(p, "FuncTypeOrLit"))
780         }
781
782         typ := p.parseFuncType()
783         if p.tok != token.LBRACE {
784                 // function type only
785                 return typ
786         }
787
788         p.exprLev++
789         body := p.parseBody()
790         p.exprLev--
791
792         return &ast.FuncLit{typ, body}
793 }
794
795
796 // parseOperand may return an expression or a raw type (incl. array
797 // types of the form [...]T. Callers must verify the result.
798 //
799 func (p *parser) parseOperand() ast.Expr {
800         if p.trace {
801                 defer un(trace(p, "Operand"))
802         }
803
804         switch p.tok {
805         case token.IDENT:
806                 return p.parseIdent()
807
808         case token.INT, token.FLOAT, token.IMAG, token.CHAR, token.STRING:
809                 x := &ast.BasicLit{p.pos, p.tok, p.lit}
810                 p.next()
811                 return x
812
813         case token.LPAREN:
814                 lparen := p.pos
815                 p.next()
816                 p.exprLev++
817                 x := p.parseExpr()
818                 p.exprLev--
819                 rparen := p.expect(token.RPAREN)
820                 return &ast.ParenExpr{lparen, x, rparen}
821
822         case token.FUNC:
823                 return p.parseFuncTypeOrLit()
824
825         default:
826                 t := p.tryRawType(true) // could be type for composite literal or conversion
827                 if t != nil {
828                         return t
829                 }
830         }
831
832         pos := p.pos
833         p.errorExpected(pos, "operand")
834         p.next() // make progress
835         return &ast.BadExpr{pos, p.pos}
836 }
837
838
839 func (p *parser) parseSelectorOrTypeAssertion(x ast.Expr) ast.Expr {
840         if p.trace {
841                 defer un(trace(p, "SelectorOrTypeAssertion"))
842         }
843
844         p.expect(token.PERIOD)
845         if p.tok == token.IDENT {
846                 // selector
847                 sel := p.parseIdent()
848                 return &ast.SelectorExpr{x, sel}
849         }
850
851         // type assertion
852         p.expect(token.LPAREN)
853         var typ ast.Expr
854         if p.tok == token.TYPE {
855                 // type switch: typ == nil
856                 p.next()
857         } else {
858                 typ = p.parseType()
859         }
860         p.expect(token.RPAREN)
861
862         return &ast.TypeAssertExpr{x, typ}
863 }
864
865
866 func (p *parser) parseIndexOrSlice(x ast.Expr) ast.Expr {
867         if p.trace {
868                 defer un(trace(p, "IndexOrSlice"))
869         }
870
871         lbrack := p.expect(token.LBRACK)
872         p.exprLev++
873         var low, high ast.Expr
874         isSlice := false
875         if p.tok != token.COLON {
876                 low = p.parseExpr()
877         }
878         if p.tok == token.COLON {
879                 isSlice = true
880                 p.next()
881                 if p.tok != token.RBRACK {
882                         high = p.parseExpr()
883                 }
884         }
885         p.exprLev--
886         rbrack := p.expect(token.RBRACK)
887
888         if isSlice {
889                 return &ast.SliceExpr{x, lbrack, low, high, rbrack}
890         }
891         return &ast.IndexExpr{x, lbrack, low, rbrack}
892 }
893
894
895 func (p *parser) parseCallOrConversion(fun ast.Expr) *ast.CallExpr {
896         if p.trace {
897                 defer un(trace(p, "CallOrConversion"))
898         }
899
900         lparen := p.expect(token.LPAREN)
901         p.exprLev++
902         var list []ast.Expr
903         var ellipsis token.Pos
904         for p.tok != token.RPAREN && p.tok != token.EOF && !ellipsis.IsValid() {
905                 list = append(list, p.parseExpr())
906                 if p.tok == token.ELLIPSIS {
907                         ellipsis = p.pos
908                         p.next()
909                 }
910                 if p.tok != token.COMMA {
911                         break
912                 }
913                 p.next()
914         }
915         p.exprLev--
916         rparen := p.expect(token.RPAREN)
917
918         return &ast.CallExpr{fun, lparen, list, ellipsis, rparen}
919 }
920
921
922 func (p *parser) parseElement(keyOk bool) ast.Expr {
923         if p.trace {
924                 defer un(trace(p, "Element"))
925         }
926
927         if p.tok == token.LBRACE {
928                 return p.parseLiteralValue(nil)
929         }
930
931         x := p.parseExpr()
932         if keyOk && p.tok == token.COLON {
933                 colon := p.pos
934                 p.next()
935                 x = &ast.KeyValueExpr{x, colon, p.parseElement(false)}
936         }
937         return x
938 }
939
940
941 func (p *parser) parseElementList() (list []ast.Expr) {
942         if p.trace {
943                 defer un(trace(p, "ElementList"))
944         }
945
946         for p.tok != token.RBRACE && p.tok != token.EOF {
947                 list = append(list, p.parseElement(true))
948                 if p.tok != token.COMMA {
949                         break
950                 }
951                 p.next()
952         }
953
954         return
955 }
956
957
958 func (p *parser) parseLiteralValue(typ ast.Expr) ast.Expr {
959         if p.trace {
960                 defer un(trace(p, "LiteralValue"))
961         }
962
963         lbrace := p.expect(token.LBRACE)
964         var elts []ast.Expr
965         p.exprLev++
966         if p.tok != token.RBRACE {
967                 elts = p.parseElementList()
968         }
969         p.exprLev--
970         rbrace := p.expect(token.RBRACE)
971         return &ast.CompositeLit{typ, lbrace, elts, rbrace}
972 }
973
974
975 // checkExpr checks that x is an expression (and not a type).
976 func (p *parser) checkExpr(x ast.Expr) ast.Expr {
977         switch t := unparen(x).(type) {
978         case *ast.BadExpr:
979         case *ast.Ident:
980         case *ast.BasicLit:
981         case *ast.FuncLit:
982         case *ast.CompositeLit:
983         case *ast.ParenExpr:
984                 panic("unreachable")
985         case *ast.SelectorExpr:
986         case *ast.IndexExpr:
987         case *ast.SliceExpr:
988         case *ast.TypeAssertExpr:
989                 if t.Type == nil {
990                         // the form X.(type) is only allowed in type switch expressions
991                         p.errorExpected(x.Pos(), "expression")
992                         x = &ast.BadExpr{x.Pos(), x.End()}
993                 }
994         case *ast.CallExpr:
995         case *ast.StarExpr:
996         case *ast.UnaryExpr:
997                 if t.Op == token.RANGE {
998                         // the range operator is only allowed at the top of a for statement
999                         p.errorExpected(x.Pos(), "expression")
1000                         x = &ast.BadExpr{x.Pos(), x.End()}
1001                 }
1002         case *ast.BinaryExpr:
1003         default:
1004                 // all other nodes are not proper expressions
1005                 p.errorExpected(x.Pos(), "expression")
1006                 x = &ast.BadExpr{x.Pos(), x.End()}
1007         }
1008         return x
1009 }
1010
1011
1012 // isTypeName returns true iff x is a (qualified) TypeName.
1013 func isTypeName(x ast.Expr) bool {
1014         switch t := x.(type) {
1015         case *ast.BadExpr:
1016         case *ast.Ident:
1017         case *ast.SelectorExpr:
1018                 _, isIdent := t.X.(*ast.Ident)
1019                 return isIdent
1020         default:
1021                 return false // all other nodes are not type names
1022         }
1023         return true
1024 }
1025
1026
1027 // isLiteralType returns true iff x is a legal composite literal type.
1028 func isLiteralType(x ast.Expr) bool {
1029         switch t := x.(type) {
1030         case *ast.BadExpr:
1031         case *ast.Ident:
1032         case *ast.SelectorExpr:
1033                 _, isIdent := t.X.(*ast.Ident)
1034                 return isIdent
1035         case *ast.ArrayType:
1036         case *ast.StructType:
1037         case *ast.MapType:
1038         default:
1039                 return false // all other nodes are not legal composite literal types
1040         }
1041         return true
1042 }
1043
1044
1045 // If x is of the form *T, deref returns T, otherwise it returns x.
1046 func deref(x ast.Expr) ast.Expr {
1047         if p, isPtr := x.(*ast.StarExpr); isPtr {
1048                 x = p.X
1049         }
1050         return x
1051 }
1052
1053
1054 // If x is of the form (T), unparen returns unparen(T), otherwise it returns x.
1055 func unparen(x ast.Expr) ast.Expr {
1056         if p, isParen := x.(*ast.ParenExpr); isParen {
1057                 x = unparen(p.X)
1058         }
1059         return x
1060 }
1061
1062
1063 // checkExprOrType checks that x is an expression or a type
1064 // (and not a raw type such as [...]T).
1065 //
1066 func (p *parser) checkExprOrType(x ast.Expr) ast.Expr {
1067         switch t := unparen(x).(type) {
1068         case *ast.ParenExpr:
1069                 panic("unreachable")
1070         case *ast.UnaryExpr:
1071                 if t.Op == token.RANGE {
1072                         // the range operator is only allowed at the top of a for statement
1073                         p.errorExpected(x.Pos(), "expression")
1074                         x = &ast.BadExpr{x.Pos(), x.End()}
1075                 }
1076         case *ast.ArrayType:
1077                 if len, isEllipsis := t.Len.(*ast.Ellipsis); isEllipsis {
1078                         p.error(len.Pos(), "expected array length, found '...'")
1079                         x = &ast.BadExpr{x.Pos(), x.End()}
1080                 }
1081         }
1082
1083         // all other nodes are expressions or types
1084         return x
1085 }
1086
1087
1088 func (p *parser) parsePrimaryExpr() ast.Expr {
1089         if p.trace {
1090                 defer un(trace(p, "PrimaryExpr"))
1091         }
1092
1093         x := p.parseOperand()
1094 L:
1095         for {
1096                 switch p.tok {
1097                 case token.PERIOD:
1098                         x = p.parseSelectorOrTypeAssertion(p.checkExpr(x))
1099                 case token.LBRACK:
1100                         x = p.parseIndexOrSlice(p.checkExpr(x))
1101                 case token.LPAREN:
1102                         x = p.parseCallOrConversion(p.checkExprOrType(x))
1103                 case token.LBRACE:
1104                         if isLiteralType(x) && (p.exprLev >= 0 || !isTypeName(x)) {
1105                                 x = p.parseLiteralValue(x)
1106                         } else {
1107                                 break L
1108                         }
1109                 default:
1110                         break L
1111                 }
1112         }
1113
1114         return x
1115 }
1116
1117
1118 func (p *parser) parseUnaryExpr() ast.Expr {
1119         if p.trace {
1120                 defer un(trace(p, "UnaryExpr"))
1121         }
1122
1123         switch p.tok {
1124         case token.ADD, token.SUB, token.NOT, token.XOR, token.AND, token.RANGE:
1125                 pos, op := p.pos, p.tok
1126                 p.next()
1127                 x := p.parseUnaryExpr()
1128                 return &ast.UnaryExpr{pos, op, p.checkExpr(x)}
1129
1130         case token.ARROW:
1131                 // channel type or receive expression
1132                 pos := p.pos
1133                 p.next()
1134                 if p.tok == token.CHAN {
1135                         p.next()
1136                         value := p.parseType()
1137                         return &ast.ChanType{pos, ast.RECV, value}
1138                 }
1139
1140                 x := p.parseUnaryExpr()
1141                 return &ast.UnaryExpr{pos, token.ARROW, p.checkExpr(x)}
1142
1143         case token.MUL:
1144                 // pointer type or unary "*" expression
1145                 pos := p.pos
1146                 p.next()
1147                 x := p.parseUnaryExpr()
1148                 return &ast.StarExpr{pos, p.checkExprOrType(x)}
1149         }
1150
1151         return p.parsePrimaryExpr()
1152 }
1153
1154
1155 func (p *parser) parseBinaryExpr(prec1 int) ast.Expr {
1156         if p.trace {
1157                 defer un(trace(p, "BinaryExpr"))
1158         }
1159
1160         x := p.parseUnaryExpr()
1161         for prec := p.tok.Precedence(); prec >= prec1; prec-- {
1162                 for p.tok.Precedence() == prec {
1163                         pos, op := p.pos, p.tok
1164                         p.next()
1165                         y := p.parseBinaryExpr(prec + 1)
1166                         x = &ast.BinaryExpr{p.checkExpr(x), pos, op, p.checkExpr(y)}
1167                 }
1168         }
1169
1170         return x
1171 }
1172
1173
1174 // TODO(gri): parseExpr may return a type or even a raw type ([..]int) -
1175 //            should reject when a type/raw type is obviously not allowed
1176 func (p *parser) parseExpr() ast.Expr {
1177         if p.trace {
1178                 defer un(trace(p, "Expression"))
1179         }
1180
1181         return p.parseBinaryExpr(token.LowestPrec + 1)
1182 }
1183
1184
1185 // ----------------------------------------------------------------------------
1186 // Statements
1187
1188 func (p *parser) parseSimpleStmt(labelOk bool) ast.Stmt {
1189         if p.trace {
1190                 defer un(trace(p, "SimpleStmt"))
1191         }
1192
1193         x := p.parseExprList()
1194
1195         switch p.tok {
1196         case token.COLON:
1197                 // labeled statement
1198                 colon := p.pos
1199                 p.next()
1200                 if labelOk && len(x) == 1 {
1201                         if label, isIdent := x[0].(*ast.Ident); isIdent {
1202                                 return &ast.LabeledStmt{label, colon, p.parseStmt()}
1203                         }
1204                 }
1205                 p.error(x[0].Pos(), "illegal label declaration")
1206                 return &ast.BadStmt{x[0].Pos(), colon + 1}
1207
1208         case
1209                 token.DEFINE, token.ASSIGN, token.ADD_ASSIGN,
1210                 token.SUB_ASSIGN, token.MUL_ASSIGN, token.QUO_ASSIGN,
1211                 token.REM_ASSIGN, token.AND_ASSIGN, token.OR_ASSIGN,
1212                 token.XOR_ASSIGN, token.SHL_ASSIGN, token.SHR_ASSIGN, token.AND_NOT_ASSIGN:
1213                 // assignment statement
1214                 pos, tok := p.pos, p.tok
1215                 p.next()
1216                 y := p.parseExprList()
1217                 return &ast.AssignStmt{x, pos, tok, y}
1218         }
1219
1220         if len(x) > 1 {
1221                 p.error(x[0].Pos(), "only one expression allowed")
1222                 // continue with first expression
1223         }
1224
1225         if p.tok == token.INC || p.tok == token.DEC {
1226                 // increment or decrement
1227                 s := &ast.IncDecStmt{x[0], p.pos, p.tok}
1228                 p.next() // consume "++" or "--"
1229                 return s
1230         }
1231
1232         // expression
1233         return &ast.ExprStmt{x[0]}
1234 }
1235
1236
1237 func (p *parser) parseCallExpr() *ast.CallExpr {
1238         x := p.parseExpr()
1239         if call, isCall := x.(*ast.CallExpr); isCall {
1240                 return call
1241         }
1242         p.errorExpected(x.Pos(), "function/method call")
1243         return nil
1244 }
1245
1246
1247 func (p *parser) parseGoStmt() ast.Stmt {
1248         if p.trace {
1249                 defer un(trace(p, "GoStmt"))
1250         }
1251
1252         pos := p.expect(token.GO)
1253         call := p.parseCallExpr()
1254         p.expectSemi()
1255         if call == nil {
1256                 return &ast.BadStmt{pos, pos + 2} // len("go")
1257         }
1258
1259         return &ast.GoStmt{pos, call}
1260 }
1261
1262
1263 func (p *parser) parseDeferStmt() ast.Stmt {
1264         if p.trace {
1265                 defer un(trace(p, "DeferStmt"))
1266         }
1267
1268         pos := p.expect(token.DEFER)
1269         call := p.parseCallExpr()
1270         p.expectSemi()
1271         if call == nil {
1272                 return &ast.BadStmt{pos, pos + 5} // len("defer")
1273         }
1274
1275         return &ast.DeferStmt{pos, call}
1276 }
1277
1278
1279 func (p *parser) parseReturnStmt() *ast.ReturnStmt {
1280         if p.trace {
1281                 defer un(trace(p, "ReturnStmt"))
1282         }
1283
1284         pos := p.pos
1285         p.expect(token.RETURN)
1286         var x []ast.Expr
1287         if p.tok != token.SEMICOLON && p.tok != token.RBRACE {
1288                 x = p.parseExprList()
1289         }
1290         p.expectSemi()
1291
1292         return &ast.ReturnStmt{pos, x}
1293 }
1294
1295
1296 func (p *parser) parseBranchStmt(tok token.Token) *ast.BranchStmt {
1297         if p.trace {
1298                 defer un(trace(p, "BranchStmt"))
1299         }
1300
1301         s := &ast.BranchStmt{p.pos, tok, nil}
1302         p.expect(tok)
1303         if tok != token.FALLTHROUGH && p.tok == token.IDENT {
1304                 s.Label = p.parseIdent()
1305         }
1306         p.expectSemi()
1307
1308         return s
1309 }
1310
1311
1312 func (p *parser) makeExpr(s ast.Stmt) ast.Expr {
1313         if s == nil {
1314                 return nil
1315         }
1316         if es, isExpr := s.(*ast.ExprStmt); isExpr {
1317                 return p.checkExpr(es.X)
1318         }
1319         p.error(s.Pos(), "expected condition, found simple statement")
1320         return &ast.BadExpr{s.Pos(), s.End()}
1321 }
1322
1323
1324 func (p *parser) parseControlClause(isForStmt bool) (s1, s2, s3 ast.Stmt) {
1325         if p.tok != token.LBRACE {
1326                 prevLev := p.exprLev
1327                 p.exprLev = -1
1328
1329                 if p.tok != token.SEMICOLON {
1330                         s1 = p.parseSimpleStmt(false)
1331                 }
1332                 if p.tok == token.SEMICOLON {
1333                         p.next()
1334                         if p.tok != token.LBRACE && p.tok != token.SEMICOLON {
1335                                 s2 = p.parseSimpleStmt(false)
1336                         }
1337                         if isForStmt {
1338                                 // for statements have a 3rd section
1339                                 p.expectSemi()
1340                                 if p.tok != token.LBRACE {
1341                                         s3 = p.parseSimpleStmt(false)
1342                                 }
1343                         }
1344                 } else {
1345                         s1, s2 = nil, s1
1346                 }
1347
1348                 p.exprLev = prevLev
1349         }
1350
1351         return s1, s2, s3
1352 }
1353
1354
1355 func (p *parser) parseIfStmt() *ast.IfStmt {
1356         if p.trace {
1357                 defer un(trace(p, "IfStmt"))
1358         }
1359
1360         pos := p.expect(token.IF)
1361         s1, s2, _ := p.parseControlClause(false)
1362         body := p.parseBlockStmt()
1363         var else_ ast.Stmt
1364         if p.tok == token.ELSE {
1365                 p.next()
1366                 else_ = p.parseStmt()
1367         } else {
1368                 p.expectSemi()
1369         }
1370
1371         return &ast.IfStmt{pos, s1, p.makeExpr(s2), body, else_}
1372 }
1373
1374
1375 func (p *parser) parseCaseClause() *ast.CaseClause {
1376         if p.trace {
1377                 defer un(trace(p, "CaseClause"))
1378         }
1379
1380         // SwitchCase
1381         pos := p.pos
1382         var x []ast.Expr
1383         if p.tok == token.CASE {
1384                 p.next()
1385                 x = p.parseExprList()
1386         } else {
1387                 p.expect(token.DEFAULT)
1388         }
1389
1390         colon := p.expect(token.COLON)
1391         body := p.parseStmtList()
1392
1393         return &ast.CaseClause{pos, x, colon, body}
1394 }
1395
1396
1397 func (p *parser) parseTypeList() (list []ast.Expr) {
1398         if p.trace {
1399                 defer un(trace(p, "TypeList"))
1400         }
1401
1402         list = append(list, p.parseType())
1403         for p.tok == token.COMMA {
1404                 p.next()
1405                 list = append(list, p.parseType())
1406         }
1407
1408         return
1409 }
1410
1411
1412 func (p *parser) parseTypeCaseClause() *ast.TypeCaseClause {
1413         if p.trace {
1414                 defer un(trace(p, "TypeCaseClause"))
1415         }
1416
1417         // TypeSwitchCase
1418         pos := p.pos
1419         var types []ast.Expr
1420         if p.tok == token.CASE {
1421                 p.next()
1422                 types = p.parseTypeList()
1423         } else {
1424                 p.expect(token.DEFAULT)
1425         }
1426
1427         colon := p.expect(token.COLON)
1428         body := p.parseStmtList()
1429
1430         return &ast.TypeCaseClause{pos, types, colon, body}
1431 }
1432
1433
1434 func isExprSwitch(s ast.Stmt) bool {
1435         if s == nil {
1436                 return true
1437         }
1438         if e, ok := s.(*ast.ExprStmt); ok {
1439                 if a, ok := e.X.(*ast.TypeAssertExpr); ok {
1440                         return a.Type != nil // regular type assertion
1441                 }
1442                 return true
1443         }
1444         return false
1445 }
1446
1447
1448 func (p *parser) parseSwitchStmt() ast.Stmt {
1449         if p.trace {
1450                 defer un(trace(p, "SwitchStmt"))
1451         }
1452
1453         pos := p.expect(token.SWITCH)
1454         s1, s2, _ := p.parseControlClause(false)
1455
1456         if isExprSwitch(s2) {
1457                 lbrace := p.expect(token.LBRACE)
1458                 var list []ast.Stmt
1459                 for p.tok == token.CASE || p.tok == token.DEFAULT {
1460                         list = append(list, p.parseCaseClause())
1461                 }
1462                 rbrace := p.expect(token.RBRACE)
1463                 body := &ast.BlockStmt{lbrace, list, rbrace}
1464                 p.expectSemi()
1465                 return &ast.SwitchStmt{pos, s1, p.makeExpr(s2), body}
1466         }
1467
1468         // type switch
1469         // TODO(gri): do all the checks!
1470         lbrace := p.expect(token.LBRACE)
1471         var list []ast.Stmt
1472         for p.tok == token.CASE || p.tok == token.DEFAULT {
1473                 list = append(list, p.parseTypeCaseClause())
1474         }
1475         rbrace := p.expect(token.RBRACE)
1476         p.expectSemi()
1477         body := &ast.BlockStmt{lbrace, list, rbrace}
1478         return &ast.TypeSwitchStmt{pos, s1, s2, body}
1479 }
1480
1481
1482 func (p *parser) parseCommClause() *ast.CommClause {
1483         if p.trace {
1484                 defer un(trace(p, "CommClause"))
1485         }
1486
1487         // CommCase
1488         pos := p.pos
1489         var tok token.Token
1490         var lhs, rhs ast.Expr
1491         if p.tok == token.CASE {
1492                 p.next()
1493                 if p.tok == token.ARROW {
1494                         // RecvExpr without assignment
1495                         rhs = p.parseExpr()
1496                 } else {
1497                         // SendExpr or RecvExpr
1498                         rhs = p.parseExpr()
1499                         if p.tok == token.ASSIGN || p.tok == token.DEFINE {
1500                                 // RecvExpr with assignment
1501                                 tok = p.tok
1502                                 p.next()
1503                                 lhs = rhs
1504                                 if p.tok == token.ARROW {
1505                                         rhs = p.parseExpr()
1506                                 } else {
1507                                         p.expect(token.ARROW) // use expect() error handling
1508                                 }
1509                         }
1510                         // else SendExpr
1511                 }
1512         } else {
1513                 p.expect(token.DEFAULT)
1514         }
1515
1516         colon := p.expect(token.COLON)
1517         body := p.parseStmtList()
1518
1519         return &ast.CommClause{pos, tok, lhs, rhs, colon, body}
1520 }
1521
1522
1523 func (p *parser) parseSelectStmt() *ast.SelectStmt {
1524         if p.trace {
1525                 defer un(trace(p, "SelectStmt"))
1526         }
1527
1528         pos := p.expect(token.SELECT)
1529         lbrace := p.expect(token.LBRACE)
1530         var list []ast.Stmt
1531         for p.tok == token.CASE || p.tok == token.DEFAULT {
1532                 list = append(list, p.parseCommClause())
1533         }
1534         rbrace := p.expect(token.RBRACE)
1535         p.expectSemi()
1536         body := &ast.BlockStmt{lbrace, list, rbrace}
1537
1538         return &ast.SelectStmt{pos, body}
1539 }
1540
1541
1542 func (p *parser) parseForStmt() ast.Stmt {
1543         if p.trace {
1544                 defer un(trace(p, "ForStmt"))
1545         }
1546
1547         pos := p.expect(token.FOR)
1548         s1, s2, s3 := p.parseControlClause(true)
1549         body := p.parseBlockStmt()
1550         p.expectSemi()
1551
1552         if as, isAssign := s2.(*ast.AssignStmt); isAssign {
1553                 // possibly a for statement with a range clause; check assignment operator
1554                 if as.Tok != token.ASSIGN && as.Tok != token.DEFINE {
1555                         p.errorExpected(as.TokPos, "'=' or ':='")
1556                         return &ast.BadStmt{pos, body.End()}
1557                 }
1558                 // check lhs
1559                 var key, value ast.Expr
1560                 switch len(as.Lhs) {
1561                 case 2:
1562                         key, value = as.Lhs[0], as.Lhs[1]
1563                 case 1:
1564                         key = as.Lhs[0]
1565                 default:
1566                         p.errorExpected(as.Lhs[0].Pos(), "1 or 2 expressions")
1567                         return &ast.BadStmt{pos, body.End()}
1568                 }
1569                 // check rhs
1570                 if len(as.Rhs) != 1 {
1571                         p.errorExpected(as.Rhs[0].Pos(), "1 expressions")
1572                         return &ast.BadStmt{pos, body.End()}
1573                 }
1574                 if rhs, isUnary := as.Rhs[0].(*ast.UnaryExpr); isUnary && rhs.Op == token.RANGE {
1575                         // rhs is range expression; check lhs
1576                         return &ast.RangeStmt{pos, key, value, as.TokPos, as.Tok, rhs.X, body}
1577                 } else {
1578                         p.errorExpected(s2.Pos(), "range clause")
1579                         return &ast.BadStmt{pos, body.End()}
1580                 }
1581         } else {
1582                 // regular for statement
1583                 return &ast.ForStmt{pos, s1, p.makeExpr(s2), s3, body}
1584         }
1585
1586         panic("unreachable")
1587 }
1588
1589
1590 func (p *parser) parseStmt() (s ast.Stmt) {
1591         if p.trace {
1592                 defer un(trace(p, "Statement"))
1593         }
1594
1595         switch p.tok {
1596         case token.CONST, token.TYPE, token.VAR:
1597                 s = &ast.DeclStmt{p.parseDecl()}
1598         case
1599                 // tokens that may start a top-level expression
1600                 token.IDENT, token.INT, token.FLOAT, token.CHAR, token.STRING, token.FUNC, token.LPAREN, // operand
1601                 token.LBRACK, token.STRUCT, // composite type
1602                 token.MUL, token.AND, token.ARROW, token.ADD, token.SUB, token.XOR: // unary operators
1603                 s = p.parseSimpleStmt(true)
1604                 // because of the required look-ahead, labeled statements are
1605                 // parsed by parseSimpleStmt - don't expect a semicolon after
1606                 // them
1607                 if _, isLabeledStmt := s.(*ast.LabeledStmt); !isLabeledStmt {
1608                         p.expectSemi()
1609                 }
1610         case token.GO:
1611                 s = p.parseGoStmt()
1612         case token.DEFER:
1613                 s = p.parseDeferStmt()
1614         case token.RETURN:
1615                 s = p.parseReturnStmt()
1616         case token.BREAK, token.CONTINUE, token.GOTO, token.FALLTHROUGH:
1617                 s = p.parseBranchStmt(p.tok)
1618         case token.LBRACE:
1619                 s = p.parseBlockStmt()
1620                 p.expectSemi()
1621         case token.IF:
1622                 s = p.parseIfStmt()
1623         case token.SWITCH:
1624                 s = p.parseSwitchStmt()
1625         case token.SELECT:
1626                 s = p.parseSelectStmt()
1627         case token.FOR:
1628                 s = p.parseForStmt()
1629         case token.SEMICOLON:
1630                 s = &ast.EmptyStmt{p.pos}
1631                 p.next()
1632         case token.RBRACE:
1633                 // a semicolon may be omitted before a closing "}"
1634                 s = &ast.EmptyStmt{p.pos}
1635         default:
1636                 // no statement found
1637                 pos := p.pos
1638                 p.errorExpected(pos, "statement")
1639                 p.next() // make progress
1640                 s = &ast.BadStmt{pos, p.pos}
1641         }
1642
1643         return
1644 }
1645
1646
1647 // ----------------------------------------------------------------------------
1648 // Declarations
1649
1650 type parseSpecFunction func(p *parser, doc *ast.CommentGroup) ast.Spec
1651
1652
1653 func parseImportSpec(p *parser, doc *ast.CommentGroup) ast.Spec {
1654         if p.trace {
1655                 defer un(trace(p, "ImportSpec"))
1656         }
1657
1658         var ident *ast.Ident
1659         if p.tok == token.PERIOD {
1660                 ident = &ast.Ident{p.pos, ".", nil}
1661                 p.next()
1662         } else if p.tok == token.IDENT {
1663                 ident = p.parseIdent()
1664         }
1665
1666         var path *ast.BasicLit
1667         if p.tok == token.STRING {
1668                 path = &ast.BasicLit{p.pos, p.tok, p.lit}
1669                 p.next()
1670         } else {
1671                 p.expect(token.STRING) // use expect() error handling
1672         }
1673         p.expectSemi()
1674
1675         return &ast.ImportSpec{doc, ident, path, p.lineComment}
1676 }
1677
1678
1679 func parseConstSpec(p *parser, doc *ast.CommentGroup) ast.Spec {
1680         if p.trace {
1681                 defer un(trace(p, "ConstSpec"))
1682         }
1683
1684         idents := p.parseIdentList()
1685         typ := p.tryType()
1686         var values []ast.Expr
1687         if typ != nil || p.tok == token.ASSIGN {
1688                 p.expect(token.ASSIGN)
1689                 values = p.parseExprList()
1690         }
1691         p.expectSemi()
1692
1693         return &ast.ValueSpec{doc, idents, typ, values, p.lineComment}
1694 }
1695
1696
1697 func parseTypeSpec(p *parser, doc *ast.CommentGroup) ast.Spec {
1698         if p.trace {
1699                 defer un(trace(p, "TypeSpec"))
1700         }
1701
1702         ident := p.parseIdent()
1703         typ := p.parseType()
1704         p.expectSemi()
1705
1706         return &ast.TypeSpec{doc, ident, typ, p.lineComment}
1707 }
1708
1709
1710 func parseVarSpec(p *parser, doc *ast.CommentGroup) ast.Spec {
1711         if p.trace {
1712                 defer un(trace(p, "VarSpec"))
1713         }
1714
1715         idents := p.parseIdentList()
1716         typ := p.tryType()
1717         var values []ast.Expr
1718         if typ == nil || p.tok == token.ASSIGN {
1719                 p.expect(token.ASSIGN)
1720                 values = p.parseExprList()
1721         }
1722         p.expectSemi()
1723
1724         return &ast.ValueSpec{doc, idents, typ, values, p.lineComment}
1725 }
1726
1727
1728 func (p *parser) parseGenDecl(keyword token.Token, f parseSpecFunction) *ast.GenDecl {
1729         if p.trace {
1730                 defer un(trace(p, "GenDecl("+keyword.String()+")"))
1731         }
1732
1733         doc := p.leadComment
1734         pos := p.expect(keyword)
1735         var lparen, rparen token.Pos
1736         var list []ast.Spec
1737         if p.tok == token.LPAREN {
1738                 lparen = p.pos
1739                 p.next()
1740                 for p.tok != token.RPAREN && p.tok != token.EOF {
1741                         list = append(list, f(p, p.leadComment))
1742                 }
1743                 rparen = p.expect(token.RPAREN)
1744                 p.expectSemi()
1745         } else {
1746                 list = append(list, f(p, nil))
1747         }
1748
1749         return &ast.GenDecl{doc, pos, keyword, lparen, list, rparen}
1750 }
1751
1752
1753 func (p *parser) parseReceiver() *ast.FieldList {
1754         if p.trace {
1755                 defer un(trace(p, "Receiver"))
1756         }
1757
1758         pos := p.pos
1759         par := p.parseParameters(false)
1760
1761         // must have exactly one receiver
1762         if par.NumFields() != 1 {
1763                 p.errorExpected(pos, "exactly one receiver")
1764                 // TODO determine a better range for BadExpr below
1765                 par.List = []*ast.Field{&ast.Field{Type: &ast.BadExpr{pos, pos}}}
1766                 return par
1767         }
1768
1769         // recv type must be of the form ["*"] identifier
1770         recv := par.List[0]
1771         base := deref(recv.Type)
1772         if _, isIdent := base.(*ast.Ident); !isIdent {
1773                 p.errorExpected(base.Pos(), "(unqualified) identifier")
1774                 par.List = []*ast.Field{&ast.Field{Type: &ast.BadExpr{recv.Pos(), recv.End()}}}
1775         }
1776
1777         return par
1778 }
1779
1780
1781 func (p *parser) parseFuncDecl() *ast.FuncDecl {
1782         if p.trace {
1783                 defer un(trace(p, "FunctionDecl"))
1784         }
1785
1786         doc := p.leadComment
1787         pos := p.expect(token.FUNC)
1788
1789         var recv *ast.FieldList
1790         if p.tok == token.LPAREN {
1791                 recv = p.parseReceiver()
1792         }
1793
1794         ident := p.parseIdent()
1795         params, results := p.parseSignature()
1796
1797         var body *ast.BlockStmt
1798         if p.tok == token.LBRACE {
1799                 body = p.parseBody()
1800         }
1801         p.expectSemi()
1802
1803         return &ast.FuncDecl{doc, recv, ident, &ast.FuncType{pos, params, results}, body}
1804 }
1805
1806
1807 func (p *parser) parseDecl() ast.Decl {
1808         if p.trace {
1809                 defer un(trace(p, "Declaration"))
1810         }
1811
1812         var f parseSpecFunction
1813         switch p.tok {
1814         case token.CONST:
1815                 f = parseConstSpec
1816
1817         case token.TYPE:
1818                 f = parseTypeSpec
1819
1820         case token.VAR:
1821                 f = parseVarSpec
1822
1823         case token.FUNC:
1824                 return p.parseFuncDecl()
1825
1826         default:
1827                 pos := p.pos
1828                 p.errorExpected(pos, "declaration")
1829                 p.next() // make progress
1830                 decl := &ast.BadDecl{pos, p.pos}
1831                 return decl
1832         }
1833
1834         return p.parseGenDecl(p.tok, f)
1835 }
1836
1837
1838 func (p *parser) parseDeclList() (list []ast.Decl) {
1839         if p.trace {
1840                 defer un(trace(p, "DeclList"))
1841         }
1842
1843         for p.tok != token.EOF {
1844                 list = append(list, p.parseDecl())
1845         }
1846
1847         return
1848 }
1849
1850
1851 // ----------------------------------------------------------------------------
1852 // Source files
1853
1854 func (p *parser) parseFile() *ast.File {
1855         if p.trace {
1856                 defer un(trace(p, "File"))
1857         }
1858
1859         // package clause
1860         doc := p.leadComment
1861         pos := p.expect(token.PACKAGE)
1862         ident := p.parseIdent()
1863         p.expectSemi()
1864
1865         var decls []ast.Decl
1866
1867         // Don't bother parsing the rest if we had errors already.
1868         // Likely not a Go source file at all.
1869
1870         if p.ErrorCount() == 0 && p.mode&PackageClauseOnly == 0 {
1871                 // import decls
1872                 for p.tok == token.IMPORT {
1873                         decls = append(decls, p.parseGenDecl(token.IMPORT, parseImportSpec))
1874                 }
1875
1876                 if p.mode&ImportsOnly == 0 {
1877                         // rest of package body
1878                         for p.tok != token.EOF {
1879                                 decls = append(decls, p.parseDecl())
1880                         }
1881                 }
1882         }
1883
1884         return &ast.File{doc, pos, ident, decls, p.comments}
1885 }