Run Format

Source file src/pkg/go/parser/parser.go

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

View as plain text