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.
22 // The parser structure holds the parser's internal state.
25 errors scanner.ErrorList
26 scanner scanner.Scanner
29 mode Mode // parsing mode
30 trace bool // == (mode & Trace != 0)
31 indent uint // indentation used for tracing output
34 comments []*ast.CommentGroup
35 leadComment *ast.CommentGroup // last lead comment
36 lineComment *ast.CommentGroup // last line comment
39 pos token.Pos // token position
40 tok token.Token // one token look-ahead
41 lit string // token literal
44 // (used to limit the number of calls to syncXXX functions
45 // w/o making scanning progress - avoids potential endless
46 // loops across multiple parser functions during error recovery)
47 syncPos token.Pos // last synchronization position
48 syncCnt int // number of calls to syncXXX without progress
50 // Non-syntactic parser control
51 exprLev int // < 0: in control clause, >= 0: in expression
53 // Ordinary identifier scopes
54 pkgScope *ast.Scope // pkgScope.Outer == nil
55 topScope *ast.Scope // top-most scope; may be pkgScope
56 unresolved []*ast.Ident // unresolved identifiers
57 imports []*ast.ImportSpec // list of imports
60 // (maintained by open/close LabelScope)
61 labelScope *ast.Scope // label scope for current function
62 targetStack [][]*ast.Ident // stack of unresolved labels
65 func (p *parser) init(fset *token.FileSet, filename string, src []byte, mode Mode) {
66 p.file = fset.AddFile(filename, fset.Base(), len(src))
68 if mode&ParseComments != 0 {
69 m = scanner.ScanComments
71 eh := func(pos token.Position, msg string) { p.errors.Add(pos, msg) }
72 p.scanner.Init(p.file, src, eh, m)
75 p.trace = mode&Trace != 0 // for convenience (p.trace is used frequently)
79 // set up the pkgScope here (as opposed to in parseFile) because
80 // there are other parser entry points (ParseExpr, etc.)
82 p.pkgScope = p.topScope
84 // for the same reason, set up a label scope
88 // ----------------------------------------------------------------------------
91 func (p *parser) openScope() {
92 p.topScope = ast.NewScope(p.topScope)
95 func (p *parser) closeScope() {
96 p.topScope = p.topScope.Outer
99 func (p *parser) openLabelScope() {
100 p.labelScope = ast.NewScope(p.labelScope)
101 p.targetStack = append(p.targetStack, nil)
104 func (p *parser) closeLabelScope() {
106 n := len(p.targetStack) - 1
107 scope := p.labelScope
108 for _, ident := range p.targetStack[n] {
109 ident.Obj = scope.Lookup(ident.Name)
110 if ident.Obj == nil && p.mode&DeclarationErrors != 0 {
111 p.error(ident.Pos(), fmt.Sprintf("label %s undefined", ident.Name))
115 p.targetStack = p.targetStack[0:n]
116 p.labelScope = p.labelScope.Outer
119 func (p *parser) declare(decl, data interface{}, scope *ast.Scope, kind ast.ObjKind, idents ...*ast.Ident) {
120 for _, ident := range idents {
121 assert(ident.Obj == nil, "identifier already declared or resolved")
122 obj := ast.NewObj(kind, ident.Name)
123 // remember the corresponding declaration for redeclaration
124 // errors and global variable resolution/typechecking phase
128 if ident.Name != "_" {
129 if alt := scope.Insert(obj); alt != nil && p.mode&DeclarationErrors != 0 {
131 if pos := alt.Pos(); pos.IsValid() {
132 prevDecl = fmt.Sprintf("\n\tprevious declaration at %s", p.file.Position(pos))
134 p.error(ident.Pos(), fmt.Sprintf("%s redeclared in this block%s", ident.Name, prevDecl))
140 func (p *parser) shortVarDecl(decl *ast.AssignStmt, list []ast.Expr) {
141 // Go spec: A short variable declaration may redeclare variables
142 // provided they were originally declared in the same block with
143 // the same type, and at least one of the non-blank variables is new.
144 n := 0 // number of new variables
145 for _, x := range list {
146 if ident, isIdent := x.(*ast.Ident); isIdent {
147 assert(ident.Obj == nil, "identifier already declared or resolved")
148 obj := ast.NewObj(ast.Var, ident.Name)
149 // remember corresponding assignment for other tools
152 if ident.Name != "_" {
153 if alt := p.topScope.Insert(obj); alt != nil {
154 ident.Obj = alt // redeclaration
156 n++ // new declaration
160 p.errorExpected(x.Pos(), "identifier")
163 if n == 0 && p.mode&DeclarationErrors != 0 {
164 p.error(list[0].Pos(), "no new variables on left side of :=")
168 // The unresolved object is a sentinel to mark identifiers that have been added
169 // to the list of unresolved identifiers. The sentinel is only used for verifying
170 // internal consistency.
171 var unresolved = new(ast.Object)
173 func (p *parser) resolve(x ast.Expr) {
174 // nothing to do if x is not an identifier or the blank identifier
175 ident, _ := x.(*ast.Ident)
179 assert(ident.Obj == nil, "identifier already declared or resolved")
180 if ident.Name == "_" {
183 // try to resolve the identifier
184 for s := p.topScope; s != nil; s = s.Outer {
185 if obj := s.Lookup(ident.Name); obj != nil {
190 // all local scopes are known, so any unresolved identifier
191 // must be found either in the file scope, package scope
192 // (perhaps in another file), or universe scope --- collect
193 // them so that they can be resolved later
194 ident.Obj = unresolved
195 p.unresolved = append(p.unresolved, ident)
198 // ----------------------------------------------------------------------------
201 func (p *parser) printTrace(a ...interface{}) {
202 const dots = ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . " +
203 ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
204 const n = uint(len(dots))
205 pos := p.file.Position(p.pos)
206 fmt.Printf("%5d:%3d: ", pos.Line, pos.Column)
208 for ; i > n; i -= n {
215 func trace(p *parser, msg string) *parser {
216 p.printTrace(msg, "(")
221 // Usage pattern: defer un(trace(p, "..."));
227 // Advance to the next token.
228 func (p *parser) next0() {
229 // Because of one-token look-ahead, print the previous token
230 // when tracing as it provides a more readable output. The
231 // very first token (!p.pos.IsValid()) is not initialized
232 // (it is token.ILLEGAL), so don't print it .
233 if p.trace && p.pos.IsValid() {
236 case p.tok.IsLiteral():
237 p.printTrace(s, p.lit)
238 case p.tok.IsOperator(), p.tok.IsKeyword():
239 p.printTrace("\"" + s + "\"")
245 p.pos, p.tok, p.lit = p.scanner.Scan()
248 // Consume a comment and return it and the line on which it ends.
249 func (p *parser) consumeComment() (comment *ast.Comment, endline int) {
250 // /*-style comments may end on a different line than where they start.
251 // Scan the comment for '\n' chars and adjust endline accordingly.
252 endline = p.file.Line(p.pos)
254 // don't use range here - no need to decode Unicode code points
255 for i := 0; i < len(p.lit); i++ {
256 if p.lit[i] == '\n' {
262 comment = &ast.Comment{Slash: p.pos, Text: p.lit}
268 // Consume a group of adjacent comments, add it to the parser's
269 // comments list, and return it together with the line at which
270 // the last comment in the group ends. An empty line or non-comment
271 // token terminates a comment group.
273 func (p *parser) consumeCommentGroup() (comments *ast.CommentGroup, endline int) {
274 var list []*ast.Comment
275 endline = p.file.Line(p.pos)
276 for p.tok == token.COMMENT && endline+1 >= p.file.Line(p.pos) {
277 var comment *ast.Comment
278 comment, endline = p.consumeComment()
279 list = append(list, comment)
282 // add comment group to the comments list
283 comments = &ast.CommentGroup{List: list}
284 p.comments = append(p.comments, comments)
289 // Advance to the next non-comment token. In the process, collect
290 // any comment groups encountered, and remember the last lead and
291 // and line comments.
293 // A lead comment is a comment group that starts and ends in a
294 // line without any other tokens and that is followed by a non-comment
295 // token on the line immediately after the comment group.
297 // A line comment is a comment group that follows a non-comment
298 // token on the same line, and that has no tokens after it on the line
301 // Lead and line comments may be considered documentation that is
302 // stored in the AST.
304 func (p *parser) next() {
307 line := p.file.Line(p.pos) // current line
310 if p.tok == token.COMMENT {
311 var comment *ast.CommentGroup
314 if p.file.Line(p.pos) == line {
315 // The comment is on same line as the previous token; it
316 // cannot be a lead comment but may be a line comment.
317 comment, endline = p.consumeCommentGroup()
318 if p.file.Line(p.pos) != endline {
319 // The next token is on a different line, thus
320 // the last comment group is a line comment.
321 p.lineComment = comment
325 // consume successor comments, if any
327 for p.tok == token.COMMENT {
328 comment, endline = p.consumeCommentGroup()
331 if endline+1 == p.file.Line(p.pos) {
332 // The next token is following on the line immediately after the
333 // comment group, thus the last comment group is a lead comment.
334 p.leadComment = comment
339 func (p *parser) error(pos token.Pos, msg string) {
340 p.errors.Add(p.file.Position(pos), msg)
343 func (p *parser) errorExpected(pos token.Pos, msg string) {
344 msg = "expected " + msg
346 // the error happened at the current position;
347 // make the error message more specific
348 if p.tok == token.SEMICOLON && p.lit == "\n" {
349 msg += ", found newline"
351 msg += ", found '" + p.tok.String() + "'"
352 if p.tok.IsLiteral() {
360 func (p *parser) expect(tok token.Token) token.Pos {
363 p.errorExpected(pos, "'"+tok.String()+"'")
365 p.next() // make progress
369 // expectClosing is like expect but provides a better error message
370 // for the common case of a missing comma before a newline.
372 func (p *parser) expectClosing(tok token.Token, context string) token.Pos {
373 if p.tok != tok && p.tok == token.SEMICOLON && p.lit == "\n" {
374 p.error(p.pos, "missing ',' before newline in "+context)
380 func (p *parser) expectSemi() {
381 // semicolon is optional before a closing ')' or '}'
382 if p.tok != token.RPAREN && p.tok != token.RBRACE {
383 if p.tok == token.SEMICOLON {
386 p.errorExpected(p.pos, "';'")
392 func (p *parser) atComma(context string) bool {
393 if p.tok == token.COMMA {
396 if p.tok == token.SEMICOLON && p.lit == "\n" {
397 p.error(p.pos, "missing ',' before newline in "+context)
398 return true // "insert" the comma and continue
404 func assert(cond bool, msg string) {
406 panic("go/parser internal error: " + msg)
410 // syncStmt advances to the next statement.
411 // Used for synchronization after an error.
413 func syncStmt(p *parser) {
416 case token.BREAK, token.CONST, token.CONTINUE, token.DEFER,
417 token.FALLTHROUGH, token.FOR, token.GO, token.GOTO,
418 token.IF, token.RETURN, token.SELECT, token.SWITCH,
419 token.TYPE, token.VAR:
420 // Return only if parser made some progress since last
421 // sync or if it has not reached 10 sync calls without
422 // progress. Otherwise consume at least one token to
423 // avoid an endless parser loop (it is possible that
424 // both parseOperand and parseStmt call syncStmt and
425 // correctly do not advance, thus the need for the
426 // invocation limit p.syncCnt).
427 if p.pos == p.syncPos && p.syncCnt < 10 {
431 if p.pos > p.syncPos {
436 // Reaching here indicates a parser bug, likely an
437 // incorrect token list in this function, but it only
438 // leads to skipping of possibly correct code if a
439 // previous error is present, and thus is preferred
440 // over a non-terminating parse.
448 // syncDecl advances to the next declaration.
449 // Used for synchronization after an error.
451 func syncDecl(p *parser) {
454 case token.CONST, token.TYPE, token.VAR:
455 // see comments in syncStmt
456 if p.pos == p.syncPos && p.syncCnt < 10 {
460 if p.pos > p.syncPos {
472 // ----------------------------------------------------------------------------
475 func (p *parser) parseIdent() *ast.Ident {
478 if p.tok == token.IDENT {
482 p.expect(token.IDENT) // use expect() error handling
484 return &ast.Ident{NamePos: pos, Name: name}
487 func (p *parser) parseIdentList() (list []*ast.Ident) {
489 defer un(trace(p, "IdentList"))
492 list = append(list, p.parseIdent())
493 for p.tok == token.COMMA {
495 list = append(list, p.parseIdent())
501 // ----------------------------------------------------------------------------
502 // Common productions
504 // If lhs is set, result list elements which are identifiers are not resolved.
505 func (p *parser) parseExprList(lhs bool) (list []ast.Expr) {
507 defer un(trace(p, "ExpressionList"))
510 list = append(list, p.checkExpr(p.parseExpr(lhs)))
511 for p.tok == token.COMMA {
513 list = append(list, p.checkExpr(p.parseExpr(lhs)))
519 func (p *parser) parseLhsList() []ast.Expr {
520 list := p.parseExprList(true)
523 // lhs of a short variable declaration
524 // but doesn't enter scope until later:
525 // caller must call p.shortVarDecl(p.makeIdentList(list))
526 // at appropriate time.
528 // lhs of a label declaration or a communication clause of a select
529 // statement (parseLhsList is not called when parsing the case clause
530 // of a switch statement):
531 // - labels are declared by the caller of parseLhsList
532 // - for communication clauses, if there is a stand-alone identifier
533 // followed by a colon, we have a syntax error; there is no need
534 // to resolve the identifier in that case
536 // identifiers must be declared elsewhere
537 for _, x := range list {
544 func (p *parser) parseRhsList() []ast.Expr {
545 return p.parseExprList(false)
548 // ----------------------------------------------------------------------------
551 func (p *parser) parseType() ast.Expr {
553 defer un(trace(p, "Type"))
560 p.errorExpected(pos, "type")
561 p.next() // make progress
562 return &ast.BadExpr{From: pos, To: p.pos}
568 // If the result is an identifier, it is not resolved.
569 func (p *parser) parseTypeName() ast.Expr {
571 defer un(trace(p, "TypeName"))
574 ident := p.parseIdent()
575 // don't resolve ident yet - it may be a parameter or field name
577 if p.tok == token.PERIOD {
578 // ident is a package name
581 sel := p.parseIdent()
582 return &ast.SelectorExpr{X: ident, Sel: sel}
588 func (p *parser) parseArrayType(ellipsisOk bool) ast.Expr {
590 defer un(trace(p, "ArrayType"))
593 lbrack := p.expect(token.LBRACK)
595 if ellipsisOk && p.tok == token.ELLIPSIS {
596 len = &ast.Ellipsis{Ellipsis: p.pos}
598 } else if p.tok != token.RBRACK {
601 p.expect(token.RBRACK)
604 return &ast.ArrayType{Lbrack: lbrack, Len: len, Elt: elt}
607 func (p *parser) makeIdentList(list []ast.Expr) []*ast.Ident {
608 idents := make([]*ast.Ident, len(list))
609 for i, x := range list {
610 ident, isIdent := x.(*ast.Ident)
612 if _, isBad := x.(*ast.BadExpr); !isBad {
613 // only report error if it's a new one
614 p.errorExpected(x.Pos(), "identifier")
616 ident = &ast.Ident{NamePos: x.Pos(), Name: "_"}
623 func (p *parser) parseFieldDecl(scope *ast.Scope) *ast.Field {
625 defer un(trace(p, "FieldDecl"))
631 list, typ := p.parseVarList(false)
634 var tag *ast.BasicLit
635 if p.tok == token.STRING {
636 tag = &ast.BasicLit{ValuePos: p.pos, Kind: p.tok, Value: p.lit}
641 var idents []*ast.Ident
643 // IdentifierList Type
644 idents = p.makeIdentList(list)
646 // ["*"] TypeName (AnonymousField)
647 typ = list[0] // we always have at least one element
649 if n := len(list); n > 1 || !isTypeName(deref(typ)) {
651 p.errorExpected(pos, "anonymous field")
652 typ = &ast.BadExpr{From: pos, To: list[n-1].End()}
656 p.expectSemi() // call before accessing p.linecomment
658 field := &ast.Field{Doc: doc, Names: idents, Type: typ, Tag: tag, Comment: p.lineComment}
659 p.declare(field, nil, scope, ast.Var, idents...)
664 func (p *parser) parseStructType() *ast.StructType {
666 defer un(trace(p, "StructType"))
669 pos := p.expect(token.STRUCT)
670 lbrace := p.expect(token.LBRACE)
671 scope := ast.NewScope(nil) // struct scope
672 var list []*ast.Field
673 for p.tok == token.IDENT || p.tok == token.MUL || p.tok == token.LPAREN {
674 // a field declaration cannot start with a '(' but we accept
675 // it here for more robust parsing and better error messages
676 // (parseFieldDecl will check and complain if necessary)
677 list = append(list, p.parseFieldDecl(scope))
679 rbrace := p.expect(token.RBRACE)
681 return &ast.StructType{
683 Fields: &ast.FieldList{
691 func (p *parser) parsePointerType() *ast.StarExpr {
693 defer un(trace(p, "PointerType"))
696 star := p.expect(token.MUL)
697 base := p.parseType()
699 return &ast.StarExpr{Star: star, X: base}
702 func (p *parser) tryVarType(isParam bool) ast.Expr {
703 if isParam && p.tok == token.ELLIPSIS {
706 typ := p.tryIdentOrType(isParam) // don't use parseType so we can provide better error message
708 p.error(pos, "'...' parameter is missing type")
709 typ = &ast.BadExpr{From: pos, To: p.pos}
711 return &ast.Ellipsis{Ellipsis: pos, Elt: typ}
713 return p.tryIdentOrType(false)
716 func (p *parser) parseVarType(isParam bool) ast.Expr {
717 typ := p.tryVarType(isParam)
720 p.errorExpected(pos, "type")
721 p.next() // make progress
722 typ = &ast.BadExpr{From: pos, To: p.pos}
727 func (p *parser) parseVarList(isParam bool) (list []ast.Expr, typ ast.Expr) {
729 defer un(trace(p, "VarList"))
732 // a list of identifiers looks like a list of type names
734 // parse/tryVarType accepts any type (including parenthesized
735 // ones) even though the syntax does not permit them here: we
736 // accept them all for more robust parsing and complain later
737 for typ := p.parseVarType(isParam); typ != nil; {
738 list = append(list, typ)
739 if p.tok != token.COMMA {
743 typ = p.tryVarType(isParam) // maybe nil as in: func f(int,) {}
746 // if we had a list of identifiers, it must be followed by a type
747 if typ = p.tryVarType(isParam); typ != nil {
754 func (p *parser) parseParameterList(scope *ast.Scope, ellipsisOk bool) (params []*ast.Field) {
756 defer un(trace(p, "ParameterList"))
759 list, typ := p.parseVarList(ellipsisOk)
761 // IdentifierList Type
762 idents := p.makeIdentList(list)
763 field := &ast.Field{Names: idents, Type: typ}
764 params = append(params, field)
765 // Go spec: The scope of an identifier denoting a function
766 // parameter or result variable is the function body.
767 p.declare(field, nil, scope, ast.Var, idents...)
768 if p.tok == token.COMMA {
772 for p.tok != token.RPAREN && p.tok != token.EOF {
773 idents := p.parseIdentList()
774 typ := p.parseVarType(ellipsisOk)
775 field := &ast.Field{Names: idents, Type: typ}
776 params = append(params, field)
777 // Go spec: The scope of an identifier denoting a function
778 // parameter or result variable is the function body.
779 p.declare(field, nil, scope, ast.Var, idents...)
780 if !p.atComma("parameter list") {
787 // Type { "," Type } (anonymous parameters)
788 params = make([]*ast.Field, len(list))
789 for i, x := range list {
791 params[i] = &ast.Field{Type: x}
798 func (p *parser) parseParameters(scope *ast.Scope, ellipsisOk bool) *ast.FieldList {
800 defer un(trace(p, "Parameters"))
803 var params []*ast.Field
804 lparen := p.expect(token.LPAREN)
805 if p.tok != token.RPAREN {
806 params = p.parseParameterList(scope, ellipsisOk)
808 rparen := p.expect(token.RPAREN)
810 return &ast.FieldList{Opening: lparen, List: params, Closing: rparen}
813 func (p *parser) parseResult(scope *ast.Scope) *ast.FieldList {
815 defer un(trace(p, "Result"))
818 if p.tok == token.LPAREN {
819 return p.parseParameters(scope, false)
824 list := make([]*ast.Field, 1)
825 list[0] = &ast.Field{Type: typ}
826 return &ast.FieldList{List: list}
832 func (p *parser) parseSignature(scope *ast.Scope) (params, results *ast.FieldList) {
834 defer un(trace(p, "Signature"))
837 params = p.parseParameters(scope, true)
838 results = p.parseResult(scope)
843 func (p *parser) parseFuncType() (*ast.FuncType, *ast.Scope) {
845 defer un(trace(p, "FuncType"))
848 pos := p.expect(token.FUNC)
849 scope := ast.NewScope(p.topScope) // function scope
850 params, results := p.parseSignature(scope)
852 return &ast.FuncType{Func: pos, Params: params, Results: results}, scope
855 func (p *parser) parseMethodSpec(scope *ast.Scope) *ast.Field {
857 defer un(trace(p, "MethodSpec"))
861 var idents []*ast.Ident
863 x := p.parseTypeName()
864 if ident, isIdent := x.(*ast.Ident); isIdent && p.tok == token.LPAREN {
866 idents = []*ast.Ident{ident}
867 scope := ast.NewScope(nil) // method scope
868 params, results := p.parseSignature(scope)
869 typ = &ast.FuncType{Func: token.NoPos, Params: params, Results: results}
871 // embedded interface
875 p.expectSemi() // call before accessing p.linecomment
877 spec := &ast.Field{Doc: doc, Names: idents, Type: typ, Comment: p.lineComment}
878 p.declare(spec, nil, scope, ast.Fun, idents...)
883 func (p *parser) parseInterfaceType() *ast.InterfaceType {
885 defer un(trace(p, "InterfaceType"))
888 pos := p.expect(token.INTERFACE)
889 lbrace := p.expect(token.LBRACE)
890 scope := ast.NewScope(nil) // interface scope
891 var list []*ast.Field
892 for p.tok == token.IDENT {
893 list = append(list, p.parseMethodSpec(scope))
895 rbrace := p.expect(token.RBRACE)
897 return &ast.InterfaceType{
899 Methods: &ast.FieldList{
907 func (p *parser) parseMapType() *ast.MapType {
909 defer un(trace(p, "MapType"))
912 pos := p.expect(token.MAP)
913 p.expect(token.LBRACK)
915 p.expect(token.RBRACK)
916 value := p.parseType()
918 return &ast.MapType{Map: pos, Key: key, Value: value}
921 func (p *parser) parseChanType() *ast.ChanType {
923 defer un(trace(p, "ChanType"))
927 dir := ast.SEND | ast.RECV
928 if p.tok == token.CHAN {
930 if p.tok == token.ARROW {
935 p.expect(token.ARROW)
939 value := p.parseType()
941 return &ast.ChanType{Begin: pos, Dir: dir, Value: value}
944 // If the result is an identifier, it is not resolved.
945 func (p *parser) tryIdentOrType(ellipsisOk bool) ast.Expr {
948 return p.parseTypeName()
950 return p.parseArrayType(ellipsisOk)
952 return p.parseStructType()
954 return p.parsePointerType()
956 typ, _ := p.parseFuncType()
958 case token.INTERFACE:
959 return p.parseInterfaceType()
961 return p.parseMapType()
962 case token.CHAN, token.ARROW:
963 return p.parseChanType()
968 rparen := p.expect(token.RPAREN)
969 return &ast.ParenExpr{Lparen: lparen, X: typ, Rparen: rparen}
976 func (p *parser) tryType() ast.Expr {
977 typ := p.tryIdentOrType(false)
984 // ----------------------------------------------------------------------------
987 func (p *parser) parseStmtList() (list []ast.Stmt) {
989 defer un(trace(p, "StatementList"))
992 for p.tok != token.CASE && p.tok != token.DEFAULT && p.tok != token.RBRACE && p.tok != token.EOF {
993 list = append(list, p.parseStmt())
999 func (p *parser) parseBody(scope *ast.Scope) *ast.BlockStmt {
1001 defer un(trace(p, "Body"))
1004 lbrace := p.expect(token.LBRACE)
1005 p.topScope = scope // open function scope
1007 list := p.parseStmtList()
1010 rbrace := p.expect(token.RBRACE)
1012 return &ast.BlockStmt{Lbrace: lbrace, List: list, Rbrace: rbrace}
1015 func (p *parser) parseBlockStmt() *ast.BlockStmt {
1017 defer un(trace(p, "BlockStmt"))
1020 lbrace := p.expect(token.LBRACE)
1022 list := p.parseStmtList()
1024 rbrace := p.expect(token.RBRACE)
1026 return &ast.BlockStmt{Lbrace: lbrace, List: list, Rbrace: rbrace}
1029 // ----------------------------------------------------------------------------
1032 func (p *parser) parseFuncTypeOrLit() ast.Expr {
1034 defer un(trace(p, "FuncTypeOrLit"))
1037 typ, scope := p.parseFuncType()
1038 if p.tok != token.LBRACE {
1039 // function type only
1044 body := p.parseBody(scope)
1047 return &ast.FuncLit{Type: typ, Body: body}
1050 // parseOperand may return an expression or a raw type (incl. array
1051 // types of the form [...]T. Callers must verify the result.
1052 // If lhs is set and the result is an identifier, it is not resolved.
1054 func (p *parser) parseOperand(lhs bool) ast.Expr {
1056 defer un(trace(p, "Operand"))
1067 case token.INT, token.FLOAT, token.IMAG, token.CHAR, token.STRING:
1068 x := &ast.BasicLit{ValuePos: p.pos, Kind: p.tok, Value: p.lit}
1076 x := p.parseRhsOrType() // types may be parenthesized: (some type)
1078 rparen := p.expect(token.RPAREN)
1079 return &ast.ParenExpr{Lparen: lparen, X: x, Rparen: rparen}
1082 return p.parseFuncTypeOrLit()
1085 if typ := p.tryIdentOrType(true); typ != nil {
1086 // could be type for composite literal or conversion
1087 _, isIdent := typ.(*ast.Ident)
1088 assert(!isIdent, "type cannot be identifier")
1094 p.errorExpected(pos, "operand")
1096 return &ast.BadExpr{From: pos, To: p.pos}
1099 func (p *parser) parseSelector(x ast.Expr) ast.Expr {
1101 defer un(trace(p, "Selector"))
1104 sel := p.parseIdent()
1106 return &ast.SelectorExpr{X: x, Sel: sel}
1109 func (p *parser) parseTypeAssertion(x ast.Expr) ast.Expr {
1111 defer un(trace(p, "TypeAssertion"))
1114 p.expect(token.LPAREN)
1116 if p.tok == token.TYPE {
1117 // type switch: typ == nil
1122 p.expect(token.RPAREN)
1124 return &ast.TypeAssertExpr{X: x, Type: typ}
1127 func (p *parser) parseIndexOrSlice(x ast.Expr) ast.Expr {
1129 defer un(trace(p, "IndexOrSlice"))
1132 lbrack := p.expect(token.LBRACK)
1134 var low, high ast.Expr
1136 if p.tok != token.COLON {
1139 if p.tok == token.COLON {
1142 if p.tok != token.RBRACK {
1147 rbrack := p.expect(token.RBRACK)
1150 return &ast.SliceExpr{X: x, Lbrack: lbrack, Low: low, High: high, Rbrack: rbrack}
1152 return &ast.IndexExpr{X: x, Lbrack: lbrack, Index: low, Rbrack: rbrack}
1155 func (p *parser) parseCallOrConversion(fun ast.Expr) *ast.CallExpr {
1157 defer un(trace(p, "CallOrConversion"))
1160 lparen := p.expect(token.LPAREN)
1163 var ellipsis token.Pos
1164 for p.tok != token.RPAREN && p.tok != token.EOF && !ellipsis.IsValid() {
1165 list = append(list, p.parseRhsOrType()) // builtins may expect a type: make(some type, ...)
1166 if p.tok == token.ELLIPSIS {
1170 if !p.atComma("argument list") {
1176 rparen := p.expectClosing(token.RPAREN, "argument list")
1178 return &ast.CallExpr{Fun: fun, Lparen: lparen, Args: list, Ellipsis: ellipsis, Rparen: rparen}
1181 func (p *parser) parseElement(keyOk bool) ast.Expr {
1183 defer un(trace(p, "Element"))
1186 if p.tok == token.LBRACE {
1187 return p.parseLiteralValue(nil)
1190 x := p.checkExpr(p.parseExpr(keyOk)) // don't resolve if map key
1192 if p.tok == token.COLON {
1195 return &ast.KeyValueExpr{Key: x, Colon: colon, Value: p.parseElement(false)}
1197 p.resolve(x) // not a map key
1203 func (p *parser) parseElementList() (list []ast.Expr) {
1205 defer un(trace(p, "ElementList"))
1208 for p.tok != token.RBRACE && p.tok != token.EOF {
1209 list = append(list, p.parseElement(true))
1210 if !p.atComma("composite literal") {
1219 func (p *parser) parseLiteralValue(typ ast.Expr) ast.Expr {
1221 defer un(trace(p, "LiteralValue"))
1224 lbrace := p.expect(token.LBRACE)
1227 if p.tok != token.RBRACE {
1228 elts = p.parseElementList()
1231 rbrace := p.expectClosing(token.RBRACE, "composite literal")
1232 return &ast.CompositeLit{Type: typ, Lbrace: lbrace, Elts: elts, Rbrace: rbrace}
1235 // checkExpr checks that x is an expression (and not a type).
1236 func (p *parser) checkExpr(x ast.Expr) ast.Expr {
1237 switch unparen(x).(type) {
1242 case *ast.CompositeLit:
1243 case *ast.ParenExpr:
1244 panic("unreachable")
1245 case *ast.SelectorExpr:
1246 case *ast.IndexExpr:
1247 case *ast.SliceExpr:
1248 case *ast.TypeAssertExpr:
1249 // If t.Type == nil we have a type assertion of the form
1250 // y.(type), which is only allowed in type switch expressions.
1251 // It's hard to exclude those but for the case where we are in
1252 // a type switch. Instead be lenient and test this in the type
1256 case *ast.UnaryExpr:
1257 case *ast.BinaryExpr:
1259 // all other nodes are not proper expressions
1260 p.errorExpected(x.Pos(), "expression")
1261 x = &ast.BadExpr{From: x.Pos(), To: x.End()}
1266 // isTypeName returns true iff x is a (qualified) TypeName.
1267 func isTypeName(x ast.Expr) bool {
1268 switch t := x.(type) {
1271 case *ast.SelectorExpr:
1272 _, isIdent := t.X.(*ast.Ident)
1275 return false // all other nodes are not type names
1280 // isLiteralType returns true iff x is a legal composite literal type.
1281 func isLiteralType(x ast.Expr) bool {
1282 switch t := x.(type) {
1285 case *ast.SelectorExpr:
1286 _, isIdent := t.X.(*ast.Ident)
1288 case *ast.ArrayType:
1289 case *ast.StructType:
1292 return false // all other nodes are not legal composite literal types
1297 // If x is of the form *T, deref returns T, otherwise it returns x.
1298 func deref(x ast.Expr) ast.Expr {
1299 if p, isPtr := x.(*ast.StarExpr); isPtr {
1305 // If x is of the form (T), unparen returns unparen(T), otherwise it returns x.
1306 func unparen(x ast.Expr) ast.Expr {
1307 if p, isParen := x.(*ast.ParenExpr); isParen {
1313 // checkExprOrType checks that x is an expression or a type
1314 // (and not a raw type such as [...]T).
1316 func (p *parser) checkExprOrType(x ast.Expr) ast.Expr {
1317 switch t := unparen(x).(type) {
1318 case *ast.ParenExpr:
1319 panic("unreachable")
1320 case *ast.UnaryExpr:
1321 case *ast.ArrayType:
1322 if len, isEllipsis := t.Len.(*ast.Ellipsis); isEllipsis {
1323 p.error(len.Pos(), "expected array length, found '...'")
1324 x = &ast.BadExpr{From: x.Pos(), To: x.End()}
1328 // all other nodes are expressions or types
1332 // If lhs is set and the result is an identifier, it is not resolved.
1333 func (p *parser) parsePrimaryExpr(lhs bool) ast.Expr {
1335 defer un(trace(p, "PrimaryExpr"))
1338 x := p.parseOperand(lhs)
1349 x = p.parseSelector(p.checkExpr(x))
1351 x = p.parseTypeAssertion(p.checkExpr(x))
1354 p.errorExpected(pos, "selector or type assertion")
1355 p.next() // make progress
1356 x = &ast.BadExpr{From: pos, To: p.pos}
1362 x = p.parseIndexOrSlice(p.checkExpr(x))
1367 x = p.parseCallOrConversion(p.checkExprOrType(x))
1369 if isLiteralType(x) && (p.exprLev >= 0 || !isTypeName(x)) {
1373 x = p.parseLiteralValue(x)
1380 lhs = false // no need to try to resolve again
1386 // If lhs is set and the result is an identifier, it is not resolved.
1387 func (p *parser) parseUnaryExpr(lhs bool) ast.Expr {
1389 defer un(trace(p, "UnaryExpr"))
1393 case token.ADD, token.SUB, token.NOT, token.XOR, token.AND:
1394 pos, op := p.pos, p.tok
1396 x := p.parseUnaryExpr(false)
1397 return &ast.UnaryExpr{OpPos: pos, Op: op, X: p.checkExpr(x)}
1400 // channel type or receive expression
1403 if p.tok == token.CHAN {
1405 value := p.parseType()
1406 return &ast.ChanType{Begin: pos, Dir: ast.RECV, Value: value}
1409 x := p.parseUnaryExpr(false)
1410 return &ast.UnaryExpr{OpPos: pos, Op: token.ARROW, X: p.checkExpr(x)}
1413 // pointer type or unary "*" expression
1416 x := p.parseUnaryExpr(false)
1417 return &ast.StarExpr{Star: pos, X: p.checkExprOrType(x)}
1420 return p.parsePrimaryExpr(lhs)
1423 // If lhs is set and the result is an identifier, it is not resolved.
1424 func (p *parser) parseBinaryExpr(lhs bool, prec1 int) ast.Expr {
1426 defer un(trace(p, "BinaryExpr"))
1429 x := p.parseUnaryExpr(lhs)
1430 for prec := p.tok.Precedence(); prec >= prec1; prec-- {
1431 for p.tok.Precedence() == prec {
1432 pos, op := p.pos, p.tok
1438 y := p.parseBinaryExpr(false, prec+1)
1439 x = &ast.BinaryExpr{X: p.checkExpr(x), OpPos: pos, Op: op, Y: p.checkExpr(y)}
1446 // If lhs is set and the result is an identifier, it is not resolved.
1447 // The result may be a type or even a raw type ([...]int). Callers must
1448 // check the result (using checkExpr or checkExprOrType), depending on
1450 func (p *parser) parseExpr(lhs bool) ast.Expr {
1452 defer un(trace(p, "Expression"))
1455 return p.parseBinaryExpr(lhs, token.LowestPrec+1)
1458 func (p *parser) parseRhs() ast.Expr {
1459 return p.checkExpr(p.parseExpr(false))
1462 func (p *parser) parseRhsOrType() ast.Expr {
1463 return p.checkExprOrType(p.parseExpr(false))
1466 // ----------------------------------------------------------------------------
1469 // Parsing modes for parseSimpleStmt.
1476 // parseSimpleStmt returns true as 2nd result if it parsed the assignment
1477 // of a range clause (with mode == rangeOk). The returned statement is an
1478 // assignment with a right-hand side that is a single unary expression of
1479 // the form "range x". No guarantees are given for the left-hand side.
1480 func (p *parser) parseSimpleStmt(mode int) (ast.Stmt, bool) {
1482 defer un(trace(p, "SimpleStmt"))
1485 x := p.parseLhsList()
1489 token.DEFINE, token.ASSIGN, token.ADD_ASSIGN,
1490 token.SUB_ASSIGN, token.MUL_ASSIGN, token.QUO_ASSIGN,
1491 token.REM_ASSIGN, token.AND_ASSIGN, token.OR_ASSIGN,
1492 token.XOR_ASSIGN, token.SHL_ASSIGN, token.SHR_ASSIGN, token.AND_NOT_ASSIGN:
1493 // assignment statement, possibly part of a range clause
1494 pos, tok := p.pos, p.tok
1498 if mode == rangeOk && p.tok == token.RANGE && (tok == token.DEFINE || tok == token.ASSIGN) {
1501 y = []ast.Expr{&ast.UnaryExpr{OpPos: pos, Op: token.RANGE, X: p.parseRhs()}}
1504 y = p.parseRhsList()
1506 as := &ast.AssignStmt{Lhs: x, TokPos: pos, Tok: tok, Rhs: y}
1507 if tok == token.DEFINE {
1508 p.shortVarDecl(as, x)
1514 p.errorExpected(x[0].Pos(), "1 expression")
1515 // continue with first expression
1520 // labeled statement
1523 if label, isIdent := x[0].(*ast.Ident); mode == labelOk && isIdent {
1524 // Go spec: The scope of a label is the body of the function
1525 // in which it is declared and excludes the body of any nested
1527 stmt := &ast.LabeledStmt{Label: label, Colon: colon, Stmt: p.parseStmt()}
1528 p.declare(stmt, nil, p.labelScope, ast.Lbl, label)
1531 // The label declaration typically starts at x[0].Pos(), but the label
1532 // declaration may be erroneous due to a token after that position (and
1533 // before the ':'). If SpuriousErrors is not set, the (only) error re-
1534 // ported for the line is the illegal label error instead of the token
1535 // before the ':' that caused the problem. Thus, use the (latest) colon
1536 // position for error reporting.
1537 p.error(colon, "illegal label declaration")
1538 return &ast.BadStmt{From: x[0].Pos(), To: colon + 1}, false
1545 return &ast.SendStmt{Chan: x[0], Arrow: arrow, Value: y}, false
1547 case token.INC, token.DEC:
1548 // increment or decrement
1549 s := &ast.IncDecStmt{X: x[0], TokPos: p.pos, Tok: p.tok}
1555 return &ast.ExprStmt{X: x[0]}, false
1558 func (p *parser) parseCallExpr() *ast.CallExpr {
1559 x := p.parseRhsOrType() // could be a conversion: (some type)(x)
1560 if call, isCall := x.(*ast.CallExpr); isCall {
1563 if _, isBad := x.(*ast.BadExpr); !isBad {
1564 // only report error if it's a new one
1565 p.errorExpected(x.Pos(), "function/method call")
1570 func (p *parser) parseGoStmt() ast.Stmt {
1572 defer un(trace(p, "GoStmt"))
1575 pos := p.expect(token.GO)
1576 call := p.parseCallExpr()
1579 return &ast.BadStmt{From: pos, To: pos + 2} // len("go")
1582 return &ast.GoStmt{Go: pos, Call: call}
1585 func (p *parser) parseDeferStmt() ast.Stmt {
1587 defer un(trace(p, "DeferStmt"))
1590 pos := p.expect(token.DEFER)
1591 call := p.parseCallExpr()
1594 return &ast.BadStmt{From: pos, To: pos + 5} // len("defer")
1597 return &ast.DeferStmt{Defer: pos, Call: call}
1600 func (p *parser) parseReturnStmt() *ast.ReturnStmt {
1602 defer un(trace(p, "ReturnStmt"))
1606 p.expect(token.RETURN)
1608 if p.tok != token.SEMICOLON && p.tok != token.RBRACE {
1609 x = p.parseRhsList()
1613 return &ast.ReturnStmt{Return: pos, Results: x}
1616 func (p *parser) parseBranchStmt(tok token.Token) *ast.BranchStmt {
1618 defer un(trace(p, "BranchStmt"))
1621 pos := p.expect(tok)
1622 var label *ast.Ident
1623 if tok != token.FALLTHROUGH && p.tok == token.IDENT {
1624 label = p.parseIdent()
1625 // add to list of unresolved targets
1626 n := len(p.targetStack) - 1
1627 p.targetStack[n] = append(p.targetStack[n], label)
1631 return &ast.BranchStmt{TokPos: pos, Tok: tok, Label: label}
1634 func (p *parser) makeExpr(s ast.Stmt) ast.Expr {
1638 if es, isExpr := s.(*ast.ExprStmt); isExpr {
1639 return p.checkExpr(es.X)
1641 p.error(s.Pos(), "expected condition, found simple statement")
1642 return &ast.BadExpr{From: s.Pos(), To: s.End()}
1645 func (p *parser) parseIfStmt() *ast.IfStmt {
1647 defer un(trace(p, "IfStmt"))
1650 pos := p.expect(token.IF)
1652 defer p.closeScope()
1657 prevLev := p.exprLev
1659 if p.tok == token.SEMICOLON {
1663 s, _ = p.parseSimpleStmt(basic)
1664 if p.tok == token.SEMICOLON {
1675 body := p.parseBlockStmt()
1677 if p.tok == token.ELSE {
1679 else_ = p.parseStmt()
1684 return &ast.IfStmt{If: pos, Init: s, Cond: x, Body: body, Else: else_}
1687 func (p *parser) parseTypeList() (list []ast.Expr) {
1689 defer un(trace(p, "TypeList"))
1692 list = append(list, p.parseType())
1693 for p.tok == token.COMMA {
1695 list = append(list, p.parseType())
1701 func (p *parser) parseCaseClause(typeSwitch bool) *ast.CaseClause {
1703 defer un(trace(p, "CaseClause"))
1708 if p.tok == token.CASE {
1711 list = p.parseTypeList()
1713 list = p.parseRhsList()
1716 p.expect(token.DEFAULT)
1719 colon := p.expect(token.COLON)
1721 body := p.parseStmtList()
1724 return &ast.CaseClause{Case: pos, List: list, Colon: colon, Body: body}
1727 func isTypeSwitchAssert(x ast.Expr) bool {
1728 a, ok := x.(*ast.TypeAssertExpr)
1729 return ok && a.Type == nil
1732 func isTypeSwitchGuard(s ast.Stmt) bool {
1733 switch t := s.(type) {
1736 return isTypeSwitchAssert(t.X)
1737 case *ast.AssignStmt:
1739 return len(t.Lhs) == 1 && t.Tok == token.DEFINE && len(t.Rhs) == 1 && isTypeSwitchAssert(t.Rhs[0])
1744 func (p *parser) parseSwitchStmt() ast.Stmt {
1746 defer un(trace(p, "SwitchStmt"))
1749 pos := p.expect(token.SWITCH)
1751 defer p.closeScope()
1754 if p.tok != token.LBRACE {
1755 prevLev := p.exprLev
1757 if p.tok != token.SEMICOLON {
1758 s2, _ = p.parseSimpleStmt(basic)
1760 if p.tok == token.SEMICOLON {
1764 if p.tok != token.LBRACE {
1765 // A TypeSwitchGuard may declare a variable in addition
1766 // to the variable declared in the initial SimpleStmt.
1767 // Introduce extra scope to avoid redeclaration errors:
1769 // switch t := 0; t := x.(T) { ... }
1771 // (this code is not valid Go because the first t will
1772 // cannot be accessed and thus is never used, the extra
1773 // scope is needed for the correct error message).
1775 // If we don't have a type switch, s2 must be an expression.
1776 // Having the extra nested but empty scope won't affect it.
1778 defer p.closeScope()
1779 s2, _ = p.parseSimpleStmt(basic)
1785 typeSwitch := isTypeSwitchGuard(s2)
1786 lbrace := p.expect(token.LBRACE)
1788 for p.tok == token.CASE || p.tok == token.DEFAULT {
1789 list = append(list, p.parseCaseClause(typeSwitch))
1791 rbrace := p.expect(token.RBRACE)
1793 body := &ast.BlockStmt{Lbrace: lbrace, List: list, Rbrace: rbrace}
1796 return &ast.TypeSwitchStmt{Switch: pos, Init: s1, Assign: s2, Body: body}
1799 return &ast.SwitchStmt{Switch: pos, Init: s1, Tag: p.makeExpr(s2), Body: body}
1802 func (p *parser) parseCommClause() *ast.CommClause {
1804 defer un(trace(p, "CommClause"))
1810 if p.tok == token.CASE {
1812 lhs := p.parseLhsList()
1813 if p.tok == token.ARROW {
1816 p.errorExpected(lhs[0].Pos(), "1 expression")
1817 // continue with first expression
1822 comm = &ast.SendStmt{Chan: lhs[0], Arrow: arrow, Value: rhs}
1825 if tok := p.tok; tok == token.ASSIGN || tok == token.DEFINE {
1826 // RecvStmt with assignment
1828 p.errorExpected(lhs[0].Pos(), "1 or 2 expressions")
1829 // continue with first two expressions
1835 as := &ast.AssignStmt{Lhs: lhs, TokPos: pos, Tok: tok, Rhs: []ast.Expr{rhs}}
1836 if tok == token.DEFINE {
1837 p.shortVarDecl(as, lhs)
1841 // lhs must be single receive operation
1843 p.errorExpected(lhs[0].Pos(), "1 expression")
1844 // continue with first expression
1846 comm = &ast.ExprStmt{X: lhs[0]}
1850 p.expect(token.DEFAULT)
1853 colon := p.expect(token.COLON)
1854 body := p.parseStmtList()
1857 return &ast.CommClause{Case: pos, Comm: comm, Colon: colon, Body: body}
1860 func (p *parser) parseSelectStmt() *ast.SelectStmt {
1862 defer un(trace(p, "SelectStmt"))
1865 pos := p.expect(token.SELECT)
1866 lbrace := p.expect(token.LBRACE)
1868 for p.tok == token.CASE || p.tok == token.DEFAULT {
1869 list = append(list, p.parseCommClause())
1871 rbrace := p.expect(token.RBRACE)
1873 body := &ast.BlockStmt{Lbrace: lbrace, List: list, Rbrace: rbrace}
1875 return &ast.SelectStmt{Select: pos, Body: body}
1878 func (p *parser) parseForStmt() ast.Stmt {
1880 defer un(trace(p, "ForStmt"))
1883 pos := p.expect(token.FOR)
1885 defer p.closeScope()
1887 var s1, s2, s3 ast.Stmt
1889 if p.tok != token.LBRACE {
1890 prevLev := p.exprLev
1892 if p.tok != token.SEMICOLON {
1893 s2, isRange = p.parseSimpleStmt(rangeOk)
1895 if !isRange && p.tok == token.SEMICOLON {
1899 if p.tok != token.SEMICOLON {
1900 s2, _ = p.parseSimpleStmt(basic)
1903 if p.tok != token.LBRACE {
1904 s3, _ = p.parseSimpleStmt(basic)
1910 body := p.parseBlockStmt()
1914 as := s2.(*ast.AssignStmt)
1916 var key, value ast.Expr
1917 switch len(as.Lhs) {
1919 key, value = as.Lhs[0], as.Lhs[1]
1923 p.errorExpected(as.Lhs[0].Pos(), "1 or 2 expressions")
1924 return &ast.BadStmt{From: pos, To: body.End()}
1926 // parseSimpleStmt returned a right-hand side that
1927 // is a single unary expression of the form "range x"
1928 x := as.Rhs[0].(*ast.UnaryExpr).X
1929 return &ast.RangeStmt{
1940 // regular for statement
1941 return &ast.ForStmt{
1944 Cond: p.makeExpr(s2),
1950 func (p *parser) parseStmt() (s ast.Stmt) {
1952 defer un(trace(p, "Statement"))
1956 case token.CONST, token.TYPE, token.VAR:
1957 s = &ast.DeclStmt{Decl: p.parseDecl(syncStmt)}
1959 // tokens that may start an expression
1960 token.IDENT, token.INT, token.FLOAT, token.IMAG, token.CHAR, token.STRING, token.FUNC, token.LPAREN, // operands
1961 token.LBRACK, token.STRUCT, // composite types
1962 token.ADD, token.SUB, token.MUL, token.AND, token.XOR, token.ARROW, token.NOT: // unary operators
1963 s, _ = p.parseSimpleStmt(labelOk)
1964 // because of the required look-ahead, labeled statements are
1965 // parsed by parseSimpleStmt - don't expect a semicolon after
1967 if _, isLabeledStmt := s.(*ast.LabeledStmt); !isLabeledStmt {
1973 s = p.parseDeferStmt()
1975 s = p.parseReturnStmt()
1976 case token.BREAK, token.CONTINUE, token.GOTO, token.FALLTHROUGH:
1977 s = p.parseBranchStmt(p.tok)
1979 s = p.parseBlockStmt()
1984 s = p.parseSwitchStmt()
1986 s = p.parseSelectStmt()
1988 s = p.parseForStmt()
1989 case token.SEMICOLON:
1990 s = &ast.EmptyStmt{Semicolon: p.pos}
1993 // a semicolon may be omitted before a closing "}"
1994 s = &ast.EmptyStmt{Semicolon: p.pos}
1996 // no statement found
1998 p.errorExpected(pos, "statement")
2000 s = &ast.BadStmt{From: pos, To: p.pos}
2006 // ----------------------------------------------------------------------------
2009 type parseSpecFunction func(p *parser, doc *ast.CommentGroup, iota int) ast.Spec
2011 func isValidImport(lit string) bool {
2012 const illegalChars = `!"#$%&'()*,:;<=>?[\]^{|}` + "`\uFFFD"
2013 s, _ := strconv.Unquote(lit) // go/scanner returns a legal string literal
2014 for _, r := range s {
2015 if !unicode.IsGraphic(r) || unicode.IsSpace(r) || strings.ContainsRune(illegalChars, r) {
2022 func parseImportSpec(p *parser, doc *ast.CommentGroup, _ int) ast.Spec {
2024 defer un(trace(p, "ImportSpec"))
2027 var ident *ast.Ident
2030 ident = &ast.Ident{NamePos: p.pos, Name: "."}
2033 ident = p.parseIdent()
2036 var path *ast.BasicLit
2037 if p.tok == token.STRING {
2038 if !isValidImport(p.lit) {
2039 p.error(p.pos, "invalid import path: "+p.lit)
2041 path = &ast.BasicLit{ValuePos: p.pos, Kind: p.tok, Value: p.lit}
2044 p.expect(token.STRING) // use expect() error handling
2046 p.expectSemi() // call before accessing p.linecomment
2049 spec := &ast.ImportSpec{
2053 Comment: p.lineComment,
2055 p.imports = append(p.imports, spec)
2060 func parseConstSpec(p *parser, doc *ast.CommentGroup, iota int) ast.Spec {
2062 defer un(trace(p, "ConstSpec"))
2065 idents := p.parseIdentList()
2067 var values []ast.Expr
2068 if typ != nil || p.tok == token.ASSIGN || iota == 0 {
2069 p.expect(token.ASSIGN)
2070 values = p.parseRhsList()
2072 p.expectSemi() // call before accessing p.linecomment
2074 // Go spec: The scope of a constant or variable identifier declared inside
2075 // a function begins at the end of the ConstSpec or VarSpec and ends at
2076 // the end of the innermost containing block.
2077 // (Global identifiers are resolved in a separate phase after parsing.)
2078 spec := &ast.ValueSpec{
2083 Comment: p.lineComment,
2085 p.declare(spec, iota, p.topScope, ast.Con, idents...)
2090 func parseTypeSpec(p *parser, doc *ast.CommentGroup, _ int) ast.Spec {
2092 defer un(trace(p, "TypeSpec"))
2095 ident := p.parseIdent()
2097 // Go spec: The scope of a type identifier declared inside a function begins
2098 // at the identifier in the TypeSpec and ends at the end of the innermost
2099 // containing block.
2100 // (Global identifiers are resolved in a separate phase after parsing.)
2101 spec := &ast.TypeSpec{Doc: doc, Name: ident}
2102 p.declare(spec, nil, p.topScope, ast.Typ, ident)
2104 spec.Type = p.parseType()
2105 p.expectSemi() // call before accessing p.linecomment
2106 spec.Comment = p.lineComment
2111 func parseVarSpec(p *parser, doc *ast.CommentGroup, _ int) ast.Spec {
2113 defer un(trace(p, "VarSpec"))
2116 idents := p.parseIdentList()
2118 var values []ast.Expr
2119 if typ == nil || p.tok == token.ASSIGN {
2120 p.expect(token.ASSIGN)
2121 values = p.parseRhsList()
2123 p.expectSemi() // call before accessing p.linecomment
2125 // Go spec: The scope of a constant or variable identifier declared inside
2126 // a function begins at the end of the ConstSpec or VarSpec and ends at
2127 // the end of the innermost containing block.
2128 // (Global identifiers are resolved in a separate phase after parsing.)
2129 spec := &ast.ValueSpec{
2134 Comment: p.lineComment,
2136 p.declare(spec, nil, p.topScope, ast.Var, idents...)
2141 func (p *parser) parseGenDecl(keyword token.Token, f parseSpecFunction) *ast.GenDecl {
2143 defer un(trace(p, "GenDecl("+keyword.String()+")"))
2146 doc := p.leadComment
2147 pos := p.expect(keyword)
2148 var lparen, rparen token.Pos
2150 if p.tok == token.LPAREN {
2153 for iota := 0; p.tok != token.RPAREN && p.tok != token.EOF; iota++ {
2154 list = append(list, f(p, p.leadComment, iota))
2156 rparen = p.expect(token.RPAREN)
2159 list = append(list, f(p, nil, 0))
2162 return &ast.GenDecl{
2172 func (p *parser) parseReceiver(scope *ast.Scope) *ast.FieldList {
2174 defer un(trace(p, "Receiver"))
2177 par := p.parseParameters(scope, false)
2179 // must have exactly one receiver
2180 if par.NumFields() != 1 {
2181 p.errorExpected(par.Opening, "exactly one receiver")
2182 par.List = []*ast.Field{{Type: &ast.BadExpr{From: par.Opening, To: par.Closing + 1}}}
2186 // recv type must be of the form ["*"] identifier
2188 base := deref(recv.Type)
2189 if _, isIdent := base.(*ast.Ident); !isIdent {
2190 if _, isBad := base.(*ast.BadExpr); !isBad {
2191 // only report error if it's a new one
2192 p.errorExpected(base.Pos(), "(unqualified) identifier")
2194 par.List = []*ast.Field{
2195 {Type: &ast.BadExpr{From: recv.Pos(), To: recv.End()}},
2202 func (p *parser) parseFuncDecl() *ast.FuncDecl {
2204 defer un(trace(p, "FunctionDecl"))
2207 doc := p.leadComment
2208 pos := p.expect(token.FUNC)
2209 scope := ast.NewScope(p.topScope) // function scope
2211 var recv *ast.FieldList
2212 if p.tok == token.LPAREN {
2213 recv = p.parseReceiver(scope)
2216 ident := p.parseIdent()
2218 params, results := p.parseSignature(scope)
2220 var body *ast.BlockStmt
2221 if p.tok == token.LBRACE {
2222 body = p.parseBody(scope)
2226 decl := &ast.FuncDecl{
2230 Type: &ast.FuncType{
2238 // Go spec: The scope of an identifier denoting a constant, type,
2239 // variable, or function (but not method) declared at top level
2240 // (outside any function) is the package block.
2242 // init() functions cannot be referred to and there may
2243 // be more than one - don't put them in the pkgScope
2244 if ident.Name != "init" {
2245 p.declare(decl, nil, p.pkgScope, ast.Fun, ident)
2252 func (p *parser) parseDecl(sync func(*parser)) ast.Decl {
2254 defer un(trace(p, "Declaration"))
2257 var f parseSpecFunction
2269 return p.parseFuncDecl()
2273 p.errorExpected(pos, "declaration")
2275 return &ast.BadDecl{From: pos, To: p.pos}
2278 return p.parseGenDecl(p.tok, f)
2281 // ----------------------------------------------------------------------------
2284 func (p *parser) parseFile() *ast.File {
2286 defer un(trace(p, "File"))
2290 doc := p.leadComment
2291 pos := p.expect(token.PACKAGE)
2292 // Go spec: The package clause is not a declaration;
2293 // the package name does not appear in any scope.
2294 ident := p.parseIdent()
2295 if ident.Name == "_" {
2296 p.error(p.pos, "invalid package name _")
2300 var decls []ast.Decl
2302 // Don't bother parsing the rest if we had errors already.
2303 // Likely not a Go source file at all.
2305 if p.errors.Len() == 0 && p.mode&PackageClauseOnly == 0 {
2307 for p.tok == token.IMPORT {
2308 decls = append(decls, p.parseGenDecl(token.IMPORT, parseImportSpec))
2311 if p.mode&ImportsOnly == 0 {
2312 // rest of package body
2313 for p.tok != token.EOF {
2314 decls = append(decls, p.parseDecl(syncDecl))
2319 assert(p.topScope == p.pkgScope, "imbalanced scopes")
2321 // resolve global identifiers within the same file
2323 for _, ident := range p.unresolved {
2324 // i <= index for current ident
2325 assert(ident.Obj == unresolved, "object already resolved")
2326 ident.Obj = p.pkgScope.Lookup(ident.Name) // also removes unresolved sentinel
2327 if ident.Obj == nil {
2328 p.unresolved[i] = ident
2340 Unresolved: p.unresolved[0:i],
2341 Comments: p.comments,