OSDN Git Service

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