1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // A parser for Go source files. Input may be provided in a variety of
6 // forms (see the various Parse* functions); the output is an abstract
7 // syntax tree (AST) representing the Go source. The parser is invoked
8 // through one of the Parse* functions.
20 // noPos is used when there is no corresponding source position for a token.
21 var noPos token.Position
24 // The mode parameter to the Parse* functions is a set of flags (or 0).
25 // They control the amount of source code parsed and other optional
26 // parser functionality.
29 PackageClauseOnly uint = 1 << iota // parsing stops after package clause
30 ImportsOnly // parsing stops after import declarations
31 ParseComments // parse comments and add them to AST
32 Trace // print a trace of parsed productions
36 // The parser structure holds the parser's internal state.
40 scanner scanner.Scanner
43 mode uint // parsing mode
44 trace bool // == (mode & Trace != 0)
45 indent uint // indentation used for tracing output
48 comments []*ast.CommentGroup
49 leadComment *ast.CommentGroup // the last lead comment
50 lineComment *ast.CommentGroup // the last line comment
53 pos token.Pos // token position
54 tok token.Token // one token look-ahead
55 lit []byte // token literal
57 // Non-syntactic parser control
58 exprLev int // < 0: in control clause, >= 0: in expression
62 // scannerMode returns the scanner mode bits given the parser's mode bits.
63 func scannerMode(mode uint) uint {
64 var m uint = scanner.InsertSemis
65 if mode&ParseComments != 0 {
66 m |= scanner.ScanComments
72 func (p *parser) init(fset *token.FileSet, filename string, src []byte, mode uint) {
73 p.file = fset.AddFile(filename, fset.Base(), len(src))
74 p.scanner.Init(p.file, src, p, scannerMode(mode))
76 p.trace = mode&Trace != 0 // for convenience (p.trace is used frequently)
81 // ----------------------------------------------------------------------------
84 func (p *parser) printTrace(a ...interface{}) {
85 const dots = ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . " +
86 ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
87 const n = uint(len(dots))
88 pos := p.file.Position(p.pos)
89 fmt.Printf("%5d:%3d: ", pos.Line, pos.Column)
99 func trace(p *parser, msg string) *parser {
100 p.printTrace(msg, "(")
106 // Usage pattern: defer un(trace(p, "..."));
113 // Advance to the next token.
114 func (p *parser) next0() {
115 // Because of one-token look-ahead, print the previous token
116 // when tracing as it provides a more readable output. The
117 // very first token (!p.pos.IsValid()) is not initialized
118 // (it is token.ILLEGAL), so don't print it .
119 if p.trace && p.pos.IsValid() {
122 case p.tok.IsLiteral():
123 p.printTrace(s, string(p.lit))
124 case p.tok.IsOperator(), p.tok.IsKeyword():
125 p.printTrace("\"" + s + "\"")
131 p.pos, p.tok, p.lit = p.scanner.Scan()
134 // Consume a comment and return it and the line on which it ends.
135 func (p *parser) consumeComment() (comment *ast.Comment, endline int) {
136 // /*-style comments may end on a different line than where they start.
137 // Scan the comment for '\n' chars and adjust endline accordingly.
138 endline = p.file.Line(p.pos)
140 for _, b := range p.lit {
147 comment = &ast.Comment{p.pos, p.lit}
154 // Consume a group of adjacent comments, add it to the parser's
155 // comments list, and return it together with the line at which
156 // the last comment in the group ends. An empty line or non-comment
157 // token terminates a comment group.
159 func (p *parser) consumeCommentGroup() (comments *ast.CommentGroup, endline int) {
160 var list []*ast.Comment
161 endline = p.file.Line(p.pos)
162 for p.tok == token.COMMENT && endline+1 >= p.file.Line(p.pos) {
163 var comment *ast.Comment
164 comment, endline = p.consumeComment()
165 list = append(list, comment)
168 // add comment group to the comments list
169 comments = &ast.CommentGroup{list}
170 p.comments = append(p.comments, comments)
176 // Advance to the next non-comment token. In the process, collect
177 // any comment groups encountered, and remember the last lead and
178 // and line comments.
180 // A lead comment is a comment group that starts and ends in a
181 // line without any other tokens and that is followed by a non-comment
182 // token on the line immediately after the comment group.
184 // A line comment is a comment group that follows a non-comment
185 // token on the same line, and that has no tokens after it on the line
188 // Lead and line comments may be considered documentation that is
189 // stored in the AST.
191 func (p *parser) next() {
194 line := p.file.Line(p.pos) // current line
197 if p.tok == token.COMMENT {
198 var comment *ast.CommentGroup
201 if p.file.Line(p.pos) == line {
202 // The comment is on same line as previous token; it
203 // cannot be a lead comment but may be a line comment.
204 comment, endline = p.consumeCommentGroup()
205 if p.file.Line(p.pos) != endline {
206 // The next token is on a different line, thus
207 // the last comment group is a line comment.
208 p.lineComment = comment
212 // consume successor comments, if any
214 for p.tok == token.COMMENT {
215 comment, endline = p.consumeCommentGroup()
218 if endline+1 == p.file.Line(p.pos) {
219 // The next token is following on the line immediately after the
220 // comment group, thus the last comment group is a lead comment.
221 p.leadComment = comment
227 func (p *parser) error(pos token.Pos, msg string) {
228 p.Error(p.file.Position(pos), msg)
232 func (p *parser) errorExpected(pos token.Pos, msg string) {
233 msg = "expected " + msg
235 // the error happened at the current position;
236 // make the error message more specific
237 if p.tok == token.SEMICOLON && p.lit[0] == '\n' {
238 msg += ", found newline"
240 msg += ", found '" + p.tok.String() + "'"
241 if p.tok.IsLiteral() {
242 msg += " " + string(p.lit)
250 func (p *parser) expect(tok token.Token) token.Pos {
253 p.errorExpected(pos, "'"+tok.String()+"'")
255 p.next() // make progress
260 func (p *parser) expectSemi() {
261 if p.tok != token.RPAREN && p.tok != token.RBRACE {
262 p.expect(token.SEMICOLON)
267 // ----------------------------------------------------------------------------
270 func (p *parser) parseIdent() *ast.Ident {
273 if p.tok == token.IDENT {
277 p.expect(token.IDENT) // use expect() error handling
279 return &ast.Ident{pos, name, nil}
283 func (p *parser) parseIdentList() (list []*ast.Ident) {
285 defer un(trace(p, "IdentList"))
288 list = append(list, p.parseIdent())
289 for p.tok == token.COMMA {
291 list = append(list, p.parseIdent())
298 // ----------------------------------------------------------------------------
299 // Common productions
301 func (p *parser) parseExprList() (list []ast.Expr) {
303 defer un(trace(p, "ExpressionList"))
306 list = append(list, p.parseExpr())
307 for p.tok == token.COMMA {
309 list = append(list, p.parseExpr())
316 // ----------------------------------------------------------------------------
319 func (p *parser) parseType() ast.Expr {
321 defer un(trace(p, "Type"))
328 p.errorExpected(pos, "type")
329 p.next() // make progress
330 return &ast.BadExpr{pos, p.pos}
337 func (p *parser) parseQualifiedIdent() ast.Expr {
339 defer un(trace(p, "QualifiedIdent"))
342 var x ast.Expr = p.parseIdent()
343 if p.tok == token.PERIOD {
344 // first identifier is a package identifier
346 sel := p.parseIdent()
347 x = &ast.SelectorExpr{x, sel}
353 func (p *parser) parseTypeName() ast.Expr {
355 defer un(trace(p, "TypeName"))
358 return p.parseQualifiedIdent()
362 func (p *parser) parseArrayType(ellipsisOk bool) ast.Expr {
364 defer un(trace(p, "ArrayType"))
367 lbrack := p.expect(token.LBRACK)
369 if ellipsisOk && p.tok == token.ELLIPSIS {
370 len = &ast.Ellipsis{p.pos, nil}
372 } else if p.tok != token.RBRACK {
375 p.expect(token.RBRACK)
378 return &ast.ArrayType{lbrack, len, elt}
382 func (p *parser) makeIdentList(list []ast.Expr) []*ast.Ident {
383 idents := make([]*ast.Ident, len(list))
384 for i, x := range list {
385 ident, isIdent := x.(*ast.Ident)
387 pos := x.(ast.Expr).Pos()
388 p.errorExpected(pos, "identifier")
389 ident = &ast.Ident{pos, "_", nil}
397 func (p *parser) parseFieldDecl() *ast.Field {
399 defer un(trace(p, "FieldDecl"))
405 list, typ := p.parseVarList(false)
408 var tag *ast.BasicLit
409 if p.tok == token.STRING {
410 tag = &ast.BasicLit{p.pos, p.tok, p.lit}
415 var idents []*ast.Ident
417 // IdentifierList Type
418 idents = p.makeIdentList(list)
420 // ["*"] TypeName (AnonymousField)
421 typ = list[0] // we always have at least one element
422 if n := len(list); n > 1 || !isTypeName(deref(typ)) {
424 p.errorExpected(pos, "anonymous field")
425 typ = &ast.BadExpr{pos, list[n-1].End()}
431 return &ast.Field{doc, idents, typ, tag, p.lineComment}
435 func (p *parser) parseStructType() *ast.StructType {
437 defer un(trace(p, "StructType"))
440 pos := p.expect(token.STRUCT)
441 lbrace := p.expect(token.LBRACE)
442 var list []*ast.Field
443 for p.tok == token.IDENT || p.tok == token.MUL || p.tok == token.LPAREN {
444 // a field declaration cannot start with a '(' but we accept
445 // it here for more robust parsing and better error messages
446 // (parseFieldDecl will check and complain if necessary)
447 list = append(list, p.parseFieldDecl())
449 rbrace := p.expect(token.RBRACE)
451 return &ast.StructType{pos, &ast.FieldList{lbrace, list, rbrace}, false}
455 func (p *parser) parsePointerType() *ast.StarExpr {
457 defer un(trace(p, "PointerType"))
460 star := p.expect(token.MUL)
461 base := p.parseType()
463 return &ast.StarExpr{star, base}
467 func (p *parser) tryVarType(isParam bool) ast.Expr {
468 if isParam && p.tok == token.ELLIPSIS {
471 typ := p.tryType() // don't use parseType so we can provide better error message
473 p.error(pos, "'...' parameter is missing type")
474 typ = &ast.BadExpr{pos, p.pos}
476 if p.tok != token.RPAREN {
477 p.error(pos, "can use '...' with last parameter type only")
479 return &ast.Ellipsis{pos, typ}
485 func (p *parser) parseVarType(isParam bool) ast.Expr {
486 typ := p.tryVarType(isParam)
489 p.errorExpected(pos, "type")
490 p.next() // make progress
491 typ = &ast.BadExpr{pos, p.pos}
497 func (p *parser) parseVarList(isParam bool) (list []ast.Expr, typ ast.Expr) {
499 defer un(trace(p, "VarList"))
502 // a list of identifiers looks like a list of type names
504 // parseVarType accepts any type (including parenthesized ones)
505 // even though the syntax does not permit them here: we
506 // accept them all for more robust parsing and complain
508 list = append(list, p.parseVarType(isParam))
509 if p.tok != token.COMMA {
515 // if we had a list of identifiers, it must be followed by a type
516 typ = p.tryVarType(isParam)
522 func (p *parser) parseParameterList(ellipsisOk bool) (params []*ast.Field) {
524 defer un(trace(p, "ParameterList"))
527 list, typ := p.parseVarList(ellipsisOk)
529 // IdentifierList Type
530 idents := p.makeIdentList(list)
531 params = append(params, &ast.Field{nil, idents, typ, nil, nil})
532 if p.tok == token.COMMA {
536 for p.tok != token.RPAREN && p.tok != token.EOF {
537 idents := p.parseIdentList()
538 typ := p.parseVarType(ellipsisOk)
539 params = append(params, &ast.Field{nil, idents, typ, nil, nil})
540 if p.tok != token.COMMA {
547 // Type { "," Type } (anonymous parameters)
548 params = make([]*ast.Field, len(list))
549 for i, x := range list {
550 params[i] = &ast.Field{Type: x}
558 func (p *parser) parseParameters(ellipsisOk bool) *ast.FieldList {
560 defer un(trace(p, "Parameters"))
563 var params []*ast.Field
564 lparen := p.expect(token.LPAREN)
565 if p.tok != token.RPAREN {
566 params = p.parseParameterList(ellipsisOk)
568 rparen := p.expect(token.RPAREN)
570 return &ast.FieldList{lparen, params, rparen}
574 func (p *parser) parseResult() *ast.FieldList {
576 defer un(trace(p, "Result"))
579 if p.tok == token.LPAREN {
580 return p.parseParameters(false)
585 list := make([]*ast.Field, 1)
586 list[0] = &ast.Field{Type: typ}
587 return &ast.FieldList{List: list}
594 func (p *parser) parseSignature() (params, results *ast.FieldList) {
596 defer un(trace(p, "Signature"))
599 params = p.parseParameters(true)
600 results = p.parseResult()
606 func (p *parser) parseFuncType() *ast.FuncType {
608 defer un(trace(p, "FuncType"))
611 pos := p.expect(token.FUNC)
612 params, results := p.parseSignature()
614 return &ast.FuncType{pos, params, results}
618 func (p *parser) parseMethodSpec() *ast.Field {
620 defer un(trace(p, "MethodSpec"))
624 var idents []*ast.Ident
626 x := p.parseQualifiedIdent()
627 if ident, isIdent := x.(*ast.Ident); isIdent && p.tok == token.LPAREN {
629 idents = []*ast.Ident{ident}
630 params, results := p.parseSignature()
631 typ = &ast.FuncType{token.NoPos, params, results}
633 // embedded interface
638 return &ast.Field{doc, idents, typ, nil, p.lineComment}
642 func (p *parser) parseInterfaceType() *ast.InterfaceType {
644 defer un(trace(p, "InterfaceType"))
647 pos := p.expect(token.INTERFACE)
648 lbrace := p.expect(token.LBRACE)
649 var list []*ast.Field
650 for p.tok == token.IDENT {
651 list = append(list, p.parseMethodSpec())
653 rbrace := p.expect(token.RBRACE)
655 return &ast.InterfaceType{pos, &ast.FieldList{lbrace, list, rbrace}, false}
659 func (p *parser) parseMapType() *ast.MapType {
661 defer un(trace(p, "MapType"))
664 pos := p.expect(token.MAP)
665 p.expect(token.LBRACK)
667 p.expect(token.RBRACK)
668 value := p.parseType()
670 return &ast.MapType{pos, key, value}
674 func (p *parser) parseChanType() *ast.ChanType {
676 defer un(trace(p, "ChanType"))
680 dir := ast.SEND | ast.RECV
681 if p.tok == token.CHAN {
683 if p.tok == token.ARROW {
688 p.expect(token.ARROW)
692 value := p.parseType()
694 return &ast.ChanType{pos, dir, value}
698 func (p *parser) tryRawType(ellipsisOk bool) ast.Expr {
701 return p.parseTypeName()
703 return p.parseArrayType(ellipsisOk)
705 return p.parseStructType()
707 return p.parsePointerType()
709 return p.parseFuncType()
710 case token.INTERFACE:
711 return p.parseInterfaceType()
713 return p.parseMapType()
714 case token.CHAN, token.ARROW:
715 return p.parseChanType()
720 rparen := p.expect(token.RPAREN)
721 return &ast.ParenExpr{lparen, typ, rparen}
729 func (p *parser) tryType() ast.Expr { return p.tryRawType(false) }
732 // ----------------------------------------------------------------------------
735 func (p *parser) parseStmtList() (list []ast.Stmt) {
737 defer un(trace(p, "StatementList"))
740 for p.tok != token.CASE && p.tok != token.DEFAULT && p.tok != token.RBRACE && p.tok != token.EOF {
741 list = append(list, p.parseStmt())
748 func (p *parser) parseBody() *ast.BlockStmt {
750 defer un(trace(p, "Body"))
753 lbrace := p.expect(token.LBRACE)
754 list := p.parseStmtList()
755 rbrace := p.expect(token.RBRACE)
757 return &ast.BlockStmt{lbrace, list, rbrace}
761 func (p *parser) parseBlockStmt() *ast.BlockStmt {
763 defer un(trace(p, "BlockStmt"))
766 lbrace := p.expect(token.LBRACE)
767 list := p.parseStmtList()
768 rbrace := p.expect(token.RBRACE)
770 return &ast.BlockStmt{lbrace, list, rbrace}
774 // ----------------------------------------------------------------------------
777 func (p *parser) parseFuncTypeOrLit() ast.Expr {
779 defer un(trace(p, "FuncTypeOrLit"))
782 typ := p.parseFuncType()
783 if p.tok != token.LBRACE {
784 // function type only
789 body := p.parseBody()
792 return &ast.FuncLit{typ, body}
796 // parseOperand may return an expression or a raw type (incl. array
797 // types of the form [...]T. Callers must verify the result.
799 func (p *parser) parseOperand() ast.Expr {
801 defer un(trace(p, "Operand"))
806 return p.parseIdent()
808 case token.INT, token.FLOAT, token.IMAG, token.CHAR, token.STRING:
809 x := &ast.BasicLit{p.pos, p.tok, p.lit}
819 rparen := p.expect(token.RPAREN)
820 return &ast.ParenExpr{lparen, x, rparen}
823 return p.parseFuncTypeOrLit()
826 t := p.tryRawType(true) // could be type for composite literal or conversion
833 p.errorExpected(pos, "operand")
834 p.next() // make progress
835 return &ast.BadExpr{pos, p.pos}
839 func (p *parser) parseSelectorOrTypeAssertion(x ast.Expr) ast.Expr {
841 defer un(trace(p, "SelectorOrTypeAssertion"))
844 p.expect(token.PERIOD)
845 if p.tok == token.IDENT {
847 sel := p.parseIdent()
848 return &ast.SelectorExpr{x, sel}
852 p.expect(token.LPAREN)
854 if p.tok == token.TYPE {
855 // type switch: typ == nil
860 p.expect(token.RPAREN)
862 return &ast.TypeAssertExpr{x, typ}
866 func (p *parser) parseIndexOrSlice(x ast.Expr) ast.Expr {
868 defer un(trace(p, "IndexOrSlice"))
871 lbrack := p.expect(token.LBRACK)
873 var low, high ast.Expr
875 if p.tok != token.COLON {
878 if p.tok == token.COLON {
881 if p.tok != token.RBRACK {
886 rbrack := p.expect(token.RBRACK)
889 return &ast.SliceExpr{x, lbrack, low, high, rbrack}
891 return &ast.IndexExpr{x, lbrack, low, rbrack}
895 func (p *parser) parseCallOrConversion(fun ast.Expr) *ast.CallExpr {
897 defer un(trace(p, "CallOrConversion"))
900 lparen := p.expect(token.LPAREN)
903 var ellipsis token.Pos
904 for p.tok != token.RPAREN && p.tok != token.EOF && !ellipsis.IsValid() {
905 list = append(list, p.parseExpr())
906 if p.tok == token.ELLIPSIS {
910 if p.tok != token.COMMA {
916 rparen := p.expect(token.RPAREN)
918 return &ast.CallExpr{fun, lparen, list, ellipsis, rparen}
922 func (p *parser) parseElement(keyOk bool) ast.Expr {
924 defer un(trace(p, "Element"))
927 if p.tok == token.LBRACE {
928 return p.parseLiteralValue(nil)
932 if keyOk && p.tok == token.COLON {
935 x = &ast.KeyValueExpr{x, colon, p.parseElement(false)}
941 func (p *parser) parseElementList() (list []ast.Expr) {
943 defer un(trace(p, "ElementList"))
946 for p.tok != token.RBRACE && p.tok != token.EOF {
947 list = append(list, p.parseElement(true))
948 if p.tok != token.COMMA {
958 func (p *parser) parseLiteralValue(typ ast.Expr) ast.Expr {
960 defer un(trace(p, "LiteralValue"))
963 lbrace := p.expect(token.LBRACE)
966 if p.tok != token.RBRACE {
967 elts = p.parseElementList()
970 rbrace := p.expect(token.RBRACE)
971 return &ast.CompositeLit{typ, lbrace, elts, rbrace}
975 // checkExpr checks that x is an expression (and not a type).
976 func (p *parser) checkExpr(x ast.Expr) ast.Expr {
977 switch t := unparen(x).(type) {
982 case *ast.CompositeLit:
985 case *ast.SelectorExpr:
988 case *ast.TypeAssertExpr:
990 // the form X.(type) is only allowed in type switch expressions
991 p.errorExpected(x.Pos(), "expression")
992 x = &ast.BadExpr{x.Pos(), x.End()}
997 if t.Op == token.RANGE {
998 // the range operator is only allowed at the top of a for statement
999 p.errorExpected(x.Pos(), "expression")
1000 x = &ast.BadExpr{x.Pos(), x.End()}
1002 case *ast.BinaryExpr:
1004 // all other nodes are not proper expressions
1005 p.errorExpected(x.Pos(), "expression")
1006 x = &ast.BadExpr{x.Pos(), x.End()}
1012 // isTypeName returns true iff x is a (qualified) TypeName.
1013 func isTypeName(x ast.Expr) bool {
1014 switch t := x.(type) {
1017 case *ast.SelectorExpr:
1018 _, isIdent := t.X.(*ast.Ident)
1021 return false // all other nodes are not type names
1027 // isLiteralType returns true iff x is a legal composite literal type.
1028 func isLiteralType(x ast.Expr) bool {
1029 switch t := x.(type) {
1032 case *ast.SelectorExpr:
1033 _, isIdent := t.X.(*ast.Ident)
1035 case *ast.ArrayType:
1036 case *ast.StructType:
1039 return false // all other nodes are not legal composite literal types
1045 // If x is of the form *T, deref returns T, otherwise it returns x.
1046 func deref(x ast.Expr) ast.Expr {
1047 if p, isPtr := x.(*ast.StarExpr); isPtr {
1054 // If x is of the form (T), unparen returns unparen(T), otherwise it returns x.
1055 func unparen(x ast.Expr) ast.Expr {
1056 if p, isParen := x.(*ast.ParenExpr); isParen {
1063 // checkExprOrType checks that x is an expression or a type
1064 // (and not a raw type such as [...]T).
1066 func (p *parser) checkExprOrType(x ast.Expr) ast.Expr {
1067 switch t := unparen(x).(type) {
1068 case *ast.ParenExpr:
1069 panic("unreachable")
1070 case *ast.UnaryExpr:
1071 if t.Op == token.RANGE {
1072 // the range operator is only allowed at the top of a for statement
1073 p.errorExpected(x.Pos(), "expression")
1074 x = &ast.BadExpr{x.Pos(), x.End()}
1076 case *ast.ArrayType:
1077 if len, isEllipsis := t.Len.(*ast.Ellipsis); isEllipsis {
1078 p.error(len.Pos(), "expected array length, found '...'")
1079 x = &ast.BadExpr{x.Pos(), x.End()}
1083 // all other nodes are expressions or types
1088 func (p *parser) parsePrimaryExpr() ast.Expr {
1090 defer un(trace(p, "PrimaryExpr"))
1093 x := p.parseOperand()
1098 x = p.parseSelectorOrTypeAssertion(p.checkExpr(x))
1100 x = p.parseIndexOrSlice(p.checkExpr(x))
1102 x = p.parseCallOrConversion(p.checkExprOrType(x))
1104 if isLiteralType(x) && (p.exprLev >= 0 || !isTypeName(x)) {
1105 x = p.parseLiteralValue(x)
1118 func (p *parser) parseUnaryExpr() ast.Expr {
1120 defer un(trace(p, "UnaryExpr"))
1124 case token.ADD, token.SUB, token.NOT, token.XOR, token.AND, token.RANGE:
1125 pos, op := p.pos, p.tok
1127 x := p.parseUnaryExpr()
1128 return &ast.UnaryExpr{pos, op, p.checkExpr(x)}
1131 // channel type or receive expression
1134 if p.tok == token.CHAN {
1136 value := p.parseType()
1137 return &ast.ChanType{pos, ast.RECV, value}
1140 x := p.parseUnaryExpr()
1141 return &ast.UnaryExpr{pos, token.ARROW, p.checkExpr(x)}
1144 // pointer type or unary "*" expression
1147 x := p.parseUnaryExpr()
1148 return &ast.StarExpr{pos, p.checkExprOrType(x)}
1151 return p.parsePrimaryExpr()
1155 func (p *parser) parseBinaryExpr(prec1 int) ast.Expr {
1157 defer un(trace(p, "BinaryExpr"))
1160 x := p.parseUnaryExpr()
1161 for prec := p.tok.Precedence(); prec >= prec1; prec-- {
1162 for p.tok.Precedence() == prec {
1163 pos, op := p.pos, p.tok
1165 y := p.parseBinaryExpr(prec + 1)
1166 x = &ast.BinaryExpr{p.checkExpr(x), pos, op, p.checkExpr(y)}
1174 // TODO(gri): parseExpr may return a type or even a raw type ([..]int) -
1175 // should reject when a type/raw type is obviously not allowed
1176 func (p *parser) parseExpr() ast.Expr {
1178 defer un(trace(p, "Expression"))
1181 return p.parseBinaryExpr(token.LowestPrec + 1)
1185 // ----------------------------------------------------------------------------
1188 func (p *parser) parseSimpleStmt(labelOk bool) ast.Stmt {
1190 defer un(trace(p, "SimpleStmt"))
1193 x := p.parseExprList()
1197 // labeled statement
1200 if labelOk && len(x) == 1 {
1201 if label, isIdent := x[0].(*ast.Ident); isIdent {
1202 return &ast.LabeledStmt{label, colon, p.parseStmt()}
1205 p.error(x[0].Pos(), "illegal label declaration")
1206 return &ast.BadStmt{x[0].Pos(), colon + 1}
1209 token.DEFINE, token.ASSIGN, token.ADD_ASSIGN,
1210 token.SUB_ASSIGN, token.MUL_ASSIGN, token.QUO_ASSIGN,
1211 token.REM_ASSIGN, token.AND_ASSIGN, token.OR_ASSIGN,
1212 token.XOR_ASSIGN, token.SHL_ASSIGN, token.SHR_ASSIGN, token.AND_NOT_ASSIGN:
1213 // assignment statement
1214 pos, tok := p.pos, p.tok
1216 y := p.parseExprList()
1217 return &ast.AssignStmt{x, pos, tok, y}
1221 p.error(x[0].Pos(), "only one expression allowed")
1222 // continue with first expression
1225 if p.tok == token.INC || p.tok == token.DEC {
1226 // increment or decrement
1227 s := &ast.IncDecStmt{x[0], p.pos, p.tok}
1228 p.next() // consume "++" or "--"
1233 return &ast.ExprStmt{x[0]}
1237 func (p *parser) parseCallExpr() *ast.CallExpr {
1239 if call, isCall := x.(*ast.CallExpr); isCall {
1242 p.errorExpected(x.Pos(), "function/method call")
1247 func (p *parser) parseGoStmt() ast.Stmt {
1249 defer un(trace(p, "GoStmt"))
1252 pos := p.expect(token.GO)
1253 call := p.parseCallExpr()
1256 return &ast.BadStmt{pos, pos + 2} // len("go")
1259 return &ast.GoStmt{pos, call}
1263 func (p *parser) parseDeferStmt() ast.Stmt {
1265 defer un(trace(p, "DeferStmt"))
1268 pos := p.expect(token.DEFER)
1269 call := p.parseCallExpr()
1272 return &ast.BadStmt{pos, pos + 5} // len("defer")
1275 return &ast.DeferStmt{pos, call}
1279 func (p *parser) parseReturnStmt() *ast.ReturnStmt {
1281 defer un(trace(p, "ReturnStmt"))
1285 p.expect(token.RETURN)
1287 if p.tok != token.SEMICOLON && p.tok != token.RBRACE {
1288 x = p.parseExprList()
1292 return &ast.ReturnStmt{pos, x}
1296 func (p *parser) parseBranchStmt(tok token.Token) *ast.BranchStmt {
1298 defer un(trace(p, "BranchStmt"))
1301 s := &ast.BranchStmt{p.pos, tok, nil}
1303 if tok != token.FALLTHROUGH && p.tok == token.IDENT {
1304 s.Label = p.parseIdent()
1312 func (p *parser) makeExpr(s ast.Stmt) ast.Expr {
1316 if es, isExpr := s.(*ast.ExprStmt); isExpr {
1317 return p.checkExpr(es.X)
1319 p.error(s.Pos(), "expected condition, found simple statement")
1320 return &ast.BadExpr{s.Pos(), s.End()}
1324 func (p *parser) parseControlClause(isForStmt bool) (s1, s2, s3 ast.Stmt) {
1325 if p.tok != token.LBRACE {
1326 prevLev := p.exprLev
1329 if p.tok != token.SEMICOLON {
1330 s1 = p.parseSimpleStmt(false)
1332 if p.tok == token.SEMICOLON {
1334 if p.tok != token.LBRACE && p.tok != token.SEMICOLON {
1335 s2 = p.parseSimpleStmt(false)
1338 // for statements have a 3rd section
1340 if p.tok != token.LBRACE {
1341 s3 = p.parseSimpleStmt(false)
1355 func (p *parser) parseIfStmt() *ast.IfStmt {
1357 defer un(trace(p, "IfStmt"))
1360 pos := p.expect(token.IF)
1361 s1, s2, _ := p.parseControlClause(false)
1362 body := p.parseBlockStmt()
1364 if p.tok == token.ELSE {
1366 else_ = p.parseStmt()
1371 return &ast.IfStmt{pos, s1, p.makeExpr(s2), body, else_}
1375 func (p *parser) parseCaseClause() *ast.CaseClause {
1377 defer un(trace(p, "CaseClause"))
1383 if p.tok == token.CASE {
1385 x = p.parseExprList()
1387 p.expect(token.DEFAULT)
1390 colon := p.expect(token.COLON)
1391 body := p.parseStmtList()
1393 return &ast.CaseClause{pos, x, colon, body}
1397 func (p *parser) parseTypeList() (list []ast.Expr) {
1399 defer un(trace(p, "TypeList"))
1402 list = append(list, p.parseType())
1403 for p.tok == token.COMMA {
1405 list = append(list, p.parseType())
1412 func (p *parser) parseTypeCaseClause() *ast.TypeCaseClause {
1414 defer un(trace(p, "TypeCaseClause"))
1419 var types []ast.Expr
1420 if p.tok == token.CASE {
1422 types = p.parseTypeList()
1424 p.expect(token.DEFAULT)
1427 colon := p.expect(token.COLON)
1428 body := p.parseStmtList()
1430 return &ast.TypeCaseClause{pos, types, colon, body}
1434 func isExprSwitch(s ast.Stmt) bool {
1438 if e, ok := s.(*ast.ExprStmt); ok {
1439 if a, ok := e.X.(*ast.TypeAssertExpr); ok {
1440 return a.Type != nil // regular type assertion
1448 func (p *parser) parseSwitchStmt() ast.Stmt {
1450 defer un(trace(p, "SwitchStmt"))
1453 pos := p.expect(token.SWITCH)
1454 s1, s2, _ := p.parseControlClause(false)
1456 if isExprSwitch(s2) {
1457 lbrace := p.expect(token.LBRACE)
1459 for p.tok == token.CASE || p.tok == token.DEFAULT {
1460 list = append(list, p.parseCaseClause())
1462 rbrace := p.expect(token.RBRACE)
1463 body := &ast.BlockStmt{lbrace, list, rbrace}
1465 return &ast.SwitchStmt{pos, s1, p.makeExpr(s2), body}
1469 // TODO(gri): do all the checks!
1470 lbrace := p.expect(token.LBRACE)
1472 for p.tok == token.CASE || p.tok == token.DEFAULT {
1473 list = append(list, p.parseTypeCaseClause())
1475 rbrace := p.expect(token.RBRACE)
1477 body := &ast.BlockStmt{lbrace, list, rbrace}
1478 return &ast.TypeSwitchStmt{pos, s1, s2, body}
1482 func (p *parser) parseCommClause() *ast.CommClause {
1484 defer un(trace(p, "CommClause"))
1490 var lhs, rhs ast.Expr
1491 if p.tok == token.CASE {
1493 if p.tok == token.ARROW {
1494 // RecvExpr without assignment
1497 // SendExpr or RecvExpr
1499 if p.tok == token.ASSIGN || p.tok == token.DEFINE {
1500 // RecvExpr with assignment
1504 if p.tok == token.ARROW {
1507 p.expect(token.ARROW) // use expect() error handling
1513 p.expect(token.DEFAULT)
1516 colon := p.expect(token.COLON)
1517 body := p.parseStmtList()
1519 return &ast.CommClause{pos, tok, lhs, rhs, colon, body}
1523 func (p *parser) parseSelectStmt() *ast.SelectStmt {
1525 defer un(trace(p, "SelectStmt"))
1528 pos := p.expect(token.SELECT)
1529 lbrace := p.expect(token.LBRACE)
1531 for p.tok == token.CASE || p.tok == token.DEFAULT {
1532 list = append(list, p.parseCommClause())
1534 rbrace := p.expect(token.RBRACE)
1536 body := &ast.BlockStmt{lbrace, list, rbrace}
1538 return &ast.SelectStmt{pos, body}
1542 func (p *parser) parseForStmt() ast.Stmt {
1544 defer un(trace(p, "ForStmt"))
1547 pos := p.expect(token.FOR)
1548 s1, s2, s3 := p.parseControlClause(true)
1549 body := p.parseBlockStmt()
1552 if as, isAssign := s2.(*ast.AssignStmt); isAssign {
1553 // possibly a for statement with a range clause; check assignment operator
1554 if as.Tok != token.ASSIGN && as.Tok != token.DEFINE {
1555 p.errorExpected(as.TokPos, "'=' or ':='")
1556 return &ast.BadStmt{pos, body.End()}
1559 var key, value ast.Expr
1560 switch len(as.Lhs) {
1562 key, value = as.Lhs[0], as.Lhs[1]
1566 p.errorExpected(as.Lhs[0].Pos(), "1 or 2 expressions")
1567 return &ast.BadStmt{pos, body.End()}
1570 if len(as.Rhs) != 1 {
1571 p.errorExpected(as.Rhs[0].Pos(), "1 expressions")
1572 return &ast.BadStmt{pos, body.End()}
1574 if rhs, isUnary := as.Rhs[0].(*ast.UnaryExpr); isUnary && rhs.Op == token.RANGE {
1575 // rhs is range expression; check lhs
1576 return &ast.RangeStmt{pos, key, value, as.TokPos, as.Tok, rhs.X, body}
1578 p.errorExpected(s2.Pos(), "range clause")
1579 return &ast.BadStmt{pos, body.End()}
1582 // regular for statement
1583 return &ast.ForStmt{pos, s1, p.makeExpr(s2), s3, body}
1586 panic("unreachable")
1590 func (p *parser) parseStmt() (s ast.Stmt) {
1592 defer un(trace(p, "Statement"))
1596 case token.CONST, token.TYPE, token.VAR:
1597 s = &ast.DeclStmt{p.parseDecl()}
1599 // tokens that may start a top-level expression
1600 token.IDENT, token.INT, token.FLOAT, token.CHAR, token.STRING, token.FUNC, token.LPAREN, // operand
1601 token.LBRACK, token.STRUCT, // composite type
1602 token.MUL, token.AND, token.ARROW, token.ADD, token.SUB, token.XOR: // unary operators
1603 s = p.parseSimpleStmt(true)
1604 // because of the required look-ahead, labeled statements are
1605 // parsed by parseSimpleStmt - don't expect a semicolon after
1607 if _, isLabeledStmt := s.(*ast.LabeledStmt); !isLabeledStmt {
1613 s = p.parseDeferStmt()
1615 s = p.parseReturnStmt()
1616 case token.BREAK, token.CONTINUE, token.GOTO, token.FALLTHROUGH:
1617 s = p.parseBranchStmt(p.tok)
1619 s = p.parseBlockStmt()
1624 s = p.parseSwitchStmt()
1626 s = p.parseSelectStmt()
1628 s = p.parseForStmt()
1629 case token.SEMICOLON:
1630 s = &ast.EmptyStmt{p.pos}
1633 // a semicolon may be omitted before a closing "}"
1634 s = &ast.EmptyStmt{p.pos}
1636 // no statement found
1638 p.errorExpected(pos, "statement")
1639 p.next() // make progress
1640 s = &ast.BadStmt{pos, p.pos}
1647 // ----------------------------------------------------------------------------
1650 type parseSpecFunction func(p *parser, doc *ast.CommentGroup) ast.Spec
1653 func parseImportSpec(p *parser, doc *ast.CommentGroup) ast.Spec {
1655 defer un(trace(p, "ImportSpec"))
1658 var ident *ast.Ident
1659 if p.tok == token.PERIOD {
1660 ident = &ast.Ident{p.pos, ".", nil}
1662 } else if p.tok == token.IDENT {
1663 ident = p.parseIdent()
1666 var path *ast.BasicLit
1667 if p.tok == token.STRING {
1668 path = &ast.BasicLit{p.pos, p.tok, p.lit}
1671 p.expect(token.STRING) // use expect() error handling
1675 return &ast.ImportSpec{doc, ident, path, p.lineComment}
1679 func parseConstSpec(p *parser, doc *ast.CommentGroup) ast.Spec {
1681 defer un(trace(p, "ConstSpec"))
1684 idents := p.parseIdentList()
1686 var values []ast.Expr
1687 if typ != nil || p.tok == token.ASSIGN {
1688 p.expect(token.ASSIGN)
1689 values = p.parseExprList()
1693 return &ast.ValueSpec{doc, idents, typ, values, p.lineComment}
1697 func parseTypeSpec(p *parser, doc *ast.CommentGroup) ast.Spec {
1699 defer un(trace(p, "TypeSpec"))
1702 ident := p.parseIdent()
1703 typ := p.parseType()
1706 return &ast.TypeSpec{doc, ident, typ, p.lineComment}
1710 func parseVarSpec(p *parser, doc *ast.CommentGroup) ast.Spec {
1712 defer un(trace(p, "VarSpec"))
1715 idents := p.parseIdentList()
1717 var values []ast.Expr
1718 if typ == nil || p.tok == token.ASSIGN {
1719 p.expect(token.ASSIGN)
1720 values = p.parseExprList()
1724 return &ast.ValueSpec{doc, idents, typ, values, p.lineComment}
1728 func (p *parser) parseGenDecl(keyword token.Token, f parseSpecFunction) *ast.GenDecl {
1730 defer un(trace(p, "GenDecl("+keyword.String()+")"))
1733 doc := p.leadComment
1734 pos := p.expect(keyword)
1735 var lparen, rparen token.Pos
1737 if p.tok == token.LPAREN {
1740 for p.tok != token.RPAREN && p.tok != token.EOF {
1741 list = append(list, f(p, p.leadComment))
1743 rparen = p.expect(token.RPAREN)
1746 list = append(list, f(p, nil))
1749 return &ast.GenDecl{doc, pos, keyword, lparen, list, rparen}
1753 func (p *parser) parseReceiver() *ast.FieldList {
1755 defer un(trace(p, "Receiver"))
1759 par := p.parseParameters(false)
1761 // must have exactly one receiver
1762 if par.NumFields() != 1 {
1763 p.errorExpected(pos, "exactly one receiver")
1764 // TODO determine a better range for BadExpr below
1765 par.List = []*ast.Field{&ast.Field{Type: &ast.BadExpr{pos, pos}}}
1769 // recv type must be of the form ["*"] identifier
1771 base := deref(recv.Type)
1772 if _, isIdent := base.(*ast.Ident); !isIdent {
1773 p.errorExpected(base.Pos(), "(unqualified) identifier")
1774 par.List = []*ast.Field{&ast.Field{Type: &ast.BadExpr{recv.Pos(), recv.End()}}}
1781 func (p *parser) parseFuncDecl() *ast.FuncDecl {
1783 defer un(trace(p, "FunctionDecl"))
1786 doc := p.leadComment
1787 pos := p.expect(token.FUNC)
1789 var recv *ast.FieldList
1790 if p.tok == token.LPAREN {
1791 recv = p.parseReceiver()
1794 ident := p.parseIdent()
1795 params, results := p.parseSignature()
1797 var body *ast.BlockStmt
1798 if p.tok == token.LBRACE {
1799 body = p.parseBody()
1803 return &ast.FuncDecl{doc, recv, ident, &ast.FuncType{pos, params, results}, body}
1807 func (p *parser) parseDecl() ast.Decl {
1809 defer un(trace(p, "Declaration"))
1812 var f parseSpecFunction
1824 return p.parseFuncDecl()
1828 p.errorExpected(pos, "declaration")
1829 p.next() // make progress
1830 decl := &ast.BadDecl{pos, p.pos}
1834 return p.parseGenDecl(p.tok, f)
1838 func (p *parser) parseDeclList() (list []ast.Decl) {
1840 defer un(trace(p, "DeclList"))
1843 for p.tok != token.EOF {
1844 list = append(list, p.parseDecl())
1851 // ----------------------------------------------------------------------------
1854 func (p *parser) parseFile() *ast.File {
1856 defer un(trace(p, "File"))
1860 doc := p.leadComment
1861 pos := p.expect(token.PACKAGE)
1862 ident := p.parseIdent()
1865 var decls []ast.Decl
1867 // Don't bother parsing the rest if we had errors already.
1868 // Likely not a Go source file at all.
1870 if p.ErrorCount() == 0 && p.mode&PackageClauseOnly == 0 {
1872 for p.tok == token.IMPORT {
1873 decls = append(decls, p.parseGenDecl(token.IMPORT, parseImportSpec))
1876 if p.mode&ImportsOnly == 0 {
1877 // rest of package body
1878 for p.tok != token.EOF {
1879 decls = append(decls, p.parseDecl())
1884 return &ast.File{doc, pos, ident, decls, p.comments}