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 // 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.
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.
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
32 // The parser structure holds the parser's internal state.
36 scanner scanner.Scanner
39 mode uint // parsing mode
40 trace bool // == (mode & Trace != 0)
41 indent uint // indentation used for tracing output
44 comments []*ast.CommentGroup
45 leadComment *ast.CommentGroup // last lead comment
46 lineComment *ast.CommentGroup // last line comment
49 pos token.Pos // token position
50 tok token.Token // one token look-ahead
51 lit string // token literal
53 // Non-syntactic parser control
54 exprLev int // < 0: in control clause, >= 0: in expression
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
63 // (maintained by open/close LabelScope)
64 labelScope *ast.Scope // label scope for current function
65 targetStack [][]*ast.Ident // stack of unresolved labels
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
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))
82 p.trace = mode&Trace != 0 // for convenience (p.trace is used frequently)
86 // set up the pkgScope here (as opposed to in parseFile) because
87 // there are other parser entry points (ParseExpr, etc.)
89 p.pkgScope = p.topScope
91 // for the same reason, set up a label scope
95 // ----------------------------------------------------------------------------
98 func (p *parser) openScope() {
99 p.topScope = ast.NewScope(p.topScope)
102 func (p *parser) closeScope() {
103 p.topScope = p.topScope.Outer
106 func (p *parser) openLabelScope() {
107 p.labelScope = ast.NewScope(p.labelScope)
108 p.targetStack = append(p.targetStack, nil)
111 func (p *parser) closeLabelScope() {
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))
122 p.targetStack = p.targetStack[0:n]
123 p.labelScope = p.labelScope.Outer
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
135 if ident.Name != "_" {
136 if alt := scope.Insert(obj); alt != nil && p.mode&DeclarationErrors != 0 {
138 if pos := alt.Pos(); pos.IsValid() {
139 prevDecl = fmt.Sprintf("\n\tprevious declaration at %s", p.file.Position(pos))
141 p.error(ident.Pos(), fmt.Sprintf("%s redeclared in this block%s", ident.Name, prevDecl))
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
159 if ident.Name != "_" {
160 if alt := p.topScope.Insert(obj); alt != nil {
161 ident.Obj = alt // redeclaration
163 n++ // new declaration
167 if n == 0 && p.mode&DeclarationErrors != 0 {
168 p.error(idents[0].Pos(), "no new variables on left side of :=")
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)
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)
183 assert(ident.Obj == nil, "identifier already declared or resolved")
184 if ident.Name == "_" {
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 {
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)
202 // ----------------------------------------------------------------------------
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)
212 for ; i > n; i -= n {
219 func trace(p *parser, msg string) *parser {
220 p.printTrace(msg, "(")
225 // Usage pattern: defer un(trace(p, "..."));
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() {
240 case p.tok.IsLiteral():
241 p.printTrace(s, p.lit)
242 case p.tok.IsOperator(), p.tok.IsKeyword():
243 p.printTrace("\"" + s + "\"")
249 p.pos, p.tok, p.lit = p.scanner.Scan()
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)
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' {
266 comment = &ast.Comment{p.pos, p.lit}
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.
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)
286 // add comment group to the comments list
287 comments = &ast.CommentGroup{list}
288 p.comments = append(p.comments, comments)
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.
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.
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
305 // Lead and line comments may be considered documentation that is
306 // stored in the AST.
308 func (p *parser) next() {
311 line := p.file.Line(p.pos) // current line
314 if p.tok == token.COMMENT {
315 var comment *ast.CommentGroup
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
329 // consume successor comments, if any
331 for p.tok == token.COMMENT {
332 comment, endline = p.consumeCommentGroup()
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
343 func (p *parser) error(pos token.Pos, msg string) {
344 p.Error(p.file.Position(pos), msg)
347 func (p *parser) errorExpected(pos token.Pos, msg string) {
348 msg = "expected " + msg
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"
355 msg += ", found '" + p.tok.String() + "'"
356 if p.tok.IsLiteral() {
364 func (p *parser) expect(tok token.Token) token.Pos {
367 p.errorExpected(pos, "'"+tok.String()+"'")
369 p.next() // make progress
373 func (p *parser) expectSemi() {
374 if p.tok != token.RPAREN && p.tok != token.RBRACE {
375 p.expect(token.SEMICOLON)
379 func assert(cond bool, msg string) {
381 panic("go/parser internal error: " + msg)
385 // ----------------------------------------------------------------------------
388 func (p *parser) parseIdent() *ast.Ident {
391 if p.tok == token.IDENT {
395 p.expect(token.IDENT) // use expect() error handling
397 return &ast.Ident{pos, name, nil}
400 func (p *parser) parseIdentList() (list []*ast.Ident) {
402 defer un(trace(p, "IdentList"))
405 list = append(list, p.parseIdent())
406 for p.tok == token.COMMA {
408 list = append(list, p.parseIdent())
414 // ----------------------------------------------------------------------------
415 // Common productions
417 // If lhs is set, result list elements which are identifiers are not resolved.
418 func (p *parser) parseExprList(lhs bool) (list []ast.Expr) {
420 defer un(trace(p, "ExpressionList"))
423 list = append(list, p.checkExpr(p.parseExpr(lhs)))
424 for p.tok == token.COMMA {
426 list = append(list, p.checkExpr(p.parseExpr(lhs)))
432 func (p *parser) parseLhsList() []ast.Expr {
433 list := p.parseExprList(true)
436 // lhs of a short variable declaration
437 p.shortVarDecl(p.makeIdentList(list))
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
447 // identifiers must be declared elsewhere
448 for _, x := range list {
455 func (p *parser) parseRhsList() []ast.Expr {
456 return p.parseExprList(false)
459 // ----------------------------------------------------------------------------
462 func (p *parser) parseType() ast.Expr {
464 defer un(trace(p, "Type"))
471 p.errorExpected(pos, "type")
472 p.next() // make progress
473 return &ast.BadExpr{pos, p.pos}
479 // If the result is an identifier, it is not resolved.
480 func (p *parser) parseTypeName() ast.Expr {
482 defer un(trace(p, "TypeName"))
485 ident := p.parseIdent()
486 // don't resolve ident yet - it may be a parameter or field name
488 if p.tok == token.PERIOD {
489 // ident is a package name
492 sel := p.parseIdent()
493 return &ast.SelectorExpr{ident, sel}
499 func (p *parser) parseArrayType(ellipsisOk bool) ast.Expr {
501 defer un(trace(p, "ArrayType"))
504 lbrack := p.expect(token.LBRACK)
506 if ellipsisOk && p.tok == token.ELLIPSIS {
507 len = &ast.Ellipsis{p.pos, nil}
509 } else if p.tok != token.RBRACK {
512 p.expect(token.RBRACK)
515 return &ast.ArrayType{lbrack, len, elt}
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)
523 pos := x.(ast.Expr).Pos()
524 p.errorExpected(pos, "identifier")
525 ident = &ast.Ident{pos, "_", nil}
532 func (p *parser) parseFieldDecl(scope *ast.Scope) *ast.Field {
534 defer un(trace(p, "FieldDecl"))
540 list, typ := p.parseVarList(false)
543 var tag *ast.BasicLit
544 if p.tok == token.STRING {
545 tag = &ast.BasicLit{p.pos, p.tok, p.lit}
550 var idents []*ast.Ident
552 // IdentifierList Type
553 idents = p.makeIdentList(list)
555 // ["*"] TypeName (AnonymousField)
556 typ = list[0] // we always have at least one element
558 if n := len(list); n > 1 || !isTypeName(deref(typ)) {
560 p.errorExpected(pos, "anonymous field")
561 typ = &ast.BadExpr{pos, list[n-1].End()}
565 p.expectSemi() // call before accessing p.linecomment
567 field := &ast.Field{doc, idents, typ, tag, p.lineComment}
568 p.declare(field, nil, scope, ast.Var, idents...)
573 func (p *parser) parseStructType() *ast.StructType {
575 defer un(trace(p, "StructType"))
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))
588 rbrace := p.expect(token.RBRACE)
590 return &ast.StructType{pos, &ast.FieldList{lbrace, list, rbrace}, false}
593 func (p *parser) parsePointerType() *ast.StarExpr {
595 defer un(trace(p, "PointerType"))
598 star := p.expect(token.MUL)
599 base := p.parseType()
601 return &ast.StarExpr{star, base}
604 func (p *parser) tryVarType(isParam bool) ast.Expr {
605 if isParam && p.tok == token.ELLIPSIS {
608 typ := p.tryIdentOrType(isParam) // don't use parseType so we can provide better error message
610 p.error(pos, "'...' parameter is missing type")
611 typ = &ast.BadExpr{pos, p.pos}
613 return &ast.Ellipsis{pos, typ}
615 return p.tryIdentOrType(false)
618 func (p *parser) parseVarType(isParam bool) ast.Expr {
619 typ := p.tryVarType(isParam)
622 p.errorExpected(pos, "type")
623 p.next() // make progress
624 typ = &ast.BadExpr{pos, p.pos}
629 func (p *parser) parseVarList(isParam bool) (list []ast.Expr, typ ast.Expr) {
631 defer un(trace(p, "VarList"))
634 // a list of identifiers looks like a list of type names
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 {
645 typ = p.tryVarType(isParam) // maybe nil as in: func f(int,) {}
648 // if we had a list of identifiers, it must be followed by a type
649 if typ = p.tryVarType(isParam); typ != nil {
656 func (p *parser) parseParameterList(scope *ast.Scope, ellipsisOk bool) (params []*ast.Field) {
658 defer un(trace(p, "ParameterList"))
661 list, typ := p.parseVarList(ellipsisOk)
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 {
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 {
689 // Type { "," Type } (anonymous parameters)
690 params = make([]*ast.Field, len(list))
691 for i, x := range list {
693 params[i] = &ast.Field{Type: x}
700 func (p *parser) parseParameters(scope *ast.Scope, ellipsisOk bool) *ast.FieldList {
702 defer un(trace(p, "Parameters"))
705 var params []*ast.Field
706 lparen := p.expect(token.LPAREN)
707 if p.tok != token.RPAREN {
708 params = p.parseParameterList(scope, ellipsisOk)
710 rparen := p.expect(token.RPAREN)
712 return &ast.FieldList{lparen, params, rparen}
715 func (p *parser) parseResult(scope *ast.Scope) *ast.FieldList {
717 defer un(trace(p, "Result"))
720 if p.tok == token.LPAREN {
721 return p.parseParameters(scope, false)
726 list := make([]*ast.Field, 1)
727 list[0] = &ast.Field{Type: typ}
728 return &ast.FieldList{List: list}
734 func (p *parser) parseSignature(scope *ast.Scope) (params, results *ast.FieldList) {
736 defer un(trace(p, "Signature"))
739 params = p.parseParameters(scope, true)
740 results = p.parseResult(scope)
745 func (p *parser) parseFuncType() (*ast.FuncType, *ast.Scope) {
747 defer un(trace(p, "FuncType"))
750 pos := p.expect(token.FUNC)
751 scope := ast.NewScope(p.topScope) // function scope
752 params, results := p.parseSignature(scope)
754 return &ast.FuncType{pos, params, results}, scope
757 func (p *parser) parseMethodSpec(scope *ast.Scope) *ast.Field {
759 defer un(trace(p, "MethodSpec"))
763 var idents []*ast.Ident
765 x := p.parseTypeName()
766 if ident, isIdent := x.(*ast.Ident); isIdent && p.tok == token.LPAREN {
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}
773 // embedded interface
777 p.expectSemi() // call before accessing p.linecomment
779 spec := &ast.Field{doc, idents, typ, nil, p.lineComment}
780 p.declare(spec, nil, scope, ast.Fun, idents...)
785 func (p *parser) parseInterfaceType() *ast.InterfaceType {
787 defer un(trace(p, "InterfaceType"))
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))
797 rbrace := p.expect(token.RBRACE)
799 return &ast.InterfaceType{pos, &ast.FieldList{lbrace, list, rbrace}, false}
802 func (p *parser) parseMapType() *ast.MapType {
804 defer un(trace(p, "MapType"))
807 pos := p.expect(token.MAP)
808 p.expect(token.LBRACK)
810 p.expect(token.RBRACK)
811 value := p.parseType()
813 return &ast.MapType{pos, key, value}
816 func (p *parser) parseChanType() *ast.ChanType {
818 defer un(trace(p, "ChanType"))
822 dir := ast.SEND | ast.RECV
823 if p.tok == token.CHAN {
825 if p.tok == token.ARROW {
830 p.expect(token.ARROW)
834 value := p.parseType()
836 return &ast.ChanType{pos, dir, value}
839 // If the result is an identifier, it is not resolved.
840 func (p *parser) tryIdentOrType(ellipsisOk bool) ast.Expr {
843 return p.parseTypeName()
845 return p.parseArrayType(ellipsisOk)
847 return p.parseStructType()
849 return p.parsePointerType()
851 typ, _ := p.parseFuncType()
853 case token.INTERFACE:
854 return p.parseInterfaceType()
856 return p.parseMapType()
857 case token.CHAN, token.ARROW:
858 return p.parseChanType()
863 rparen := p.expect(token.RPAREN)
864 return &ast.ParenExpr{lparen, typ, rparen}
871 func (p *parser) tryType() ast.Expr {
872 typ := p.tryIdentOrType(false)
879 // ----------------------------------------------------------------------------
882 func (p *parser) parseStmtList() (list []ast.Stmt) {
884 defer un(trace(p, "StatementList"))
887 for p.tok != token.CASE && p.tok != token.DEFAULT && p.tok != token.RBRACE && p.tok != token.EOF {
888 list = append(list, p.parseStmt())
894 func (p *parser) parseBody(scope *ast.Scope) *ast.BlockStmt {
896 defer un(trace(p, "Body"))
899 lbrace := p.expect(token.LBRACE)
900 p.topScope = scope // open function scope
902 list := p.parseStmtList()
905 rbrace := p.expect(token.RBRACE)
907 return &ast.BlockStmt{lbrace, list, rbrace}
910 func (p *parser) parseBlockStmt() *ast.BlockStmt {
912 defer un(trace(p, "BlockStmt"))
915 lbrace := p.expect(token.LBRACE)
917 list := p.parseStmtList()
919 rbrace := p.expect(token.RBRACE)
921 return &ast.BlockStmt{lbrace, list, rbrace}
924 // ----------------------------------------------------------------------------
927 func (p *parser) parseFuncTypeOrLit() ast.Expr {
929 defer un(trace(p, "FuncTypeOrLit"))
932 typ, scope := p.parseFuncType()
933 if p.tok != token.LBRACE {
934 // function type only
939 body := p.parseBody(scope)
942 return &ast.FuncLit{typ, body}
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.
949 func (p *parser) parseOperand(lhs bool) ast.Expr {
951 defer un(trace(p, "Operand"))
962 case token.INT, token.FLOAT, token.IMAG, token.CHAR, token.STRING:
963 x := &ast.BasicLit{p.pos, p.tok, p.lit}
971 x := p.parseRhsOrType() // types may be parenthesized: (some type)
973 rparen := p.expect(token.RPAREN)
974 return &ast.ParenExpr{lparen, x, rparen}
977 return p.parseFuncTypeOrLit()
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")
989 p.errorExpected(pos, "operand")
990 p.next() // make progress
991 return &ast.BadExpr{pos, p.pos}
994 func (p *parser) parseSelector(x ast.Expr) ast.Expr {
996 defer un(trace(p, "Selector"))
999 sel := p.parseIdent()
1001 return &ast.SelectorExpr{x, sel}
1004 func (p *parser) parseTypeAssertion(x ast.Expr) ast.Expr {
1006 defer un(trace(p, "TypeAssertion"))
1009 p.expect(token.LPAREN)
1011 if p.tok == token.TYPE {
1012 // type switch: typ == nil
1017 p.expect(token.RPAREN)
1019 return &ast.TypeAssertExpr{x, typ}
1022 func (p *parser) parseIndexOrSlice(x ast.Expr) ast.Expr {
1024 defer un(trace(p, "IndexOrSlice"))
1027 lbrack := p.expect(token.LBRACK)
1029 var low, high ast.Expr
1031 if p.tok != token.COLON {
1034 if p.tok == token.COLON {
1037 if p.tok != token.RBRACK {
1042 rbrack := p.expect(token.RBRACK)
1045 return &ast.SliceExpr{x, lbrack, low, high, rbrack}
1047 return &ast.IndexExpr{x, lbrack, low, rbrack}
1050 func (p *parser) parseCallOrConversion(fun ast.Expr) *ast.CallExpr {
1052 defer un(trace(p, "CallOrConversion"))
1055 lparen := p.expect(token.LPAREN)
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 {
1065 if p.tok != token.COMMA {
1071 rparen := p.expect(token.RPAREN)
1073 return &ast.CallExpr{fun, lparen, list, ellipsis, rparen}
1076 func (p *parser) parseElement(keyOk bool) ast.Expr {
1078 defer un(trace(p, "Element"))
1081 if p.tok == token.LBRACE {
1082 return p.parseLiteralValue(nil)
1085 x := p.checkExpr(p.parseExpr(keyOk)) // don't resolve if map key
1087 if p.tok == token.COLON {
1090 return &ast.KeyValueExpr{x, colon, p.parseElement(false)}
1092 p.resolve(x) // not a map key
1098 func (p *parser) parseElementList() (list []ast.Expr) {
1100 defer un(trace(p, "ElementList"))
1103 for p.tok != token.RBRACE && p.tok != token.EOF {
1104 list = append(list, p.parseElement(true))
1105 if p.tok != token.COMMA {
1114 func (p *parser) parseLiteralValue(typ ast.Expr) ast.Expr {
1116 defer un(trace(p, "LiteralValue"))
1119 lbrace := p.expect(token.LBRACE)
1122 if p.tok != token.RBRACE {
1123 elts = p.parseElementList()
1126 rbrace := p.expect(token.RBRACE)
1127 return &ast.CompositeLit{typ, lbrace, elts, rbrace}
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) {
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
1151 case *ast.UnaryExpr:
1152 case *ast.BinaryExpr:
1154 // all other nodes are not proper expressions
1155 p.errorExpected(x.Pos(), "expression")
1156 x = &ast.BadExpr{x.Pos(), x.End()}
1161 // isTypeName returns true iff x is a (qualified) TypeName.
1162 func isTypeName(x ast.Expr) bool {
1163 switch t := x.(type) {
1166 case *ast.SelectorExpr:
1167 _, isIdent := t.X.(*ast.Ident)
1170 return false // all other nodes are not type names
1175 // isLiteralType returns true iff x is a legal composite literal type.
1176 func isLiteralType(x ast.Expr) bool {
1177 switch t := x.(type) {
1180 case *ast.SelectorExpr:
1181 _, isIdent := t.X.(*ast.Ident)
1183 case *ast.ArrayType:
1184 case *ast.StructType:
1187 return false // all other nodes are not legal composite literal types
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 {
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 {
1208 // checkExprOrType checks that x is an expression or a type
1209 // (and not a raw type such as [...]T).
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()}
1223 // all other nodes are expressions or types
1227 // If lhs is set and the result is an identifier, it is not resolved.
1228 func (p *parser) parsePrimaryExpr(lhs bool) ast.Expr {
1230 defer un(trace(p, "PrimaryExpr"))
1233 x := p.parseOperand(lhs)
1244 x = p.parseSelector(p.checkExpr(x))
1246 x = p.parseTypeAssertion(p.checkExpr(x))
1249 p.next() // make progress
1250 p.errorExpected(pos, "selector or type assertion")
1251 x = &ast.BadExpr{pos, p.pos}
1257 x = p.parseIndexOrSlice(p.checkExpr(x))
1262 x = p.parseCallOrConversion(p.checkExprOrType(x))
1264 if isLiteralType(x) && (p.exprLev >= 0 || !isTypeName(x)) {
1268 x = p.parseLiteralValue(x)
1275 lhs = false // no need to try to resolve again
1281 // If lhs is set and the result is an identifier, it is not resolved.
1282 func (p *parser) parseUnaryExpr(lhs bool) ast.Expr {
1284 defer un(trace(p, "UnaryExpr"))
1288 case token.ADD, token.SUB, token.NOT, token.XOR, token.AND:
1289 pos, op := p.pos, p.tok
1291 x := p.parseUnaryExpr(false)
1292 return &ast.UnaryExpr{pos, op, p.checkExpr(x)}
1295 // channel type or receive expression
1298 if p.tok == token.CHAN {
1300 value := p.parseType()
1301 return &ast.ChanType{pos, ast.RECV, value}
1304 x := p.parseUnaryExpr(false)
1305 return &ast.UnaryExpr{pos, token.ARROW, p.checkExpr(x)}
1308 // pointer type or unary "*" expression
1311 x := p.parseUnaryExpr(false)
1312 return &ast.StarExpr{pos, p.checkExprOrType(x)}
1315 return p.parsePrimaryExpr(lhs)
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 {
1321 defer un(trace(p, "BinaryExpr"))
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
1333 y := p.parseBinaryExpr(false, prec+1)
1334 x = &ast.BinaryExpr{p.checkExpr(x), pos, op, p.checkExpr(y)}
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
1345 func (p *parser) parseExpr(lhs bool) ast.Expr {
1347 defer un(trace(p, "Expression"))
1350 return p.parseBinaryExpr(lhs, token.LowestPrec+1)
1353 func (p *parser) parseRhs() ast.Expr {
1354 return p.checkExpr(p.parseExpr(false))
1357 func (p *parser) parseRhsOrType() ast.Expr {
1358 return p.checkExprOrType(p.parseExpr(false))
1361 // ----------------------------------------------------------------------------
1364 // Parsing modes for parseSimpleStmt.
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) {
1377 defer un(trace(p, "SimpleStmt"))
1380 x := p.parseLhsList()
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
1393 if mode == rangeOk && p.tok == token.RANGE && (tok == token.DEFINE || tok == token.ASSIGN) {
1396 y = []ast.Expr{&ast.UnaryExpr{pos, token.RANGE, p.parseRhs()}}
1399 y = p.parseRhsList()
1401 return &ast.AssignStmt{x, pos, tok, y}, isRange
1405 p.errorExpected(x[0].Pos(), "1 expression")
1406 // continue with first expression
1411 // labeled statement
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
1418 stmt := &ast.LabeledStmt{label, colon, p.parseStmt()}
1419 p.declare(stmt, nil, p.labelScope, ast.Lbl, label)
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
1436 return &ast.SendStmt{x[0], arrow, y}, false
1438 case token.INC, token.DEC:
1439 // increment or decrement
1440 s := &ast.IncDecStmt{x[0], p.pos, p.tok}
1446 return &ast.ExprStmt{x[0]}, false
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 {
1454 p.errorExpected(x.Pos(), "function/method call")
1458 func (p *parser) parseGoStmt() ast.Stmt {
1460 defer un(trace(p, "GoStmt"))
1463 pos := p.expect(token.GO)
1464 call := p.parseCallExpr()
1467 return &ast.BadStmt{pos, pos + 2} // len("go")
1470 return &ast.GoStmt{pos, call}
1473 func (p *parser) parseDeferStmt() ast.Stmt {
1475 defer un(trace(p, "DeferStmt"))
1478 pos := p.expect(token.DEFER)
1479 call := p.parseCallExpr()
1482 return &ast.BadStmt{pos, pos + 5} // len("defer")
1485 return &ast.DeferStmt{pos, call}
1488 func (p *parser) parseReturnStmt() *ast.ReturnStmt {
1490 defer un(trace(p, "ReturnStmt"))
1494 p.expect(token.RETURN)
1496 if p.tok != token.SEMICOLON && p.tok != token.RBRACE {
1497 x = p.parseRhsList()
1501 return &ast.ReturnStmt{pos, x}
1504 func (p *parser) parseBranchStmt(tok token.Token) *ast.BranchStmt {
1506 defer un(trace(p, "BranchStmt"))
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)
1519 return &ast.BranchStmt{pos, tok, label}
1522 func (p *parser) makeExpr(s ast.Stmt) ast.Expr {
1526 if es, isExpr := s.(*ast.ExprStmt); isExpr {
1527 return p.checkExpr(es.X)
1529 p.error(s.Pos(), "expected condition, found simple statement")
1530 return &ast.BadExpr{s.Pos(), s.End()}
1533 func (p *parser) parseIfStmt() *ast.IfStmt {
1535 defer un(trace(p, "IfStmt"))
1538 pos := p.expect(token.IF)
1540 defer p.closeScope()
1545 prevLev := p.exprLev
1547 if p.tok == token.SEMICOLON {
1551 s, _ = p.parseSimpleStmt(basic)
1552 if p.tok == token.SEMICOLON {
1563 body := p.parseBlockStmt()
1565 if p.tok == token.ELSE {
1567 else_ = p.parseStmt()
1572 return &ast.IfStmt{pos, s, x, body, else_}
1575 func (p *parser) parseTypeList() (list []ast.Expr) {
1577 defer un(trace(p, "TypeList"))
1580 list = append(list, p.parseType())
1581 for p.tok == token.COMMA {
1583 list = append(list, p.parseType())
1589 func (p *parser) parseCaseClause(typeSwitch bool) *ast.CaseClause {
1591 defer un(trace(p, "CaseClause"))
1596 if p.tok == token.CASE {
1599 list = p.parseTypeList()
1601 list = p.parseRhsList()
1604 p.expect(token.DEFAULT)
1607 colon := p.expect(token.COLON)
1609 body := p.parseStmtList()
1612 return &ast.CaseClause{pos, list, colon, body}
1615 func isTypeSwitchAssert(x ast.Expr) bool {
1616 a, ok := x.(*ast.TypeAssertExpr)
1617 return ok && a.Type == nil
1620 func isTypeSwitchGuard(s ast.Stmt) bool {
1621 switch t := s.(type) {
1624 return isTypeSwitchAssert(t.X)
1625 case *ast.AssignStmt:
1627 return len(t.Lhs) == 1 && t.Tok == token.DEFINE && len(t.Rhs) == 1 && isTypeSwitchAssert(t.Rhs[0])
1632 func (p *parser) parseSwitchStmt() ast.Stmt {
1634 defer un(trace(p, "SwitchStmt"))
1637 pos := p.expect(token.SWITCH)
1639 defer p.closeScope()
1642 if p.tok != token.LBRACE {
1643 prevLev := p.exprLev
1645 if p.tok != token.SEMICOLON {
1646 s2, _ = p.parseSimpleStmt(basic)
1648 if p.tok == token.SEMICOLON {
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:
1657 // switch t := 0; t := x.(T) { ... }
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).
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.
1666 defer p.closeScope()
1667 s2, _ = p.parseSimpleStmt(basic)
1673 typeSwitch := isTypeSwitchGuard(s2)
1674 lbrace := p.expect(token.LBRACE)
1676 for p.tok == token.CASE || p.tok == token.DEFAULT {
1677 list = append(list, p.parseCaseClause(typeSwitch))
1679 rbrace := p.expect(token.RBRACE)
1681 body := &ast.BlockStmt{lbrace, list, rbrace}
1684 return &ast.TypeSwitchStmt{pos, s1, s2, body}
1687 return &ast.SwitchStmt{pos, s1, p.makeExpr(s2), body}
1690 func (p *parser) parseCommClause() *ast.CommClause {
1692 defer un(trace(p, "CommClause"))
1698 if p.tok == token.CASE {
1700 lhs := p.parseLhsList()
1701 if p.tok == token.ARROW {
1704 p.errorExpected(lhs[0].Pos(), "1 expression")
1705 // continue with first expression
1710 comm = &ast.SendStmt{lhs[0], arrow, rhs}
1716 if tok == token.ASSIGN || tok == token.DEFINE {
1717 // RecvStmt with assignment
1719 p.errorExpected(lhs[0].Pos(), "1 or 2 expressions")
1720 // continue with first two expressions
1726 // rhs must be single receive operation
1728 p.errorExpected(lhs[0].Pos(), "1 expression")
1729 // continue with first expression
1732 lhs = nil // there is no lhs
1735 comm = &ast.AssignStmt{lhs, pos, tok, []ast.Expr{rhs}}
1737 comm = &ast.ExprStmt{rhs}
1741 p.expect(token.DEFAULT)
1744 colon := p.expect(token.COLON)
1745 body := p.parseStmtList()
1748 return &ast.CommClause{pos, comm, colon, body}
1751 func (p *parser) parseSelectStmt() *ast.SelectStmt {
1753 defer un(trace(p, "SelectStmt"))
1756 pos := p.expect(token.SELECT)
1757 lbrace := p.expect(token.LBRACE)
1759 for p.tok == token.CASE || p.tok == token.DEFAULT {
1760 list = append(list, p.parseCommClause())
1762 rbrace := p.expect(token.RBRACE)
1764 body := &ast.BlockStmt{lbrace, list, rbrace}
1766 return &ast.SelectStmt{pos, body}
1769 func (p *parser) parseForStmt() ast.Stmt {
1771 defer un(trace(p, "ForStmt"))
1774 pos := p.expect(token.FOR)
1776 defer p.closeScope()
1778 var s1, s2, s3 ast.Stmt
1780 if p.tok != token.LBRACE {
1781 prevLev := p.exprLev
1783 if p.tok != token.SEMICOLON {
1784 s2, isRange = p.parseSimpleStmt(rangeOk)
1786 if !isRange && p.tok == token.SEMICOLON {
1790 if p.tok != token.SEMICOLON {
1791 s2, _ = p.parseSimpleStmt(basic)
1794 if p.tok != token.LBRACE {
1795 s3, _ = p.parseSimpleStmt(basic)
1801 body := p.parseBlockStmt()
1805 as := s2.(*ast.AssignStmt)
1807 var key, value ast.Expr
1808 switch len(as.Lhs) {
1810 key, value = as.Lhs[0], as.Lhs[1]
1814 p.errorExpected(as.Lhs[0].Pos(), "1 or 2 expressions")
1815 return &ast.BadStmt{pos, body.End()}
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}
1823 // regular for statement
1824 return &ast.ForStmt{pos, s1, p.makeExpr(s2), s3, body}
1827 func (p *parser) parseStmt() (s ast.Stmt) {
1829 defer un(trace(p, "Statement"))
1833 case token.CONST, token.TYPE, token.VAR:
1834 s = &ast.DeclStmt{p.parseDecl()}
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
1844 if _, isLabeledStmt := s.(*ast.LabeledStmt); !isLabeledStmt {
1850 s = p.parseDeferStmt()
1852 s = p.parseReturnStmt()
1853 case token.BREAK, token.CONTINUE, token.GOTO, token.FALLTHROUGH:
1854 s = p.parseBranchStmt(p.tok)
1856 s = p.parseBlockStmt()
1861 s = p.parseSwitchStmt()
1863 s = p.parseSelectStmt()
1865 s = p.parseForStmt()
1866 case token.SEMICOLON:
1867 s = &ast.EmptyStmt{p.pos}
1870 // a semicolon may be omitted before a closing "}"
1871 s = &ast.EmptyStmt{p.pos}
1873 // no statement found
1875 p.errorExpected(pos, "statement")
1876 p.next() // make progress
1877 s = &ast.BadStmt{pos, p.pos}
1883 // ----------------------------------------------------------------------------
1886 type parseSpecFunction func(p *parser, doc *ast.CommentGroup, iota int) ast.Spec
1888 func parseImportSpec(p *parser, doc *ast.CommentGroup, _ int) ast.Spec {
1890 defer un(trace(p, "ImportSpec"))
1893 var ident *ast.Ident
1896 ident = &ast.Ident{p.pos, ".", nil}
1899 ident = p.parseIdent()
1902 var path *ast.BasicLit
1903 if p.tok == token.STRING {
1904 path = &ast.BasicLit{p.pos, p.tok, p.lit}
1907 p.expect(token.STRING) // use expect() error handling
1909 p.expectSemi() // call before accessing p.linecomment
1912 spec := &ast.ImportSpec{doc, ident, path, p.lineComment}
1913 p.imports = append(p.imports, spec)
1918 func parseConstSpec(p *parser, doc *ast.CommentGroup, iota int) ast.Spec {
1920 defer un(trace(p, "ConstSpec"))
1923 idents := p.parseIdentList()
1925 var values []ast.Expr
1926 if typ != nil || p.tok == token.ASSIGN || iota == 0 {
1927 p.expect(token.ASSIGN)
1928 values = p.parseRhsList()
1930 p.expectSemi() // call before accessing p.linecomment
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...)
1942 func parseTypeSpec(p *parser, doc *ast.CommentGroup, _ int) ast.Spec {
1944 defer un(trace(p, "TypeSpec"))
1947 ident := p.parseIdent()
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)
1956 spec.Type = p.parseType()
1957 p.expectSemi() // call before accessing p.linecomment
1958 spec.Comment = p.lineComment
1963 func parseVarSpec(p *parser, doc *ast.CommentGroup, _ int) ast.Spec {
1965 defer un(trace(p, "VarSpec"))
1968 idents := p.parseIdentList()
1970 var values []ast.Expr
1971 if typ == nil || p.tok == token.ASSIGN {
1972 p.expect(token.ASSIGN)
1973 values = p.parseRhsList()
1975 p.expectSemi() // call before accessing p.linecomment
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...)
1987 func (p *parser) parseGenDecl(keyword token.Token, f parseSpecFunction) *ast.GenDecl {
1989 defer un(trace(p, "GenDecl("+keyword.String()+")"))
1992 doc := p.leadComment
1993 pos := p.expect(keyword)
1994 var lparen, rparen token.Pos
1996 if p.tok == token.LPAREN {
1999 for iota := 0; p.tok != token.RPAREN && p.tok != token.EOF; iota++ {
2000 list = append(list, f(p, p.leadComment, iota))
2002 rparen = p.expect(token.RPAREN)
2005 list = append(list, f(p, nil, 0))
2008 return &ast.GenDecl{doc, pos, keyword, lparen, list, rparen}
2011 func (p *parser) parseReceiver(scope *ast.Scope) *ast.FieldList {
2013 defer un(trace(p, "Receiver"))
2016 par := p.parseParameters(scope, false)
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}}}
2025 // recv type must be of the form ["*"] identifier
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()}}}
2036 func (p *parser) parseFuncDecl() *ast.FuncDecl {
2038 defer un(trace(p, "FunctionDecl"))
2041 doc := p.leadComment
2042 pos := p.expect(token.FUNC)
2043 scope := ast.NewScope(p.topScope) // function scope
2045 var recv *ast.FieldList
2046 if p.tok == token.LPAREN {
2047 recv = p.parseReceiver(scope)
2050 ident := p.parseIdent()
2052 params, results := p.parseSignature(scope)
2054 var body *ast.BlockStmt
2055 if p.tok == token.LBRACE {
2056 body = p.parseBody(scope)
2060 decl := &ast.FuncDecl{doc, recv, ident, &ast.FuncType{pos, params, results}, body}
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.
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)
2076 func (p *parser) parseDecl() ast.Decl {
2078 defer un(trace(p, "Declaration"))
2081 var f parseSpecFunction
2093 return p.parseFuncDecl()
2097 p.errorExpected(pos, "declaration")
2098 p.next() // make progress
2099 decl := &ast.BadDecl{pos, p.pos}
2103 return p.parseGenDecl(p.tok, f)
2106 func (p *parser) parseDeclList() (list []ast.Decl) {
2108 defer un(trace(p, "DeclList"))
2111 for p.tok != token.EOF {
2112 list = append(list, p.parseDecl())
2118 // ----------------------------------------------------------------------------
2121 func (p *parser) parseFile() *ast.File {
2123 defer un(trace(p, "File"))
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 _")
2137 var decls []ast.Decl
2139 // Don't bother parsing the rest if we had errors already.
2140 // Likely not a Go source file at all.
2142 if p.ErrorCount() == 0 && p.mode&PackageClauseOnly == 0 {
2144 for p.tok == token.IMPORT {
2145 decls = append(decls, p.parseGenDecl(token.IMPORT, parseImportSpec))
2148 if p.mode&ImportsOnly == 0 {
2149 // rest of package body
2150 for p.tok != token.EOF {
2151 decls = append(decls, p.parseDecl())
2156 assert(p.topScope == p.pkgScope, "imbalanced scopes")
2158 // resolve global identifiers within the same file
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
2170 return &ast.File{doc, pos, ident, decls, p.pkgScope, p.imports, p.unresolved[0:i], p.comments}