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.
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.
20 // The mode parameter to the Parse* functions is a set of flags (or 0).
21 // They control the amount of source code parsed and other optional
22 // parser functionality.
25 PackageClauseOnly uint = 1 << iota // parsing stops after package clause
26 ImportsOnly // parsing stops after import declarations
27 ParseComments // parse comments and add them to AST
28 Trace // print a trace of parsed productions
29 DeclarationErrors // report declaration errors
33 // The parser structure holds the parser's internal state.
37 scanner scanner.Scanner
40 mode uint // parsing mode
41 trace bool // == (mode & Trace != 0)
42 indent uint // indentation used for tracing output
45 comments []*ast.CommentGroup
46 leadComment *ast.CommentGroup // last lead comment
47 lineComment *ast.CommentGroup // last line comment
50 pos token.Pos // token position
51 tok token.Token // one token look-ahead
52 lit_ []byte // token literal (slice into original source, don't hold on to it)
54 // Non-syntactic parser control
55 exprLev int // < 0: in control clause, >= 0: in expression
57 // Ordinary identifer scopes
58 pkgScope *ast.Scope // pkgScope.Outer == nil
59 topScope *ast.Scope // top-most scope; may be pkgScope
60 unresolved []*ast.Ident // unresolved global identifiers
63 // (maintained by open/close LabelScope)
64 labelScope *ast.Scope // label scope for current function
65 targetStack [][]*ast.Ident // stack of unresolved labels
69 // scannerMode returns the scanner mode bits given the parser's mode bits.
70 func scannerMode(mode uint) uint {
71 var m uint = scanner.InsertSemis
72 if mode&ParseComments != 0 {
73 m |= scanner.ScanComments
79 func (p *parser) init(fset *token.FileSet, filename string, src []byte, mode uint) {
80 p.file = fset.AddFile(filename, fset.Base(), len(src))
81 p.scanner.Init(p.file, src, p, scannerMode(mode))
84 p.trace = mode&Trace != 0 // for convenience (p.trace is used frequently)
88 // set up the pkgScope here (as opposed to in parseFile) because
89 // there are other parser entry points (ParseExpr, etc.)
91 p.pkgScope = p.topScope
93 // for the same reason, set up a label scope
98 func (p *parser) lit() []byte {
99 // make a copy of p.lit_ so that we don't hold on to
100 // a copy of the entire source indirectly in the AST
101 t := make([]byte, len(p.lit_))
107 // ----------------------------------------------------------------------------
110 func (p *parser) openScope() {
111 p.topScope = ast.NewScope(p.topScope)
115 func (p *parser) closeScope() {
116 p.topScope = p.topScope.Outer
120 func (p *parser) openLabelScope() {
121 p.labelScope = ast.NewScope(p.labelScope)
122 p.targetStack = append(p.targetStack, nil)
126 func (p *parser) closeLabelScope() {
128 n := len(p.targetStack) - 1
129 scope := p.labelScope
130 for _, ident := range p.targetStack[n] {
131 ident.Obj = scope.Lookup(ident.Name)
132 if ident.Obj == nil && p.mode&DeclarationErrors != 0 {
133 p.error(ident.Pos(), fmt.Sprintf("label %s undefined", ident.Name))
137 p.targetStack = p.targetStack[0:n]
138 p.labelScope = p.labelScope.Outer
142 func (p *parser) declare(decl interface{}, scope *ast.Scope, kind ast.ObjKind, idents ...*ast.Ident) {
143 for _, ident := range idents {
144 if ident.Name != "_" {
145 obj := ast.NewObj(kind, ident.Name)
146 // remember the corresponding declaration for redeclaration
147 // errors and global variable resolution/typechecking phase
149 alt := scope.Insert(obj)
150 if alt != obj && p.mode&DeclarationErrors != 0 {
152 if pos := alt.Pos(); pos.IsValid() {
153 prevDecl = fmt.Sprintf("\n\tprevious declaration at %s", p.file.Position(pos))
155 p.error(ident.Pos(), fmt.Sprintf("%s redeclared in this block%s", ident.Name, prevDecl))
163 func (p *parser) shortVarDecl(idents []*ast.Ident) {
164 // Go spec: A short variable declaration may redeclare variables
165 // provided they were originally declared in the same block with
166 // the same type, and at least one of the non-blank variables is new.
167 n := 0 // number of new variables
168 for _, ident := range idents {
169 if ident.Name != "_" {
170 obj := ast.NewObj(ast.Var, ident.Name)
171 // short var declarations cannot have redeclaration errors
172 // and are not global => no need to remember the respective
174 alt := p.topScope.Insert(obj)
176 n++ // new declaration
181 if n == 0 && p.mode&DeclarationErrors != 0 {
182 p.error(idents[0].Pos(), "no new variables on left side of :=")
187 func (p *parser) resolve(ident *ast.Ident) {
188 if ident.Name == "_" {
191 // try to resolve the identifier
192 for s := p.topScope; s != nil; s = s.Outer {
193 if obj := s.Lookup(ident.Name); obj != nil {
198 // collect unresolved global identifiers; ignore the others
199 if p.topScope == p.pkgScope {
200 p.unresolved = append(p.unresolved, ident)
205 // ----------------------------------------------------------------------------
208 func (p *parser) printTrace(a ...interface{}) {
209 const dots = ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . " +
210 ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
211 const n = uint(len(dots))
212 pos := p.file.Position(p.pos)
213 fmt.Printf("%5d:%3d: ", pos.Line, pos.Column)
215 for ; i > n; i -= n {
223 func trace(p *parser, msg string) *parser {
224 p.printTrace(msg, "(")
230 // Usage pattern: defer un(trace(p, "..."));
237 // Advance to the next token.
238 func (p *parser) next0() {
239 // Because of one-token look-ahead, print the previous token
240 // when tracing as it provides a more readable output. The
241 // very first token (!p.pos.IsValid()) is not initialized
242 // (it is token.ILLEGAL), so don't print it .
243 if p.trace && p.pos.IsValid() {
246 case p.tok.IsLiteral():
247 p.printTrace(s, string(p.lit_))
248 case p.tok.IsOperator(), p.tok.IsKeyword():
249 p.printTrace("\"" + s + "\"")
255 p.pos, p.tok, p.lit_ = p.scanner.Scan()
258 // Consume a comment and return it and the line on which it ends.
259 func (p *parser) consumeComment() (comment *ast.Comment, endline int) {
260 // /*-style comments may end on a different line than where they start.
261 // Scan the comment for '\n' chars and adjust endline accordingly.
262 endline = p.file.Line(p.pos)
263 if p.lit_[1] == '*' {
264 for _, b := range p.lit_ {
271 comment = &ast.Comment{p.pos, p.lit()}
278 // Consume a group of adjacent comments, add it to the parser's
279 // comments list, and return it together with the line at which
280 // the last comment in the group ends. An empty line or non-comment
281 // token terminates a comment group.
283 func (p *parser) consumeCommentGroup() (comments *ast.CommentGroup, endline int) {
284 var list []*ast.Comment
285 endline = p.file.Line(p.pos)
286 for p.tok == token.COMMENT && endline+1 >= p.file.Line(p.pos) {
287 var comment *ast.Comment
288 comment, endline = p.consumeComment()
289 list = append(list, comment)
292 // add comment group to the comments list
293 comments = &ast.CommentGroup{list}
294 p.comments = append(p.comments, comments)
300 // Advance to the next non-comment token. In the process, collect
301 // any comment groups encountered, and remember the last lead and
302 // and line comments.
304 // A lead comment is a comment group that starts and ends in a
305 // line without any other tokens and that is followed by a non-comment
306 // token on the line immediately after the comment group.
308 // A line comment is a comment group that follows a non-comment
309 // token on the same line, and that has no tokens after it on the line
312 // Lead and line comments may be considered documentation that is
313 // stored in the AST.
315 func (p *parser) next() {
318 line := p.file.Line(p.pos) // current line
321 if p.tok == token.COMMENT {
322 var comment *ast.CommentGroup
325 if p.file.Line(p.pos) == line {
326 // The comment is on same line as previous token; it
327 // cannot be a lead comment but may be a line comment.
328 comment, endline = p.consumeCommentGroup()
329 if p.file.Line(p.pos) != endline {
330 // The next token is on a different line, thus
331 // the last comment group is a line comment.
332 p.lineComment = comment
336 // consume successor comments, if any
338 for p.tok == token.COMMENT {
339 comment, endline = p.consumeCommentGroup()
342 if endline+1 == p.file.Line(p.pos) {
343 // The next token is following on the line immediately after the
344 // comment group, thus the last comment group is a lead comment.
345 p.leadComment = comment
351 func (p *parser) error(pos token.Pos, msg string) {
352 p.Error(p.file.Position(pos), msg)
356 func (p *parser) errorExpected(pos token.Pos, msg string) {
357 msg = "expected " + msg
359 // the error happened at the current position;
360 // make the error message more specific
361 if p.tok == token.SEMICOLON && p.lit_[0] == '\n' {
362 msg += ", found newline"
364 msg += ", found '" + p.tok.String() + "'"
365 if p.tok.IsLiteral() {
366 msg += " " + string(p.lit_)
374 func (p *parser) expect(tok token.Token) token.Pos {
377 p.errorExpected(pos, "'"+tok.String()+"'")
379 p.next() // make progress
384 func (p *parser) expectSemi() {
385 if p.tok != token.RPAREN && p.tok != token.RBRACE {
386 p.expect(token.SEMICOLON)
391 // ----------------------------------------------------------------------------
394 func (p *parser) parseIdent() *ast.Ident {
397 if p.tok == token.IDENT {
398 name = string(p.lit_)
401 p.expect(token.IDENT) // use expect() error handling
403 return &ast.Ident{pos, name, nil}
407 func (p *parser) parseIdentList() (list []*ast.Ident) {
409 defer un(trace(p, "IdentList"))
412 list = append(list, p.parseIdent())
413 for p.tok == token.COMMA {
415 list = append(list, p.parseIdent())
422 // ----------------------------------------------------------------------------
423 // Common productions
425 func (p *parser) parseExprList() (list []ast.Expr) {
427 defer un(trace(p, "ExpressionList"))
430 list = append(list, p.parseExpr())
431 for p.tok == token.COMMA {
433 list = append(list, p.parseExpr())
440 // ----------------------------------------------------------------------------
443 func (p *parser) parseType() ast.Expr {
445 defer un(trace(p, "Type"))
452 p.errorExpected(pos, "type")
453 p.next() // make progress
454 return &ast.BadExpr{pos, p.pos}
461 func (p *parser) parseQualifiedIdent() ast.Expr {
463 defer un(trace(p, "QualifiedIdent"))
466 ident := p.parseIdent()
468 var x ast.Expr = ident
469 if p.tok == token.PERIOD {
470 // first identifier is a package identifier
472 sel := p.parseIdent()
473 x = &ast.SelectorExpr{x, sel}
480 func (p *parser) parseTypeName() ast.Expr {
482 defer un(trace(p, "TypeName"))
485 return p.parseQualifiedIdent()
489 func (p *parser) parseArrayType(ellipsisOk bool) ast.Expr {
491 defer un(trace(p, "ArrayType"))
494 lbrack := p.expect(token.LBRACK)
496 if ellipsisOk && p.tok == token.ELLIPSIS {
497 len = &ast.Ellipsis{p.pos, nil}
499 } else if p.tok != token.RBRACK {
502 p.expect(token.RBRACK)
505 return &ast.ArrayType{lbrack, len, elt}
509 func (p *parser) makeIdentList(list []ast.Expr) []*ast.Ident {
510 idents := make([]*ast.Ident, len(list))
511 for i, x := range list {
512 ident, isIdent := x.(*ast.Ident)
514 pos := x.(ast.Expr).Pos()
515 p.errorExpected(pos, "identifier")
516 ident = &ast.Ident{pos, "_", nil}
524 func (p *parser) parseFieldDecl() *ast.Field {
526 defer un(trace(p, "FieldDecl"))
532 list, typ := p.parseVarList(false)
535 var tag *ast.BasicLit
536 if p.tok == token.STRING {
537 tag = &ast.BasicLit{p.pos, p.tok, p.lit()}
542 var idents []*ast.Ident
544 // IdentifierList Type
545 idents = p.makeIdentList(list)
547 // ["*"] TypeName (AnonymousField)
548 typ = list[0] // we always have at least one element
549 if n := len(list); n > 1 || !isTypeName(deref(typ)) {
551 p.errorExpected(pos, "anonymous field")
552 typ = &ast.BadExpr{pos, list[n-1].End()}
556 p.expectSemi() // call before accessing p.linecomment
558 return &ast.Field{doc, idents, typ, tag, p.lineComment}
562 func (p *parser) parseStructType() *ast.StructType {
564 defer un(trace(p, "StructType"))
567 pos := p.expect(token.STRUCT)
568 lbrace := p.expect(token.LBRACE)
569 var list []*ast.Field
570 for p.tok == token.IDENT || p.tok == token.MUL || p.tok == token.LPAREN {
571 // a field declaration cannot start with a '(' but we accept
572 // it here for more robust parsing and better error messages
573 // (parseFieldDecl will check and complain if necessary)
574 list = append(list, p.parseFieldDecl())
576 rbrace := p.expect(token.RBRACE)
578 return &ast.StructType{pos, &ast.FieldList{lbrace, list, rbrace}, false}
582 func (p *parser) parsePointerType() *ast.StarExpr {
584 defer un(trace(p, "PointerType"))
587 star := p.expect(token.MUL)
588 base := p.parseType()
590 return &ast.StarExpr{star, base}
594 func (p *parser) tryVarType(isParam bool) ast.Expr {
595 if isParam && p.tok == token.ELLIPSIS {
598 typ := p.tryType() // don't use parseType so we can provide better error message
600 p.error(pos, "'...' parameter is missing type")
601 typ = &ast.BadExpr{pos, p.pos}
603 if p.tok != token.RPAREN {
604 p.error(pos, "can use '...' with last parameter type only")
606 return &ast.Ellipsis{pos, typ}
612 func (p *parser) parseVarType(isParam bool) ast.Expr {
613 typ := p.tryVarType(isParam)
616 p.errorExpected(pos, "type")
617 p.next() // make progress
618 typ = &ast.BadExpr{pos, p.pos}
624 func (p *parser) parseVarList(isParam bool) (list []ast.Expr, typ ast.Expr) {
626 defer un(trace(p, "VarList"))
629 // a list of identifiers looks like a list of type names
631 // parseVarType accepts any type (including parenthesized ones)
632 // even though the syntax does not permit them here: we
633 // accept them all for more robust parsing and complain
635 list = append(list, p.parseVarType(isParam))
636 if p.tok != token.COMMA {
642 // if we had a list of identifiers, it must be followed by a type
643 typ = p.tryVarType(isParam)
649 func (p *parser) parseParameterList(scope *ast.Scope, ellipsisOk bool) (params []*ast.Field) {
651 defer un(trace(p, "ParameterList"))
654 list, typ := p.parseVarList(ellipsisOk)
656 // IdentifierList Type
657 idents := p.makeIdentList(list)
658 field := &ast.Field{nil, idents, typ, nil, nil}
659 params = append(params, field)
660 // Go spec: The scope of an identifier denoting a function
661 // parameter or result variable is the function body.
662 p.declare(field, scope, ast.Var, idents...)
663 if p.tok == token.COMMA {
667 for p.tok != token.RPAREN && p.tok != token.EOF {
668 idents := p.parseIdentList()
669 typ := p.parseVarType(ellipsisOk)
670 field := &ast.Field{nil, idents, typ, nil, nil}
671 params = append(params, field)
672 // Go spec: The scope of an identifier denoting a function
673 // parameter or result variable is the function body.
674 p.declare(field, scope, ast.Var, idents...)
675 if p.tok != token.COMMA {
682 // Type { "," Type } (anonymous parameters)
683 params = make([]*ast.Field, len(list))
684 for i, x := range list {
685 params[i] = &ast.Field{Type: x}
693 func (p *parser) parseParameters(scope *ast.Scope, ellipsisOk bool) *ast.FieldList {
695 defer un(trace(p, "Parameters"))
698 var params []*ast.Field
699 lparen := p.expect(token.LPAREN)
700 if p.tok != token.RPAREN {
701 params = p.parseParameterList(scope, ellipsisOk)
703 rparen := p.expect(token.RPAREN)
705 return &ast.FieldList{lparen, params, rparen}
709 func (p *parser) parseResult(scope *ast.Scope) *ast.FieldList {
711 defer un(trace(p, "Result"))
714 if p.tok == token.LPAREN {
715 return p.parseParameters(scope, false)
720 list := make([]*ast.Field, 1)
721 list[0] = &ast.Field{Type: typ}
722 return &ast.FieldList{List: list}
729 func (p *parser) parseSignature(scope *ast.Scope) (params, results *ast.FieldList) {
731 defer un(trace(p, "Signature"))
734 params = p.parseParameters(scope, true)
735 results = p.parseResult(scope)
741 func (p *parser) parseFuncType() (*ast.FuncType, *ast.Scope) {
743 defer un(trace(p, "FuncType"))
746 pos := p.expect(token.FUNC)
747 scope := ast.NewScope(p.topScope) // function scope
748 params, results := p.parseSignature(scope)
750 return &ast.FuncType{pos, params, results}, scope
754 func (p *parser) parseMethodSpec() *ast.Field {
756 defer un(trace(p, "MethodSpec"))
760 var idents []*ast.Ident
762 x := p.parseQualifiedIdent()
763 if ident, isIdent := x.(*ast.Ident); isIdent && p.tok == token.LPAREN {
765 idents = []*ast.Ident{ident}
766 scope := ast.NewScope(nil) // method scope
767 params, results := p.parseSignature(scope)
768 typ = &ast.FuncType{token.NoPos, params, results}
770 // embedded interface
773 p.expectSemi() // call before accessing p.linecomment
775 return &ast.Field{doc, idents, typ, nil, p.lineComment}
779 func (p *parser) parseInterfaceType() *ast.InterfaceType {
781 defer un(trace(p, "InterfaceType"))
784 pos := p.expect(token.INTERFACE)
785 lbrace := p.expect(token.LBRACE)
786 var list []*ast.Field
787 for p.tok == token.IDENT {
788 list = append(list, p.parseMethodSpec())
790 rbrace := p.expect(token.RBRACE)
792 return &ast.InterfaceType{pos, &ast.FieldList{lbrace, list, rbrace}, false}
796 func (p *parser) parseMapType() *ast.MapType {
798 defer un(trace(p, "MapType"))
801 pos := p.expect(token.MAP)
802 p.expect(token.LBRACK)
804 p.expect(token.RBRACK)
805 value := p.parseType()
807 return &ast.MapType{pos, key, value}
811 func (p *parser) parseChanType() *ast.ChanType {
813 defer un(trace(p, "ChanType"))
817 dir := ast.SEND | ast.RECV
818 if p.tok == token.CHAN {
820 if p.tok == token.ARROW {
825 p.expect(token.ARROW)
829 value := p.parseType()
831 return &ast.ChanType{pos, dir, value}
835 func (p *parser) tryRawType(ellipsisOk bool) ast.Expr {
838 return p.parseTypeName()
840 return p.parseArrayType(ellipsisOk)
842 return p.parseStructType()
844 return p.parsePointerType()
846 typ, _ := p.parseFuncType()
848 case token.INTERFACE:
849 return p.parseInterfaceType()
851 return p.parseMapType()
852 case token.CHAN, token.ARROW:
853 return p.parseChanType()
858 rparen := p.expect(token.RPAREN)
859 return &ast.ParenExpr{lparen, typ, rparen}
867 func (p *parser) tryType() ast.Expr { return p.tryRawType(false) }
870 // ----------------------------------------------------------------------------
873 func (p *parser) parseStmtList() (list []ast.Stmt) {
875 defer un(trace(p, "StatementList"))
878 for p.tok != token.CASE && p.tok != token.DEFAULT && p.tok != token.RBRACE && p.tok != token.EOF {
879 list = append(list, p.parseStmt())
886 func (p *parser) parseBody(scope *ast.Scope) *ast.BlockStmt {
888 defer un(trace(p, "Body"))
891 lbrace := p.expect(token.LBRACE)
892 p.topScope = scope // open function scope
894 list := p.parseStmtList()
897 rbrace := p.expect(token.RBRACE)
899 return &ast.BlockStmt{lbrace, list, rbrace}
903 func (p *parser) parseBlockStmt() *ast.BlockStmt {
905 defer un(trace(p, "BlockStmt"))
908 lbrace := p.expect(token.LBRACE)
910 list := p.parseStmtList()
912 rbrace := p.expect(token.RBRACE)
914 return &ast.BlockStmt{lbrace, list, rbrace}
918 // ----------------------------------------------------------------------------
921 func (p *parser) parseFuncTypeOrLit() ast.Expr {
923 defer un(trace(p, "FuncTypeOrLit"))
926 typ, scope := p.parseFuncType()
927 if p.tok != token.LBRACE {
928 // function type only
933 body := p.parseBody(scope)
936 return &ast.FuncLit{typ, body}
940 // parseOperand may return an expression or a raw type (incl. array
941 // types of the form [...]T. Callers must verify the result.
943 func (p *parser) parseOperand() ast.Expr {
945 defer un(trace(p, "Operand"))
950 ident := p.parseIdent()
954 case token.INT, token.FLOAT, token.IMAG, token.CHAR, token.STRING:
955 x := &ast.BasicLit{p.pos, p.tok, p.lit()}
965 rparen := p.expect(token.RPAREN)
966 return &ast.ParenExpr{lparen, x, rparen}
969 return p.parseFuncTypeOrLit()
972 t := p.tryRawType(true) // could be type for composite literal or conversion
979 p.errorExpected(pos, "operand")
980 p.next() // make progress
981 return &ast.BadExpr{pos, p.pos}
985 func (p *parser) parseSelectorOrTypeAssertion(x ast.Expr) ast.Expr {
987 defer un(trace(p, "SelectorOrTypeAssertion"))
990 p.expect(token.PERIOD)
991 if p.tok == token.IDENT {
993 sel := p.parseIdent()
994 return &ast.SelectorExpr{x, sel}
998 p.expect(token.LPAREN)
1000 if p.tok == token.TYPE {
1001 // type switch: typ == nil
1006 p.expect(token.RPAREN)
1008 return &ast.TypeAssertExpr{x, typ}
1012 func (p *parser) parseIndexOrSlice(x ast.Expr) ast.Expr {
1014 defer un(trace(p, "IndexOrSlice"))
1017 lbrack := p.expect(token.LBRACK)
1019 var low, high ast.Expr
1021 if p.tok != token.COLON {
1024 if p.tok == token.COLON {
1027 if p.tok != token.RBRACK {
1028 high = p.parseExpr()
1032 rbrack := p.expect(token.RBRACK)
1035 return &ast.SliceExpr{x, lbrack, low, high, rbrack}
1037 return &ast.IndexExpr{x, lbrack, low, rbrack}
1041 func (p *parser) parseCallOrConversion(fun ast.Expr) *ast.CallExpr {
1043 defer un(trace(p, "CallOrConversion"))
1046 lparen := p.expect(token.LPAREN)
1049 var ellipsis token.Pos
1050 for p.tok != token.RPAREN && p.tok != token.EOF && !ellipsis.IsValid() {
1051 list = append(list, p.parseExpr())
1052 if p.tok == token.ELLIPSIS {
1056 if p.tok != token.COMMA {
1062 rparen := p.expect(token.RPAREN)
1064 return &ast.CallExpr{fun, lparen, list, ellipsis, rparen}
1068 func (p *parser) parseElement(keyOk bool) ast.Expr {
1070 defer un(trace(p, "Element"))
1073 if p.tok == token.LBRACE {
1074 return p.parseLiteralValue(nil)
1078 if keyOk && p.tok == token.COLON {
1081 x = &ast.KeyValueExpr{x, colon, p.parseElement(false)}
1087 func (p *parser) parseElementList() (list []ast.Expr) {
1089 defer un(trace(p, "ElementList"))
1092 for p.tok != token.RBRACE && p.tok != token.EOF {
1093 list = append(list, p.parseElement(true))
1094 if p.tok != token.COMMA {
1104 func (p *parser) parseLiteralValue(typ ast.Expr) ast.Expr {
1106 defer un(trace(p, "LiteralValue"))
1109 lbrace := p.expect(token.LBRACE)
1112 if p.tok != token.RBRACE {
1113 elts = p.parseElementList()
1116 rbrace := p.expect(token.RBRACE)
1117 return &ast.CompositeLit{typ, lbrace, elts, rbrace}
1121 // checkExpr checks that x is an expression (and not a type).
1122 func (p *parser) checkExpr(x ast.Expr) ast.Expr {
1123 switch t := unparen(x).(type) {
1128 case *ast.CompositeLit:
1129 case *ast.ParenExpr:
1130 panic("unreachable")
1131 case *ast.SelectorExpr:
1132 case *ast.IndexExpr:
1133 case *ast.SliceExpr:
1134 case *ast.TypeAssertExpr:
1136 // the form X.(type) is only allowed in type switch expressions
1137 p.errorExpected(x.Pos(), "expression")
1138 x = &ast.BadExpr{x.Pos(), x.End()}
1142 case *ast.UnaryExpr:
1143 if t.Op == token.RANGE {
1144 // the range operator is only allowed at the top of a for statement
1145 p.errorExpected(x.Pos(), "expression")
1146 x = &ast.BadExpr{x.Pos(), x.End()}
1148 case *ast.BinaryExpr:
1150 // all other nodes are not proper expressions
1151 p.errorExpected(x.Pos(), "expression")
1152 x = &ast.BadExpr{x.Pos(), x.End()}
1158 // isTypeName returns true iff x is a (qualified) TypeName.
1159 func isTypeName(x ast.Expr) bool {
1160 switch t := x.(type) {
1163 case *ast.SelectorExpr:
1164 _, isIdent := t.X.(*ast.Ident)
1167 return false // all other nodes are not type names
1173 // isLiteralType returns true iff x is a legal composite literal type.
1174 func isLiteralType(x ast.Expr) bool {
1175 switch t := x.(type) {
1178 case *ast.SelectorExpr:
1179 _, isIdent := t.X.(*ast.Ident)
1181 case *ast.ArrayType:
1182 case *ast.StructType:
1185 return false // all other nodes are not legal composite literal types
1191 // If x is of the form *T, deref returns T, otherwise it returns x.
1192 func deref(x ast.Expr) ast.Expr {
1193 if p, isPtr := x.(*ast.StarExpr); isPtr {
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 {
1209 // checkExprOrType checks that x is an expression or a type
1210 // (and not a raw type such as [...]T).
1212 func (p *parser) checkExprOrType(x ast.Expr) ast.Expr {
1213 switch t := unparen(x).(type) {
1214 case *ast.ParenExpr:
1215 panic("unreachable")
1216 case *ast.UnaryExpr:
1217 if t.Op == token.RANGE {
1218 // the range operator is only allowed at the top of a for statement
1219 p.errorExpected(x.Pos(), "expression")
1220 x = &ast.BadExpr{x.Pos(), x.End()}
1222 case *ast.ArrayType:
1223 if len, isEllipsis := t.Len.(*ast.Ellipsis); isEllipsis {
1224 p.error(len.Pos(), "expected array length, found '...'")
1225 x = &ast.BadExpr{x.Pos(), x.End()}
1229 // all other nodes are expressions or types
1234 func (p *parser) parsePrimaryExpr() ast.Expr {
1236 defer un(trace(p, "PrimaryExpr"))
1239 x := p.parseOperand()
1244 x = p.parseSelectorOrTypeAssertion(p.checkExpr(x))
1246 x = p.parseIndexOrSlice(p.checkExpr(x))
1248 x = p.parseCallOrConversion(p.checkExprOrType(x))
1250 if isLiteralType(x) && (p.exprLev >= 0 || !isTypeName(x)) {
1251 x = p.parseLiteralValue(x)
1264 func (p *parser) parseUnaryExpr() ast.Expr {
1266 defer un(trace(p, "UnaryExpr"))
1270 case token.ADD, token.SUB, token.NOT, token.XOR, token.AND, token.RANGE:
1271 pos, op := p.pos, p.tok
1273 x := p.parseUnaryExpr()
1274 return &ast.UnaryExpr{pos, op, p.checkExpr(x)}
1277 // channel type or receive expression
1280 if p.tok == token.CHAN {
1282 value := p.parseType()
1283 return &ast.ChanType{pos, ast.RECV, value}
1286 x := p.parseUnaryExpr()
1287 return &ast.UnaryExpr{pos, token.ARROW, p.checkExpr(x)}
1290 // pointer type or unary "*" expression
1293 x := p.parseUnaryExpr()
1294 return &ast.StarExpr{pos, p.checkExprOrType(x)}
1297 return p.parsePrimaryExpr()
1301 func (p *parser) parseBinaryExpr(prec1 int) ast.Expr {
1303 defer un(trace(p, "BinaryExpr"))
1306 x := p.parseUnaryExpr()
1307 for prec := p.tok.Precedence(); prec >= prec1; prec-- {
1308 for p.tok.Precedence() == prec {
1309 pos, op := p.pos, p.tok
1311 y := p.parseBinaryExpr(prec + 1)
1312 x = &ast.BinaryExpr{p.checkExpr(x), pos, op, p.checkExpr(y)}
1320 // TODO(gri): parseExpr may return a type or even a raw type ([..]int) -
1321 // should reject when a type/raw type is obviously not allowed
1322 func (p *parser) parseExpr() ast.Expr {
1324 defer un(trace(p, "Expression"))
1327 return p.parseBinaryExpr(token.LowestPrec + 1)
1331 // ----------------------------------------------------------------------------
1334 func (p *parser) parseSimpleStmt(labelOk bool) ast.Stmt {
1336 defer un(trace(p, "SimpleStmt"))
1339 x := p.parseExprList()
1343 token.DEFINE, token.ASSIGN, token.ADD_ASSIGN,
1344 token.SUB_ASSIGN, token.MUL_ASSIGN, token.QUO_ASSIGN,
1345 token.REM_ASSIGN, token.AND_ASSIGN, token.OR_ASSIGN,
1346 token.XOR_ASSIGN, token.SHL_ASSIGN, token.SHR_ASSIGN, token.AND_NOT_ASSIGN:
1347 // assignment statement
1348 pos, tok := p.pos, p.tok
1350 y := p.parseExprList()
1351 if tok == token.DEFINE {
1352 p.shortVarDecl(p.makeIdentList(x))
1354 return &ast.AssignStmt{x, pos, tok, y}
1358 p.errorExpected(x[0].Pos(), "1 expression")
1359 // continue with first expression
1364 // labeled statement
1367 if label, isIdent := x[0].(*ast.Ident); labelOk && isIdent {
1368 // Go spec: The scope of a label is the body of the function
1369 // in which it is declared and excludes the body of any nested
1371 stmt := &ast.LabeledStmt{label, colon, p.parseStmt()}
1372 p.declare(stmt, p.labelScope, ast.Lbl, label)
1375 p.error(x[0].Pos(), "illegal label declaration")
1376 return &ast.BadStmt{x[0].Pos(), colon + 1}
1381 p.next() // consume "<-"
1383 return &ast.SendStmt{x[0], arrow, y}
1385 case token.INC, token.DEC:
1386 // increment or decrement
1387 s := &ast.IncDecStmt{x[0], p.pos, p.tok}
1388 p.next() // consume "++" or "--"
1393 return &ast.ExprStmt{x[0]}
1397 func (p *parser) parseCallExpr() *ast.CallExpr {
1399 if call, isCall := x.(*ast.CallExpr); isCall {
1402 p.errorExpected(x.Pos(), "function/method call")
1407 func (p *parser) parseGoStmt() ast.Stmt {
1409 defer un(trace(p, "GoStmt"))
1412 pos := p.expect(token.GO)
1413 call := p.parseCallExpr()
1416 return &ast.BadStmt{pos, pos + 2} // len("go")
1419 return &ast.GoStmt{pos, call}
1423 func (p *parser) parseDeferStmt() ast.Stmt {
1425 defer un(trace(p, "DeferStmt"))
1428 pos := p.expect(token.DEFER)
1429 call := p.parseCallExpr()
1432 return &ast.BadStmt{pos, pos + 5} // len("defer")
1435 return &ast.DeferStmt{pos, call}
1439 func (p *parser) parseReturnStmt() *ast.ReturnStmt {
1441 defer un(trace(p, "ReturnStmt"))
1445 p.expect(token.RETURN)
1447 if p.tok != token.SEMICOLON && p.tok != token.RBRACE {
1448 x = p.parseExprList()
1452 return &ast.ReturnStmt{pos, x}
1456 func (p *parser) parseBranchStmt(tok token.Token) *ast.BranchStmt {
1458 defer un(trace(p, "BranchStmt"))
1461 pos := p.expect(tok)
1462 var label *ast.Ident
1463 if tok != token.FALLTHROUGH && p.tok == token.IDENT {
1464 label = p.parseIdent()
1465 // add to list of unresolved targets
1466 n := len(p.targetStack) - 1
1467 p.targetStack[n] = append(p.targetStack[n], label)
1471 return &ast.BranchStmt{pos, tok, label}
1475 func (p *parser) makeExpr(s ast.Stmt) ast.Expr {
1479 if es, isExpr := s.(*ast.ExprStmt); isExpr {
1480 return p.checkExpr(es.X)
1482 p.error(s.Pos(), "expected condition, found simple statement")
1483 return &ast.BadExpr{s.Pos(), s.End()}
1487 func (p *parser) parseIfStmt() *ast.IfStmt {
1489 defer un(trace(p, "IfStmt"))
1492 pos := p.expect(token.IF)
1494 defer p.closeScope()
1499 prevLev := p.exprLev
1501 if p.tok == token.SEMICOLON {
1505 s = p.parseSimpleStmt(false)
1506 if p.tok == token.SEMICOLON {
1517 body := p.parseBlockStmt()
1519 if p.tok == token.ELSE {
1521 else_ = p.parseStmt()
1526 return &ast.IfStmt{pos, s, x, body, else_}
1530 func (p *parser) parseTypeList() (list []ast.Expr) {
1532 defer un(trace(p, "TypeList"))
1535 list = append(list, p.parseType())
1536 for p.tok == token.COMMA {
1538 list = append(list, p.parseType())
1545 func (p *parser) parseCaseClause(exprSwitch bool) *ast.CaseClause {
1547 defer un(trace(p, "CaseClause"))
1552 if p.tok == token.CASE {
1555 list = p.parseExprList()
1557 list = p.parseTypeList()
1560 p.expect(token.DEFAULT)
1563 colon := p.expect(token.COLON)
1565 body := p.parseStmtList()
1568 return &ast.CaseClause{pos, list, colon, body}
1572 func isExprSwitch(s ast.Stmt) bool {
1576 if e, ok := s.(*ast.ExprStmt); ok {
1577 if a, ok := e.X.(*ast.TypeAssertExpr); ok {
1578 return a.Type != nil // regular type assertion
1586 func (p *parser) parseSwitchStmt() ast.Stmt {
1588 defer un(trace(p, "SwitchStmt"))
1591 pos := p.expect(token.SWITCH)
1593 defer p.closeScope()
1596 if p.tok != token.LBRACE {
1597 prevLev := p.exprLev
1599 if p.tok != token.SEMICOLON {
1600 s2 = p.parseSimpleStmt(false)
1602 if p.tok == token.SEMICOLON {
1606 if p.tok != token.LBRACE {
1607 s2 = p.parseSimpleStmt(false)
1613 exprSwitch := isExprSwitch(s2)
1614 lbrace := p.expect(token.LBRACE)
1616 for p.tok == token.CASE || p.tok == token.DEFAULT {
1617 list = append(list, p.parseCaseClause(exprSwitch))
1619 rbrace := p.expect(token.RBRACE)
1621 body := &ast.BlockStmt{lbrace, list, rbrace}
1624 return &ast.SwitchStmt{pos, s1, p.makeExpr(s2), body}
1627 // TODO(gri): do all the checks!
1628 return &ast.TypeSwitchStmt{pos, s1, s2, body}
1632 func (p *parser) parseCommClause() *ast.CommClause {
1634 defer un(trace(p, "CommClause"))
1640 if p.tok == token.CASE {
1642 lhs := p.parseExprList()
1643 if p.tok == token.ARROW {
1646 p.errorExpected(lhs[0].Pos(), "1 expression")
1647 // continue with first expression
1651 rhs := p.parseExpr()
1652 comm = &ast.SendStmt{lhs[0], arrow, rhs}
1658 if tok == token.ASSIGN || tok == token.DEFINE {
1659 // RecvStmt with assignment
1661 p.errorExpected(lhs[0].Pos(), "1 or 2 expressions")
1662 // continue with first two expressions
1667 if tok == token.DEFINE {
1668 p.shortVarDecl(p.makeIdentList(lhs))
1671 // rhs must be single receive operation
1673 p.errorExpected(lhs[0].Pos(), "1 expression")
1674 // continue with first expression
1677 lhs = nil // there is no lhs
1679 if x, isUnary := rhs.(*ast.UnaryExpr); !isUnary || x.Op != token.ARROW {
1680 p.errorExpected(rhs.Pos(), "send or receive operation")
1681 rhs = &ast.BadExpr{rhs.Pos(), rhs.End()}
1684 comm = &ast.AssignStmt{lhs, pos, tok, []ast.Expr{rhs}}
1686 comm = &ast.ExprStmt{rhs}
1690 p.expect(token.DEFAULT)
1693 colon := p.expect(token.COLON)
1694 body := p.parseStmtList()
1697 return &ast.CommClause{pos, comm, colon, body}
1701 func (p *parser) parseSelectStmt() *ast.SelectStmt {
1703 defer un(trace(p, "SelectStmt"))
1706 pos := p.expect(token.SELECT)
1707 lbrace := p.expect(token.LBRACE)
1709 for p.tok == token.CASE || p.tok == token.DEFAULT {
1710 list = append(list, p.parseCommClause())
1712 rbrace := p.expect(token.RBRACE)
1714 body := &ast.BlockStmt{lbrace, list, rbrace}
1716 return &ast.SelectStmt{pos, body}
1720 func (p *parser) parseForStmt() ast.Stmt {
1722 defer un(trace(p, "ForStmt"))
1725 pos := p.expect(token.FOR)
1727 defer p.closeScope()
1729 var s1, s2, s3 ast.Stmt
1730 if p.tok != token.LBRACE {
1731 prevLev := p.exprLev
1733 if p.tok != token.SEMICOLON {
1734 s2 = p.parseSimpleStmt(false)
1736 if p.tok == token.SEMICOLON {
1740 if p.tok != token.SEMICOLON {
1741 s2 = p.parseSimpleStmt(false)
1744 if p.tok != token.LBRACE {
1745 s3 = p.parseSimpleStmt(false)
1751 body := p.parseBlockStmt()
1754 if as, isAssign := s2.(*ast.AssignStmt); isAssign {
1755 // possibly a for statement with a range clause; check assignment operator
1756 if as.Tok != token.ASSIGN && as.Tok != token.DEFINE {
1757 p.errorExpected(as.TokPos, "'=' or ':='")
1758 return &ast.BadStmt{pos, body.End()}
1761 var key, value ast.Expr
1762 switch len(as.Lhs) {
1764 key, value = as.Lhs[0], as.Lhs[1]
1768 p.errorExpected(as.Lhs[0].Pos(), "1 or 2 expressions")
1769 return &ast.BadStmt{pos, body.End()}
1772 if len(as.Rhs) != 1 {
1773 p.errorExpected(as.Rhs[0].Pos(), "1 expression")
1774 return &ast.BadStmt{pos, body.End()}
1776 if rhs, isUnary := as.Rhs[0].(*ast.UnaryExpr); isUnary && rhs.Op == token.RANGE {
1777 // rhs is range expression
1778 // (any short variable declaration was handled by parseSimpleStat above)
1779 return &ast.RangeStmt{pos, key, value, as.TokPos, as.Tok, rhs.X, body}
1781 p.errorExpected(s2.Pos(), "range clause")
1782 return &ast.BadStmt{pos, body.End()}
1785 // regular for statement
1786 return &ast.ForStmt{pos, s1, p.makeExpr(s2), s3, body}
1790 func (p *parser) parseStmt() (s ast.Stmt) {
1792 defer un(trace(p, "Statement"))
1796 case token.CONST, token.TYPE, token.VAR:
1797 s = &ast.DeclStmt{p.parseDecl()}
1799 // tokens that may start a top-level expression
1800 token.IDENT, token.INT, token.FLOAT, token.CHAR, token.STRING, token.FUNC, token.LPAREN, // operand
1801 token.LBRACK, token.STRUCT, // composite type
1802 token.MUL, token.AND, token.ARROW, token.ADD, token.SUB, token.XOR: // unary operators
1803 s = p.parseSimpleStmt(true)
1804 // because of the required look-ahead, labeled statements are
1805 // parsed by parseSimpleStmt - don't expect a semicolon after
1807 if _, isLabeledStmt := s.(*ast.LabeledStmt); !isLabeledStmt {
1813 s = p.parseDeferStmt()
1815 s = p.parseReturnStmt()
1816 case token.BREAK, token.CONTINUE, token.GOTO, token.FALLTHROUGH:
1817 s = p.parseBranchStmt(p.tok)
1819 s = p.parseBlockStmt()
1824 s = p.parseSwitchStmt()
1826 s = p.parseSelectStmt()
1828 s = p.parseForStmt()
1829 case token.SEMICOLON:
1830 s = &ast.EmptyStmt{p.pos}
1833 // a semicolon may be omitted before a closing "}"
1834 s = &ast.EmptyStmt{p.pos}
1836 // no statement found
1838 p.errorExpected(pos, "statement")
1839 p.next() // make progress
1840 s = &ast.BadStmt{pos, p.pos}
1847 // ----------------------------------------------------------------------------
1850 type parseSpecFunction func(p *parser, doc *ast.CommentGroup, iota int) ast.Spec
1853 func parseImportSpec(p *parser, doc *ast.CommentGroup, _ int) ast.Spec {
1855 defer un(trace(p, "ImportSpec"))
1858 var ident *ast.Ident
1861 ident = &ast.Ident{p.pos, ".", nil}
1864 ident = p.parseIdent()
1867 var path *ast.BasicLit
1868 if p.tok == token.STRING {
1869 path = &ast.BasicLit{p.pos, p.tok, p.lit()}
1872 p.expect(token.STRING) // use expect() error handling
1874 p.expectSemi() // call before accessing p.linecomment
1876 return &ast.ImportSpec{doc, ident, path, p.lineComment}
1880 func parseConstSpec(p *parser, doc *ast.CommentGroup, iota int) ast.Spec {
1882 defer un(trace(p, "ConstSpec"))
1885 idents := p.parseIdentList()
1887 var values []ast.Expr
1888 if typ != nil || p.tok == token.ASSIGN || iota == 0 {
1889 p.expect(token.ASSIGN)
1890 values = p.parseExprList()
1892 p.expectSemi() // call before accessing p.linecomment
1894 // Go spec: The scope of a constant or variable identifier declared inside
1895 // a function begins at the end of the ConstSpec or VarSpec and ends at
1896 // the end of the innermost containing block.
1897 // (Global identifiers are resolved in a separate phase after parsing.)
1898 spec := &ast.ValueSpec{doc, idents, typ, values, p.lineComment}
1899 p.declare(spec, p.topScope, ast.Con, idents...)
1905 func parseTypeSpec(p *parser, doc *ast.CommentGroup, _ int) ast.Spec {
1907 defer un(trace(p, "TypeSpec"))
1910 ident := p.parseIdent()
1911 typ := p.parseType()
1912 p.expectSemi() // call before accessing p.linecomment
1914 // Go spec: The scope of a type identifier declared inside a function begins
1915 // at the identifier in the TypeSpec and ends at the end of the innermost
1916 // containing block.
1917 // (Global identifiers are resolved in a separate phase after parsing.)
1918 spec := &ast.TypeSpec{doc, ident, typ, p.lineComment}
1919 p.declare(spec, p.topScope, ast.Typ, ident)
1925 func parseVarSpec(p *parser, doc *ast.CommentGroup, _ int) ast.Spec {
1927 defer un(trace(p, "VarSpec"))
1930 idents := p.parseIdentList()
1932 var values []ast.Expr
1933 if typ == nil || p.tok == token.ASSIGN {
1934 p.expect(token.ASSIGN)
1935 values = p.parseExprList()
1937 p.expectSemi() // call before accessing p.linecomment
1939 // Go spec: The scope of a constant or variable identifier declared inside
1940 // a function begins at the end of the ConstSpec or VarSpec and ends at
1941 // the end of the innermost containing block.
1942 // (Global identifiers are resolved in a separate phase after parsing.)
1943 spec := &ast.ValueSpec{doc, idents, typ, values, p.lineComment}
1944 p.declare(spec, p.topScope, ast.Var, idents...)
1950 func (p *parser) parseGenDecl(keyword token.Token, f parseSpecFunction) *ast.GenDecl {
1952 defer un(trace(p, "GenDecl("+keyword.String()+")"))
1955 doc := p.leadComment
1956 pos := p.expect(keyword)
1957 var lparen, rparen token.Pos
1959 if p.tok == token.LPAREN {
1962 for iota := 0; p.tok != token.RPAREN && p.tok != token.EOF; iota++ {
1963 list = append(list, f(p, p.leadComment, iota))
1965 rparen = p.expect(token.RPAREN)
1968 list = append(list, f(p, nil, 0))
1971 return &ast.GenDecl{doc, pos, keyword, lparen, list, rparen}
1975 func (p *parser) parseReceiver(scope *ast.Scope) *ast.FieldList {
1977 defer un(trace(p, "Receiver"))
1981 par := p.parseParameters(scope, false)
1983 // must have exactly one receiver
1984 if par.NumFields() != 1 {
1985 p.errorExpected(pos, "exactly one receiver")
1986 // TODO determine a better range for BadExpr below
1987 par.List = []*ast.Field{&ast.Field{Type: &ast.BadExpr{pos, pos}}}
1991 // recv type must be of the form ["*"] identifier
1993 base := deref(recv.Type)
1994 if _, isIdent := base.(*ast.Ident); !isIdent {
1995 p.errorExpected(base.Pos(), "(unqualified) identifier")
1996 par.List = []*ast.Field{&ast.Field{Type: &ast.BadExpr{recv.Pos(), recv.End()}}}
2003 func (p *parser) parseFuncDecl() *ast.FuncDecl {
2005 defer un(trace(p, "FunctionDecl"))
2008 doc := p.leadComment
2009 pos := p.expect(token.FUNC)
2010 scope := ast.NewScope(p.topScope) // function scope
2012 var recv *ast.FieldList
2013 if p.tok == token.LPAREN {
2014 recv = p.parseReceiver(scope)
2017 ident := p.parseIdent()
2019 params, results := p.parseSignature(scope)
2021 var body *ast.BlockStmt
2022 if p.tok == token.LBRACE {
2023 body = p.parseBody(scope)
2027 decl := &ast.FuncDecl{doc, recv, ident, &ast.FuncType{pos, params, results}, body}
2029 // Go spec: The scope of an identifier denoting a constant, type,
2030 // variable, or function (but not method) declared at top level
2031 // (outside any function) is the package block.
2033 // init() functions cannot be referred to and there may
2034 // be more than one - don't put them in the pkgScope
2035 if ident.Name != "init" {
2036 p.declare(decl, p.pkgScope, ast.Fun, ident)
2044 func (p *parser) parseDecl() ast.Decl {
2046 defer un(trace(p, "Declaration"))
2049 var f parseSpecFunction
2061 return p.parseFuncDecl()
2065 p.errorExpected(pos, "declaration")
2066 p.next() // make progress
2067 decl := &ast.BadDecl{pos, p.pos}
2071 return p.parseGenDecl(p.tok, f)
2075 func (p *parser) parseDeclList() (list []ast.Decl) {
2077 defer un(trace(p, "DeclList"))
2080 for p.tok != token.EOF {
2081 list = append(list, p.parseDecl())
2088 // ----------------------------------------------------------------------------
2091 func (p *parser) parseFile() *ast.File {
2093 defer un(trace(p, "File"))
2097 doc := p.leadComment
2098 pos := p.expect(token.PACKAGE)
2099 // Go spec: The package clause is not a declaration;
2100 // the package name does not appear in any scope.
2101 ident := p.parseIdent()
2104 var decls []ast.Decl
2106 // Don't bother parsing the rest if we had errors already.
2107 // Likely not a Go source file at all.
2109 if p.ErrorCount() == 0 && p.mode&PackageClauseOnly == 0 {
2111 for p.tok == token.IMPORT {
2112 decls = append(decls, p.parseGenDecl(token.IMPORT, parseImportSpec))
2115 if p.mode&ImportsOnly == 0 {
2116 // rest of package body
2117 for p.tok != token.EOF {
2118 decls = append(decls, p.parseDecl())
2123 if p.topScope != p.pkgScope {
2124 panic("internal error: imbalanced scopes")
2127 // resolve global identifiers within the same file
2129 for _, ident := range p.unresolved {
2130 // i <= index for current ident
2131 ident.Obj = p.pkgScope.Lookup(ident.Name)
2132 if ident.Obj == nil {
2133 p.unresolved[i] = ident
2138 return &ast.File{doc, pos, ident, decls, p.pkgScope, p.unresolved[0:i], p.comments}