github.com/varialus/godfly@v0.0.0-20130904042352-1934f9f095ab/src/pkg/go/parser/parser.go (about)

     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, -1, 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  	lparen := 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  	rparen := p.expect(token.RPAREN)
  1162  
  1163  	return &ast.TypeAssertExpr{X: x, Type: typ, Lparen: lparen, Rparen: rparen}
  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 index [3]ast.Expr // change the 3 to 2 to disable slice expressions w/ cap
  1174  	if p.tok != token.COLON {
  1175  		index[0] = p.parseRhs()
  1176  	}
  1177  	ncolons := 0
  1178  	for p.tok == token.COLON && ncolons < len(index)-1 {
  1179  		p.next()
  1180  		ncolons++
  1181  		if p.tok != token.COLON && p.tok != token.RBRACK && p.tok != token.EOF {
  1182  			index[ncolons] = p.parseRhs()
  1183  		}
  1184  	}
  1185  	p.exprLev--
  1186  	rbrack := p.expect(token.RBRACK)
  1187  
  1188  	if ncolons > 0 {
  1189  		// slice expression
  1190  		return &ast.SliceExpr{X: x, Lbrack: lbrack, Low: index[0], High: index[1], Max: index[2], Rbrack: rbrack}
  1191  	}
  1192  
  1193  	return &ast.IndexExpr{X: x, Lbrack: lbrack, Index: index[0], Rbrack: rbrack}
  1194  }
  1195  
  1196  func (p *parser) parseCallOrConversion(fun ast.Expr) *ast.CallExpr {
  1197  	if p.trace {
  1198  		defer un(trace(p, "CallOrConversion"))
  1199  	}
  1200  
  1201  	lparen := p.expect(token.LPAREN)
  1202  	p.exprLev++
  1203  	var list []ast.Expr
  1204  	var ellipsis token.Pos
  1205  	for p.tok != token.RPAREN && p.tok != token.EOF && !ellipsis.IsValid() {
  1206  		list = append(list, p.parseRhsOrType()) // builtins may expect a type: make(some type, ...)
  1207  		if p.tok == token.ELLIPSIS {
  1208  			ellipsis = p.pos
  1209  			p.next()
  1210  		}
  1211  		if !p.atComma("argument list") {
  1212  			break
  1213  		}
  1214  		p.next()
  1215  	}
  1216  	p.exprLev--
  1217  	rparen := p.expectClosing(token.RPAREN, "argument list")
  1218  
  1219  	return &ast.CallExpr{Fun: fun, Lparen: lparen, Args: list, Ellipsis: ellipsis, Rparen: rparen}
  1220  }
  1221  
  1222  func (p *parser) parseElement(keyOk bool) ast.Expr {
  1223  	if p.trace {
  1224  		defer un(trace(p, "Element"))
  1225  	}
  1226  
  1227  	if p.tok == token.LBRACE {
  1228  		return p.parseLiteralValue(nil)
  1229  	}
  1230  
  1231  	// Because the parser doesn't know the composite literal type, it cannot
  1232  	// know if a key that's an identifier is a struct field name or a name
  1233  	// denoting a value. The former is not resolved by the parser or the
  1234  	// resolver.
  1235  	//
  1236  	// Instead, _try_ to resolve such a key if possible. If it resolves,
  1237  	// it a) has correctly resolved, or b) incorrectly resolved because
  1238  	// the key is a struct field with a name matching another identifier.
  1239  	// In the former case we are done, and in the latter case we don't
  1240  	// care because the type checker will do a separate field lookup.
  1241  	//
  1242  	// If the key does not resolve, it a) must be defined at the top
  1243  	// level in another file of the same package, the universe scope, or be
  1244  	// undeclared; or b) it is a struct field. In the former case, the type
  1245  	// checker can do a top-level lookup, and in the latter case it will do
  1246  	// a separate field lookup.
  1247  	x := p.checkExpr(p.parseExpr(keyOk))
  1248  	if keyOk {
  1249  		if p.tok == token.COLON {
  1250  			colon := p.pos
  1251  			p.next()
  1252  			// Try to resolve the key but don't collect it
  1253  			// as unresolved identifier if it fails so that
  1254  			// we don't get (possibly false) errors about
  1255  			// undeclared names.
  1256  			p.tryResolve(x, false)
  1257  			return &ast.KeyValueExpr{Key: x, Colon: colon, Value: p.parseElement(false)}
  1258  		}
  1259  		p.resolve(x) // not a key
  1260  	}
  1261  
  1262  	return x
  1263  }
  1264  
  1265  func (p *parser) parseElementList() (list []ast.Expr) {
  1266  	if p.trace {
  1267  		defer un(trace(p, "ElementList"))
  1268  	}
  1269  
  1270  	for p.tok != token.RBRACE && p.tok != token.EOF {
  1271  		list = append(list, p.parseElement(true))
  1272  		if !p.atComma("composite literal") {
  1273  			break
  1274  		}
  1275  		p.next()
  1276  	}
  1277  
  1278  	return
  1279  }
  1280  
  1281  func (p *parser) parseLiteralValue(typ ast.Expr) ast.Expr {
  1282  	if p.trace {
  1283  		defer un(trace(p, "LiteralValue"))
  1284  	}
  1285  
  1286  	lbrace := p.expect(token.LBRACE)
  1287  	var elts []ast.Expr
  1288  	p.exprLev++
  1289  	if p.tok != token.RBRACE {
  1290  		elts = p.parseElementList()
  1291  	}
  1292  	p.exprLev--
  1293  	rbrace := p.expectClosing(token.RBRACE, "composite literal")
  1294  	return &ast.CompositeLit{Type: typ, Lbrace: lbrace, Elts: elts, Rbrace: rbrace}
  1295  }
  1296  
  1297  // checkExpr checks that x is an expression (and not a type).
  1298  func (p *parser) checkExpr(x ast.Expr) ast.Expr {
  1299  	switch unparen(x).(type) {
  1300  	case *ast.BadExpr:
  1301  	case *ast.Ident:
  1302  	case *ast.BasicLit:
  1303  	case *ast.FuncLit:
  1304  	case *ast.CompositeLit:
  1305  	case *ast.ParenExpr:
  1306  		panic("unreachable")
  1307  	case *ast.SelectorExpr:
  1308  	case *ast.IndexExpr:
  1309  	case *ast.SliceExpr:
  1310  	case *ast.TypeAssertExpr:
  1311  		// If t.Type == nil we have a type assertion of the form
  1312  		// y.(type), which is only allowed in type switch expressions.
  1313  		// It's hard to exclude those but for the case where we are in
  1314  		// a type switch. Instead be lenient and test this in the type
  1315  		// checker.
  1316  	case *ast.CallExpr:
  1317  	case *ast.StarExpr:
  1318  	case *ast.UnaryExpr:
  1319  	case *ast.BinaryExpr:
  1320  	default:
  1321  		// all other nodes are not proper expressions
  1322  		p.errorExpected(x.Pos(), "expression")
  1323  		x = &ast.BadExpr{From: x.Pos(), To: x.End()}
  1324  	}
  1325  	return x
  1326  }
  1327  
  1328  // isTypeName returns true iff x is a (qualified) TypeName.
  1329  func isTypeName(x ast.Expr) bool {
  1330  	switch t := x.(type) {
  1331  	case *ast.BadExpr:
  1332  	case *ast.Ident:
  1333  	case *ast.SelectorExpr:
  1334  		_, isIdent := t.X.(*ast.Ident)
  1335  		return isIdent
  1336  	default:
  1337  		return false // all other nodes are not type names
  1338  	}
  1339  	return true
  1340  }
  1341  
  1342  // isLiteralType returns true iff x is a legal composite literal type.
  1343  func isLiteralType(x ast.Expr) bool {
  1344  	switch t := x.(type) {
  1345  	case *ast.BadExpr:
  1346  	case *ast.Ident:
  1347  	case *ast.SelectorExpr:
  1348  		_, isIdent := t.X.(*ast.Ident)
  1349  		return isIdent
  1350  	case *ast.ArrayType:
  1351  	case *ast.StructType:
  1352  	case *ast.MapType:
  1353  	default:
  1354  		return false // all other nodes are not legal composite literal types
  1355  	}
  1356  	return true
  1357  }
  1358  
  1359  // If x is of the form *T, deref returns T, otherwise it returns x.
  1360  func deref(x ast.Expr) ast.Expr {
  1361  	if p, isPtr := x.(*ast.StarExpr); isPtr {
  1362  		x = p.X
  1363  	}
  1364  	return x
  1365  }
  1366  
  1367  // If x is of the form (T), unparen returns unparen(T), otherwise it returns x.
  1368  func unparen(x ast.Expr) ast.Expr {
  1369  	if p, isParen := x.(*ast.ParenExpr); isParen {
  1370  		x = unparen(p.X)
  1371  	}
  1372  	return x
  1373  }
  1374  
  1375  // checkExprOrType checks that x is an expression or a type
  1376  // (and not a raw type such as [...]T).
  1377  //
  1378  func (p *parser) checkExprOrType(x ast.Expr) ast.Expr {
  1379  	switch t := unparen(x).(type) {
  1380  	case *ast.ParenExpr:
  1381  		panic("unreachable")
  1382  	case *ast.UnaryExpr:
  1383  	case *ast.ArrayType:
  1384  		if len, isEllipsis := t.Len.(*ast.Ellipsis); isEllipsis {
  1385  			p.error(len.Pos(), "expected array length, found '...'")
  1386  			x = &ast.BadExpr{From: x.Pos(), To: x.End()}
  1387  		}
  1388  	}
  1389  
  1390  	// all other nodes are expressions or types
  1391  	return x
  1392  }
  1393  
  1394  // If lhs is set and the result is an identifier, it is not resolved.
  1395  func (p *parser) parsePrimaryExpr(lhs bool) ast.Expr {
  1396  	if p.trace {
  1397  		defer un(trace(p, "PrimaryExpr"))
  1398  	}
  1399  
  1400  	x := p.parseOperand(lhs)
  1401  L:
  1402  	for {
  1403  		switch p.tok {
  1404  		case token.PERIOD:
  1405  			p.next()
  1406  			if lhs {
  1407  				p.resolve(x)
  1408  			}
  1409  			switch p.tok {
  1410  			case token.IDENT:
  1411  				x = p.parseSelector(p.checkExprOrType(x))
  1412  			case token.LPAREN:
  1413  				x = p.parseTypeAssertion(p.checkExpr(x))
  1414  			default:
  1415  				pos := p.pos
  1416  				p.errorExpected(pos, "selector or type assertion")
  1417  				p.next() // make progress
  1418  				x = &ast.BadExpr{From: pos, To: p.pos}
  1419  			}
  1420  		case token.LBRACK:
  1421  			if lhs {
  1422  				p.resolve(x)
  1423  			}
  1424  			x = p.parseIndexOrSlice(p.checkExpr(x))
  1425  		case token.LPAREN:
  1426  			if lhs {
  1427  				p.resolve(x)
  1428  			}
  1429  			x = p.parseCallOrConversion(p.checkExprOrType(x))
  1430  		case token.LBRACE:
  1431  			if isLiteralType(x) && (p.exprLev >= 0 || !isTypeName(x)) {
  1432  				if lhs {
  1433  					p.resolve(x)
  1434  				}
  1435  				x = p.parseLiteralValue(x)
  1436  			} else {
  1437  				break L
  1438  			}
  1439  		default:
  1440  			break L
  1441  		}
  1442  		lhs = false // no need to try to resolve again
  1443  	}
  1444  
  1445  	return x
  1446  }
  1447  
  1448  // If lhs is set and the result is an identifier, it is not resolved.
  1449  func (p *parser) parseUnaryExpr(lhs bool) ast.Expr {
  1450  	if p.trace {
  1451  		defer un(trace(p, "UnaryExpr"))
  1452  	}
  1453  
  1454  	switch p.tok {
  1455  	case token.ADD, token.SUB, token.NOT, token.XOR, token.AND:
  1456  		pos, op := p.pos, p.tok
  1457  		p.next()
  1458  		x := p.parseUnaryExpr(false)
  1459  		return &ast.UnaryExpr{OpPos: pos, Op: op, X: p.checkExpr(x)}
  1460  
  1461  	case token.ARROW:
  1462  		// channel type or receive expression
  1463  		arrow := p.pos
  1464  		p.next()
  1465  
  1466  		// If the next token is token.CHAN we still don't know if it
  1467  		// is a channel type or a receive operation - we only know
  1468  		// once we have found the end of the unary expression. There
  1469  		// are two cases:
  1470  		//
  1471  		//   <- type  => (<-type) must be channel type
  1472  		//   <- expr  => <-(expr) is a receive from an expression
  1473  		//
  1474  		// In the first case, the arrow must be re-associated with
  1475  		// the channel type parsed already:
  1476  		//
  1477  		//   <- (chan type)    =>  (<-chan type)
  1478  		//   <- (chan<- type)  =>  (<-chan (<-type))
  1479  
  1480  		x := p.parseUnaryExpr(false)
  1481  
  1482  		// determine which case we have
  1483  		if typ, ok := x.(*ast.ChanType); ok {
  1484  			// (<-type)
  1485  
  1486  			// re-associate position info and <-
  1487  			dir := ast.SEND
  1488  			for ok && dir == ast.SEND {
  1489  				if typ.Dir == ast.RECV {
  1490  					// error: (<-type) is (<-(<-chan T))
  1491  					p.errorExpected(typ.Arrow, "'chan'")
  1492  				}
  1493  				arrow, typ.Begin, typ.Arrow = typ.Arrow, arrow, arrow
  1494  				dir, typ.Dir = typ.Dir, ast.RECV
  1495  				typ, ok = typ.Value.(*ast.ChanType)
  1496  			}
  1497  			if dir == ast.SEND {
  1498  				p.errorExpected(arrow, "channel type")
  1499  			}
  1500  
  1501  			return x
  1502  		}
  1503  
  1504  		// <-(expr)
  1505  		return &ast.UnaryExpr{OpPos: arrow, Op: token.ARROW, X: p.checkExpr(x)}
  1506  
  1507  	case token.MUL:
  1508  		// pointer type or unary "*" expression
  1509  		pos := p.pos
  1510  		p.next()
  1511  		x := p.parseUnaryExpr(false)
  1512  		return &ast.StarExpr{Star: pos, X: p.checkExprOrType(x)}
  1513  	}
  1514  
  1515  	return p.parsePrimaryExpr(lhs)
  1516  }
  1517  
  1518  func (p *parser) tokPrec() (token.Token, int) {
  1519  	tok := p.tok
  1520  	if p.inRhs && tok == token.ASSIGN {
  1521  		tok = token.EQL
  1522  	}
  1523  	return tok, tok.Precedence()
  1524  }
  1525  
  1526  // If lhs is set and the result is an identifier, it is not resolved.
  1527  func (p *parser) parseBinaryExpr(lhs bool, prec1 int) ast.Expr {
  1528  	if p.trace {
  1529  		defer un(trace(p, "BinaryExpr"))
  1530  	}
  1531  
  1532  	x := p.parseUnaryExpr(lhs)
  1533  	for _, prec := p.tokPrec(); prec >= prec1; prec-- {
  1534  		for {
  1535  			op, oprec := p.tokPrec()
  1536  			if oprec != prec {
  1537  				break
  1538  			}
  1539  			pos := p.expect(op)
  1540  			if lhs {
  1541  				p.resolve(x)
  1542  				lhs = false
  1543  			}
  1544  			y := p.parseBinaryExpr(false, prec+1)
  1545  			x = &ast.BinaryExpr{X: p.checkExpr(x), OpPos: pos, Op: op, Y: p.checkExpr(y)}
  1546  		}
  1547  	}
  1548  
  1549  	return x
  1550  }
  1551  
  1552  // If lhs is set and the result is an identifier, it is not resolved.
  1553  // The result may be a type or even a raw type ([...]int). Callers must
  1554  // check the result (using checkExpr or checkExprOrType), depending on
  1555  // context.
  1556  func (p *parser) parseExpr(lhs bool) ast.Expr {
  1557  	if p.trace {
  1558  		defer un(trace(p, "Expression"))
  1559  	}
  1560  
  1561  	return p.parseBinaryExpr(lhs, token.LowestPrec+1)
  1562  }
  1563  
  1564  func (p *parser) parseRhs() ast.Expr {
  1565  	old := p.inRhs
  1566  	p.inRhs = true
  1567  	x := p.checkExpr(p.parseExpr(false))
  1568  	p.inRhs = old
  1569  	return x
  1570  }
  1571  
  1572  func (p *parser) parseRhsOrType() ast.Expr {
  1573  	old := p.inRhs
  1574  	p.inRhs = true
  1575  	x := p.checkExprOrType(p.parseExpr(false))
  1576  	p.inRhs = old
  1577  	return x
  1578  }
  1579  
  1580  // ----------------------------------------------------------------------------
  1581  // Statements
  1582  
  1583  // Parsing modes for parseSimpleStmt.
  1584  const (
  1585  	basic = iota
  1586  	labelOk
  1587  	rangeOk
  1588  )
  1589  
  1590  // parseSimpleStmt returns true as 2nd result if it parsed the assignment
  1591  // of a range clause (with mode == rangeOk). The returned statement is an
  1592  // assignment with a right-hand side that is a single unary expression of
  1593  // the form "range x". No guarantees are given for the left-hand side.
  1594  func (p *parser) parseSimpleStmt(mode int) (ast.Stmt, bool) {
  1595  	if p.trace {
  1596  		defer un(trace(p, "SimpleStmt"))
  1597  	}
  1598  
  1599  	x := p.parseLhsList()
  1600  
  1601  	switch p.tok {
  1602  	case
  1603  		token.DEFINE, token.ASSIGN, token.ADD_ASSIGN,
  1604  		token.SUB_ASSIGN, token.MUL_ASSIGN, token.QUO_ASSIGN,
  1605  		token.REM_ASSIGN, token.AND_ASSIGN, token.OR_ASSIGN,
  1606  		token.XOR_ASSIGN, token.SHL_ASSIGN, token.SHR_ASSIGN, token.AND_NOT_ASSIGN:
  1607  		// assignment statement, possibly part of a range clause
  1608  		pos, tok := p.pos, p.tok
  1609  		p.next()
  1610  		var y []ast.Expr
  1611  		isRange := false
  1612  		if mode == rangeOk && p.tok == token.RANGE && (tok == token.DEFINE || tok == token.ASSIGN) {
  1613  			pos := p.pos
  1614  			p.next()
  1615  			y = []ast.Expr{&ast.UnaryExpr{OpPos: pos, Op: token.RANGE, X: p.parseRhs()}}
  1616  			isRange = true
  1617  		} else {
  1618  			y = p.parseRhsList()
  1619  		}
  1620  		as := &ast.AssignStmt{Lhs: x, TokPos: pos, Tok: tok, Rhs: y}
  1621  		if tok == token.DEFINE {
  1622  			p.shortVarDecl(as, x)
  1623  		}
  1624  		return as, isRange
  1625  	}
  1626  
  1627  	if len(x) > 1 {
  1628  		p.errorExpected(x[0].Pos(), "1 expression")
  1629  		// continue with first expression
  1630  	}
  1631  
  1632  	switch p.tok {
  1633  	case token.COLON:
  1634  		// labeled statement
  1635  		colon := p.pos
  1636  		p.next()
  1637  		if label, isIdent := x[0].(*ast.Ident); mode == labelOk && isIdent {
  1638  			// Go spec: The scope of a label is the body of the function
  1639  			// in which it is declared and excludes the body of any nested
  1640  			// function.
  1641  			stmt := &ast.LabeledStmt{Label: label, Colon: colon, Stmt: p.parseStmt()}
  1642  			p.declare(stmt, nil, p.labelScope, ast.Lbl, label)
  1643  			return stmt, false
  1644  		}
  1645  		// The label declaration typically starts at x[0].Pos(), but the label
  1646  		// declaration may be erroneous due to a token after that position (and
  1647  		// before the ':'). If SpuriousErrors is not set, the (only) error re-
  1648  		// ported for the line is the illegal label error instead of the token
  1649  		// before the ':' that caused the problem. Thus, use the (latest) colon
  1650  		// position for error reporting.
  1651  		p.error(colon, "illegal label declaration")
  1652  		return &ast.BadStmt{From: x[0].Pos(), To: colon + 1}, false
  1653  
  1654  	case token.ARROW:
  1655  		// send statement
  1656  		arrow := p.pos
  1657  		p.next()
  1658  		y := p.parseRhs()
  1659  		return &ast.SendStmt{Chan: x[0], Arrow: arrow, Value: y}, false
  1660  
  1661  	case token.INC, token.DEC:
  1662  		// increment or decrement
  1663  		s := &ast.IncDecStmt{X: x[0], TokPos: p.pos, Tok: p.tok}
  1664  		p.next()
  1665  		return s, false
  1666  	}
  1667  
  1668  	// expression
  1669  	return &ast.ExprStmt{X: x[0]}, false
  1670  }
  1671  
  1672  func (p *parser) parseCallExpr() *ast.CallExpr {
  1673  	x := p.parseRhsOrType() // could be a conversion: (some type)(x)
  1674  	if call, isCall := x.(*ast.CallExpr); isCall {
  1675  		return call
  1676  	}
  1677  	if _, isBad := x.(*ast.BadExpr); !isBad {
  1678  		// only report error if it's a new one
  1679  		p.errorExpected(x.Pos(), "function/method call")
  1680  	}
  1681  	return nil
  1682  }
  1683  
  1684  func (p *parser) parseGoStmt() ast.Stmt {
  1685  	if p.trace {
  1686  		defer un(trace(p, "GoStmt"))
  1687  	}
  1688  
  1689  	pos := p.expect(token.GO)
  1690  	call := p.parseCallExpr()
  1691  	p.expectSemi()
  1692  	if call == nil {
  1693  		return &ast.BadStmt{From: pos, To: pos + 2} // len("go")
  1694  	}
  1695  
  1696  	return &ast.GoStmt{Go: pos, Call: call}
  1697  }
  1698  
  1699  func (p *parser) parseDeferStmt() ast.Stmt {
  1700  	if p.trace {
  1701  		defer un(trace(p, "DeferStmt"))
  1702  	}
  1703  
  1704  	pos := p.expect(token.DEFER)
  1705  	call := p.parseCallExpr()
  1706  	p.expectSemi()
  1707  	if call == nil {
  1708  		return &ast.BadStmt{From: pos, To: pos + 5} // len("defer")
  1709  	}
  1710  
  1711  	return &ast.DeferStmt{Defer: pos, Call: call}
  1712  }
  1713  
  1714  func (p *parser) parseReturnStmt() *ast.ReturnStmt {
  1715  	if p.trace {
  1716  		defer un(trace(p, "ReturnStmt"))
  1717  	}
  1718  
  1719  	pos := p.pos
  1720  	p.expect(token.RETURN)
  1721  	var x []ast.Expr
  1722  	if p.tok != token.SEMICOLON && p.tok != token.RBRACE {
  1723  		x = p.parseRhsList()
  1724  	}
  1725  	p.expectSemi()
  1726  
  1727  	return &ast.ReturnStmt{Return: pos, Results: x}
  1728  }
  1729  
  1730  func (p *parser) parseBranchStmt(tok token.Token) *ast.BranchStmt {
  1731  	if p.trace {
  1732  		defer un(trace(p, "BranchStmt"))
  1733  	}
  1734  
  1735  	pos := p.expect(tok)
  1736  	var label *ast.Ident
  1737  	if tok != token.FALLTHROUGH && p.tok == token.IDENT {
  1738  		label = p.parseIdent()
  1739  		// add to list of unresolved targets
  1740  		n := len(p.targetStack) - 1
  1741  		p.targetStack[n] = append(p.targetStack[n], label)
  1742  	}
  1743  	p.expectSemi()
  1744  
  1745  	return &ast.BranchStmt{TokPos: pos, Tok: tok, Label: label}
  1746  }
  1747  
  1748  func (p *parser) makeExpr(s ast.Stmt) ast.Expr {
  1749  	if s == nil {
  1750  		return nil
  1751  	}
  1752  	if es, isExpr := s.(*ast.ExprStmt); isExpr {
  1753  		return p.checkExpr(es.X)
  1754  	}
  1755  	p.error(s.Pos(), "expected condition, found simple statement")
  1756  	return &ast.BadExpr{From: s.Pos(), To: s.End()}
  1757  }
  1758  
  1759  func (p *parser) parseIfStmt() *ast.IfStmt {
  1760  	if p.trace {
  1761  		defer un(trace(p, "IfStmt"))
  1762  	}
  1763  
  1764  	pos := p.expect(token.IF)
  1765  	p.openScope()
  1766  	defer p.closeScope()
  1767  
  1768  	var s ast.Stmt
  1769  	var x ast.Expr
  1770  	{
  1771  		prevLev := p.exprLev
  1772  		p.exprLev = -1
  1773  		if p.tok == token.SEMICOLON {
  1774  			p.next()
  1775  			x = p.parseRhs()
  1776  		} else {
  1777  			s, _ = p.parseSimpleStmt(basic)
  1778  			if p.tok == token.SEMICOLON {
  1779  				p.next()
  1780  				x = p.parseRhs()
  1781  			} else {
  1782  				x = p.makeExpr(s)
  1783  				s = nil
  1784  			}
  1785  		}
  1786  		p.exprLev = prevLev
  1787  	}
  1788  
  1789  	body := p.parseBlockStmt()
  1790  	var else_ ast.Stmt
  1791  	if p.tok == token.ELSE {
  1792  		p.next()
  1793  		else_ = p.parseStmt()
  1794  	} else {
  1795  		p.expectSemi()
  1796  	}
  1797  
  1798  	return &ast.IfStmt{If: pos, Init: s, Cond: x, Body: body, Else: else_}
  1799  }
  1800  
  1801  func (p *parser) parseTypeList() (list []ast.Expr) {
  1802  	if p.trace {
  1803  		defer un(trace(p, "TypeList"))
  1804  	}
  1805  
  1806  	list = append(list, p.parseType())
  1807  	for p.tok == token.COMMA {
  1808  		p.next()
  1809  		list = append(list, p.parseType())
  1810  	}
  1811  
  1812  	return
  1813  }
  1814  
  1815  func (p *parser) parseCaseClause(typeSwitch bool) *ast.CaseClause {
  1816  	if p.trace {
  1817  		defer un(trace(p, "CaseClause"))
  1818  	}
  1819  
  1820  	pos := p.pos
  1821  	var list []ast.Expr
  1822  	if p.tok == token.CASE {
  1823  		p.next()
  1824  		if typeSwitch {
  1825  			list = p.parseTypeList()
  1826  		} else {
  1827  			list = p.parseRhsList()
  1828  		}
  1829  	} else {
  1830  		p.expect(token.DEFAULT)
  1831  	}
  1832  
  1833  	colon := p.expect(token.COLON)
  1834  	p.openScope()
  1835  	body := p.parseStmtList()
  1836  	p.closeScope()
  1837  
  1838  	return &ast.CaseClause{Case: pos, List: list, Colon: colon, Body: body}
  1839  }
  1840  
  1841  func isTypeSwitchAssert(x ast.Expr) bool {
  1842  	a, ok := x.(*ast.TypeAssertExpr)
  1843  	return ok && a.Type == nil
  1844  }
  1845  
  1846  func isTypeSwitchGuard(s ast.Stmt) bool {
  1847  	switch t := s.(type) {
  1848  	case *ast.ExprStmt:
  1849  		// x.(nil)
  1850  		return isTypeSwitchAssert(t.X)
  1851  	case *ast.AssignStmt:
  1852  		// v := x.(nil)
  1853  		return len(t.Lhs) == 1 && t.Tok == token.DEFINE && len(t.Rhs) == 1 && isTypeSwitchAssert(t.Rhs[0])
  1854  	}
  1855  	return false
  1856  }
  1857  
  1858  func (p *parser) parseSwitchStmt() ast.Stmt {
  1859  	if p.trace {
  1860  		defer un(trace(p, "SwitchStmt"))
  1861  	}
  1862  
  1863  	pos := p.expect(token.SWITCH)
  1864  	p.openScope()
  1865  	defer p.closeScope()
  1866  
  1867  	var s1, s2 ast.Stmt
  1868  	if p.tok != token.LBRACE {
  1869  		prevLev := p.exprLev
  1870  		p.exprLev = -1
  1871  		if p.tok != token.SEMICOLON {
  1872  			s2, _ = p.parseSimpleStmt(basic)
  1873  		}
  1874  		if p.tok == token.SEMICOLON {
  1875  			p.next()
  1876  			s1 = s2
  1877  			s2 = nil
  1878  			if p.tok != token.LBRACE {
  1879  				// A TypeSwitchGuard may declare a variable in addition
  1880  				// to the variable declared in the initial SimpleStmt.
  1881  				// Introduce extra scope to avoid redeclaration errors:
  1882  				//
  1883  				//	switch t := 0; t := x.(T) { ... }
  1884  				//
  1885  				// (this code is not valid Go because the first t
  1886  				// cannot be accessed and thus is never used, the extra
  1887  				// scope is needed for the correct error message).
  1888  				//
  1889  				// If we don't have a type switch, s2 must be an expression.
  1890  				// Having the extra nested but empty scope won't affect it.
  1891  				p.openScope()
  1892  				defer p.closeScope()
  1893  				s2, _ = p.parseSimpleStmt(basic)
  1894  			}
  1895  		}
  1896  		p.exprLev = prevLev
  1897  	}
  1898  
  1899  	typeSwitch := isTypeSwitchGuard(s2)
  1900  	lbrace := p.expect(token.LBRACE)
  1901  	var list []ast.Stmt
  1902  	for p.tok == token.CASE || p.tok == token.DEFAULT {
  1903  		list = append(list, p.parseCaseClause(typeSwitch))
  1904  	}
  1905  	rbrace := p.expect(token.RBRACE)
  1906  	p.expectSemi()
  1907  	body := &ast.BlockStmt{Lbrace: lbrace, List: list, Rbrace: rbrace}
  1908  
  1909  	if typeSwitch {
  1910  		return &ast.TypeSwitchStmt{Switch: pos, Init: s1, Assign: s2, Body: body}
  1911  	}
  1912  
  1913  	return &ast.SwitchStmt{Switch: pos, Init: s1, Tag: p.makeExpr(s2), Body: body}
  1914  }
  1915  
  1916  func (p *parser) parseCommClause() *ast.CommClause {
  1917  	if p.trace {
  1918  		defer un(trace(p, "CommClause"))
  1919  	}
  1920  
  1921  	p.openScope()
  1922  	pos := p.pos
  1923  	var comm ast.Stmt
  1924  	if p.tok == token.CASE {
  1925  		p.next()
  1926  		lhs := p.parseLhsList()
  1927  		if p.tok == token.ARROW {
  1928  			// SendStmt
  1929  			if len(lhs) > 1 {
  1930  				p.errorExpected(lhs[0].Pos(), "1 expression")
  1931  				// continue with first expression
  1932  			}
  1933  			arrow := p.pos
  1934  			p.next()
  1935  			rhs := p.parseRhs()
  1936  			comm = &ast.SendStmt{Chan: lhs[0], Arrow: arrow, Value: rhs}
  1937  		} else {
  1938  			// RecvStmt
  1939  			if tok := p.tok; tok == token.ASSIGN || tok == token.DEFINE {
  1940  				// RecvStmt with assignment
  1941  				if len(lhs) > 2 {
  1942  					p.errorExpected(lhs[0].Pos(), "1 or 2 expressions")
  1943  					// continue with first two expressions
  1944  					lhs = lhs[0:2]
  1945  				}
  1946  				pos := p.pos
  1947  				p.next()
  1948  				rhs := p.parseRhs()
  1949  				as := &ast.AssignStmt{Lhs: lhs, TokPos: pos, Tok: tok, Rhs: []ast.Expr{rhs}}
  1950  				if tok == token.DEFINE {
  1951  					p.shortVarDecl(as, lhs)
  1952  				}
  1953  				comm = as
  1954  			} else {
  1955  				// lhs must be single receive operation
  1956  				if len(lhs) > 1 {
  1957  					p.errorExpected(lhs[0].Pos(), "1 expression")
  1958  					// continue with first expression
  1959  				}
  1960  				comm = &ast.ExprStmt{X: lhs[0]}
  1961  			}
  1962  		}
  1963  	} else {
  1964  		p.expect(token.DEFAULT)
  1965  	}
  1966  
  1967  	colon := p.expect(token.COLON)
  1968  	body := p.parseStmtList()
  1969  	p.closeScope()
  1970  
  1971  	return &ast.CommClause{Case: pos, Comm: comm, Colon: colon, Body: body}
  1972  }
  1973  
  1974  func (p *parser) parseSelectStmt() *ast.SelectStmt {
  1975  	if p.trace {
  1976  		defer un(trace(p, "SelectStmt"))
  1977  	}
  1978  
  1979  	pos := p.expect(token.SELECT)
  1980  	lbrace := p.expect(token.LBRACE)
  1981  	var list []ast.Stmt
  1982  	for p.tok == token.CASE || p.tok == token.DEFAULT {
  1983  		list = append(list, p.parseCommClause())
  1984  	}
  1985  	rbrace := p.expect(token.RBRACE)
  1986  	p.expectSemi()
  1987  	body := &ast.BlockStmt{Lbrace: lbrace, List: list, Rbrace: rbrace}
  1988  
  1989  	return &ast.SelectStmt{Select: pos, Body: body}
  1990  }
  1991  
  1992  func (p *parser) parseForStmt() ast.Stmt {
  1993  	if p.trace {
  1994  		defer un(trace(p, "ForStmt"))
  1995  	}
  1996  
  1997  	pos := p.expect(token.FOR)
  1998  	p.openScope()
  1999  	defer p.closeScope()
  2000  
  2001  	var s1, s2, s3 ast.Stmt
  2002  	var isRange bool
  2003  	if p.tok != token.LBRACE {
  2004  		prevLev := p.exprLev
  2005  		p.exprLev = -1
  2006  		if p.tok != token.SEMICOLON {
  2007  			s2, isRange = p.parseSimpleStmt(rangeOk)
  2008  		}
  2009  		if !isRange && p.tok == token.SEMICOLON {
  2010  			p.next()
  2011  			s1 = s2
  2012  			s2 = nil
  2013  			if p.tok != token.SEMICOLON {
  2014  				s2, _ = p.parseSimpleStmt(basic)
  2015  			}
  2016  			p.expectSemi()
  2017  			if p.tok != token.LBRACE {
  2018  				s3, _ = p.parseSimpleStmt(basic)
  2019  			}
  2020  		}
  2021  		p.exprLev = prevLev
  2022  	}
  2023  
  2024  	body := p.parseBlockStmt()
  2025  	p.expectSemi()
  2026  
  2027  	if isRange {
  2028  		as := s2.(*ast.AssignStmt)
  2029  		// check lhs
  2030  		var key, value ast.Expr
  2031  		switch len(as.Lhs) {
  2032  		case 2:
  2033  			key, value = as.Lhs[0], as.Lhs[1]
  2034  		case 1:
  2035  			key = as.Lhs[0]
  2036  		default:
  2037  			p.errorExpected(as.Lhs[0].Pos(), "1 or 2 expressions")
  2038  			return &ast.BadStmt{From: pos, To: body.End()}
  2039  		}
  2040  		// parseSimpleStmt returned a right-hand side that
  2041  		// is a single unary expression of the form "range x"
  2042  		x := as.Rhs[0].(*ast.UnaryExpr).X
  2043  		return &ast.RangeStmt{
  2044  			For:    pos,
  2045  			Key:    key,
  2046  			Value:  value,
  2047  			TokPos: as.TokPos,
  2048  			Tok:    as.Tok,
  2049  			X:      x,
  2050  			Body:   body,
  2051  		}
  2052  	}
  2053  
  2054  	// regular for statement
  2055  	return &ast.ForStmt{
  2056  		For:  pos,
  2057  		Init: s1,
  2058  		Cond: p.makeExpr(s2),
  2059  		Post: s3,
  2060  		Body: body,
  2061  	}
  2062  }
  2063  
  2064  func (p *parser) parseStmt() (s ast.Stmt) {
  2065  	if p.trace {
  2066  		defer un(trace(p, "Statement"))
  2067  	}
  2068  
  2069  	switch p.tok {
  2070  	case token.CONST, token.TYPE, token.VAR:
  2071  		s = &ast.DeclStmt{Decl: p.parseDecl(syncStmt)}
  2072  	case
  2073  		// tokens that may start an expression
  2074  		token.IDENT, token.INT, token.FLOAT, token.IMAG, token.CHAR, token.STRING, token.FUNC, token.LPAREN, // operands
  2075  		token.LBRACK, token.STRUCT, // composite types
  2076  		token.ADD, token.SUB, token.MUL, token.AND, token.XOR, token.ARROW, token.NOT: // unary operators
  2077  		s, _ = p.parseSimpleStmt(labelOk)
  2078  		// because of the required look-ahead, labeled statements are
  2079  		// parsed by parseSimpleStmt - don't expect a semicolon after
  2080  		// them
  2081  		if _, isLabeledStmt := s.(*ast.LabeledStmt); !isLabeledStmt {
  2082  			p.expectSemi()
  2083  		}
  2084  	case token.GO:
  2085  		s = p.parseGoStmt()
  2086  	case token.DEFER:
  2087  		s = p.parseDeferStmt()
  2088  	case token.RETURN:
  2089  		s = p.parseReturnStmt()
  2090  	case token.BREAK, token.CONTINUE, token.GOTO, token.FALLTHROUGH:
  2091  		s = p.parseBranchStmt(p.tok)
  2092  	case token.LBRACE:
  2093  		s = p.parseBlockStmt()
  2094  		p.expectSemi()
  2095  	case token.IF:
  2096  		s = p.parseIfStmt()
  2097  	case token.SWITCH:
  2098  		s = p.parseSwitchStmt()
  2099  	case token.SELECT:
  2100  		s = p.parseSelectStmt()
  2101  	case token.FOR:
  2102  		s = p.parseForStmt()
  2103  	case token.SEMICOLON:
  2104  		s = &ast.EmptyStmt{Semicolon: p.pos}
  2105  		p.next()
  2106  	case token.RBRACE:
  2107  		// a semicolon may be omitted before a closing "}"
  2108  		s = &ast.EmptyStmt{Semicolon: p.pos}
  2109  	default:
  2110  		// no statement found
  2111  		pos := p.pos
  2112  		p.errorExpected(pos, "statement")
  2113  		syncStmt(p)
  2114  		s = &ast.BadStmt{From: pos, To: p.pos}
  2115  	}
  2116  
  2117  	return
  2118  }
  2119  
  2120  // ----------------------------------------------------------------------------
  2121  // Declarations
  2122  
  2123  type parseSpecFunction func(doc *ast.CommentGroup, keyword token.Token, iota int) ast.Spec
  2124  
  2125  func isValidImport(lit string) bool {
  2126  	const illegalChars = `!"#$%&'()*,:;<=>?[\]^{|}` + "`\uFFFD"
  2127  	s, _ := strconv.Unquote(lit) // go/scanner returns a legal string literal
  2128  	for _, r := range s {
  2129  		if !unicode.IsGraphic(r) || unicode.IsSpace(r) || strings.ContainsRune(illegalChars, r) {
  2130  			return false
  2131  		}
  2132  	}
  2133  	return s != ""
  2134  }
  2135  
  2136  func (p *parser) parseImportSpec(doc *ast.CommentGroup, _ token.Token, _ int) ast.Spec {
  2137  	if p.trace {
  2138  		defer un(trace(p, "ImportSpec"))
  2139  	}
  2140  
  2141  	var ident *ast.Ident
  2142  	switch p.tok {
  2143  	case token.PERIOD:
  2144  		ident = &ast.Ident{NamePos: p.pos, Name: "."}
  2145  		p.next()
  2146  	case token.IDENT:
  2147  		ident = p.parseIdent()
  2148  	}
  2149  
  2150  	pos := p.pos
  2151  	var path string
  2152  	if p.tok == token.STRING {
  2153  		path = p.lit
  2154  		if !isValidImport(path) {
  2155  			p.error(pos, "invalid import path: "+path)
  2156  		}
  2157  		p.next()
  2158  	} else {
  2159  		p.expect(token.STRING) // use expect() error handling
  2160  	}
  2161  	p.expectSemi() // call before accessing p.linecomment
  2162  
  2163  	// collect imports
  2164  	spec := &ast.ImportSpec{
  2165  		Doc:     doc,
  2166  		Name:    ident,
  2167  		Path:    &ast.BasicLit{ValuePos: pos, Kind: token.STRING, Value: path},
  2168  		Comment: p.lineComment,
  2169  	}
  2170  	p.imports = append(p.imports, spec)
  2171  
  2172  	return spec
  2173  }
  2174  
  2175  func (p *parser) parseValueSpec(doc *ast.CommentGroup, keyword token.Token, iota int) ast.Spec {
  2176  	if p.trace {
  2177  		defer un(trace(p, keyword.String()+"Spec"))
  2178  	}
  2179  
  2180  	idents := p.parseIdentList()
  2181  	typ := p.tryType()
  2182  	var values []ast.Expr
  2183  	// always permit optional initialization for more tolerant parsing
  2184  	if p.tok == token.ASSIGN {
  2185  		p.next()
  2186  		values = p.parseRhsList()
  2187  	}
  2188  	p.expectSemi() // call before accessing p.linecomment
  2189  
  2190  	// Go spec: The scope of a constant or variable identifier declared inside
  2191  	// a function begins at the end of the ConstSpec or VarSpec and ends at
  2192  	// the end of the innermost containing block.
  2193  	// (Global identifiers are resolved in a separate phase after parsing.)
  2194  	spec := &ast.ValueSpec{
  2195  		Doc:     doc,
  2196  		Names:   idents,
  2197  		Type:    typ,
  2198  		Values:  values,
  2199  		Comment: p.lineComment,
  2200  	}
  2201  	kind := ast.Con
  2202  	if keyword == token.VAR {
  2203  		kind = ast.Var
  2204  	}
  2205  	p.declare(spec, iota, p.topScope, kind, idents...)
  2206  
  2207  	return spec
  2208  }
  2209  
  2210  func (p *parser) parseTypeSpec(doc *ast.CommentGroup, _ token.Token, _ int) ast.Spec {
  2211  	if p.trace {
  2212  		defer un(trace(p, "TypeSpec"))
  2213  	}
  2214  
  2215  	ident := p.parseIdent()
  2216  
  2217  	// Go spec: The scope of a type identifier declared inside a function begins
  2218  	// at the identifier in the TypeSpec and ends at the end of the innermost
  2219  	// containing block.
  2220  	// (Global identifiers are resolved in a separate phase after parsing.)
  2221  	spec := &ast.TypeSpec{Doc: doc, Name: ident}
  2222  	p.declare(spec, nil, p.topScope, ast.Typ, ident)
  2223  
  2224  	spec.Type = p.parseType()
  2225  	p.expectSemi() // call before accessing p.linecomment
  2226  	spec.Comment = p.lineComment
  2227  
  2228  	return spec
  2229  }
  2230  
  2231  func (p *parser) parseGenDecl(keyword token.Token, f parseSpecFunction) *ast.GenDecl {
  2232  	if p.trace {
  2233  		defer un(trace(p, "GenDecl("+keyword.String()+")"))
  2234  	}
  2235  
  2236  	doc := p.leadComment
  2237  	pos := p.expect(keyword)
  2238  	var lparen, rparen token.Pos
  2239  	var list []ast.Spec
  2240  	if p.tok == token.LPAREN {
  2241  		lparen = p.pos
  2242  		p.next()
  2243  		for iota := 0; p.tok != token.RPAREN && p.tok != token.EOF; iota++ {
  2244  			list = append(list, f(p.leadComment, keyword, iota))
  2245  		}
  2246  		rparen = p.expect(token.RPAREN)
  2247  		p.expectSemi()
  2248  	} else {
  2249  		list = append(list, f(nil, keyword, 0))
  2250  	}
  2251  
  2252  	return &ast.GenDecl{
  2253  		Doc:    doc,
  2254  		TokPos: pos,
  2255  		Tok:    keyword,
  2256  		Lparen: lparen,
  2257  		Specs:  list,
  2258  		Rparen: rparen,
  2259  	}
  2260  }
  2261  
  2262  func (p *parser) parseReceiver(scope *ast.Scope) *ast.FieldList {
  2263  	if p.trace {
  2264  		defer un(trace(p, "Receiver"))
  2265  	}
  2266  
  2267  	par := p.parseParameters(scope, false)
  2268  
  2269  	// must have exactly one receiver
  2270  	if par.NumFields() != 1 {
  2271  		p.errorExpected(par.Opening, "exactly one receiver")
  2272  		par.List = []*ast.Field{{Type: &ast.BadExpr{From: par.Opening, To: par.Closing + 1}}}
  2273  		return par
  2274  	}
  2275  
  2276  	// recv type must be of the form ["*"] identifier
  2277  	recv := par.List[0]
  2278  	base := deref(recv.Type)
  2279  	if _, isIdent := base.(*ast.Ident); !isIdent {
  2280  		if _, isBad := base.(*ast.BadExpr); !isBad {
  2281  			// only report error if it's a new one
  2282  			p.errorExpected(base.Pos(), "(unqualified) identifier")
  2283  		}
  2284  		par.List = []*ast.Field{
  2285  			{Type: &ast.BadExpr{From: recv.Pos(), To: recv.End()}},
  2286  		}
  2287  	}
  2288  
  2289  	return par
  2290  }
  2291  
  2292  func (p *parser) parseFuncDecl() *ast.FuncDecl {
  2293  	if p.trace {
  2294  		defer un(trace(p, "FunctionDecl"))
  2295  	}
  2296  
  2297  	doc := p.leadComment
  2298  	pos := p.expect(token.FUNC)
  2299  	scope := ast.NewScope(p.topScope) // function scope
  2300  
  2301  	var recv *ast.FieldList
  2302  	if p.tok == token.LPAREN {
  2303  		recv = p.parseReceiver(scope)
  2304  	}
  2305  
  2306  	ident := p.parseIdent()
  2307  
  2308  	params, results := p.parseSignature(scope)
  2309  
  2310  	var body *ast.BlockStmt
  2311  	if p.tok == token.LBRACE {
  2312  		body = p.parseBody(scope)
  2313  	}
  2314  	p.expectSemi()
  2315  
  2316  	decl := &ast.FuncDecl{
  2317  		Doc:  doc,
  2318  		Recv: recv,
  2319  		Name: ident,
  2320  		Type: &ast.FuncType{
  2321  			Func:    pos,
  2322  			Params:  params,
  2323  			Results: results,
  2324  		},
  2325  		Body: body,
  2326  	}
  2327  	if recv == nil {
  2328  		// Go spec: The scope of an identifier denoting a constant, type,
  2329  		// variable, or function (but not method) declared at top level
  2330  		// (outside any function) is the package block.
  2331  		//
  2332  		// init() functions cannot be referred to and there may
  2333  		// be more than one - don't put them in the pkgScope
  2334  		if ident.Name != "init" {
  2335  			p.declare(decl, nil, p.pkgScope, ast.Fun, ident)
  2336  		}
  2337  	}
  2338  
  2339  	return decl
  2340  }
  2341  
  2342  func (p *parser) parseDecl(sync func(*parser)) ast.Decl {
  2343  	if p.trace {
  2344  		defer un(trace(p, "Declaration"))
  2345  	}
  2346  
  2347  	var f parseSpecFunction
  2348  	switch p.tok {
  2349  	case token.CONST, token.VAR:
  2350  		f = p.parseValueSpec
  2351  
  2352  	case token.TYPE:
  2353  		f = p.parseTypeSpec
  2354  
  2355  	case token.FUNC:
  2356  		return p.parseFuncDecl()
  2357  
  2358  	default:
  2359  		pos := p.pos
  2360  		p.errorExpected(pos, "declaration")
  2361  		sync(p)
  2362  		return &ast.BadDecl{From: pos, To: p.pos}
  2363  	}
  2364  
  2365  	return p.parseGenDecl(p.tok, f)
  2366  }
  2367  
  2368  // ----------------------------------------------------------------------------
  2369  // Source files
  2370  
  2371  func (p *parser) parseFile() *ast.File {
  2372  	if p.trace {
  2373  		defer un(trace(p, "File"))
  2374  	}
  2375  
  2376  	// Don't bother parsing the rest if we had errors scanning the first token.
  2377  	// Likely not a Go source file at all.
  2378  	if p.errors.Len() != 0 {
  2379  		return nil
  2380  	}
  2381  
  2382  	// package clause
  2383  	doc := p.leadComment
  2384  	pos := p.expect(token.PACKAGE)
  2385  	// Go spec: The package clause is not a declaration;
  2386  	// the package name does not appear in any scope.
  2387  	ident := p.parseIdent()
  2388  	if ident.Name == "_" && p.mode&DeclarationErrors != 0 {
  2389  		p.error(p.pos, "invalid package name _")
  2390  	}
  2391  	p.expectSemi()
  2392  
  2393  	// Don't bother parsing the rest if we had errors parsing the package clause.
  2394  	// Likely not a Go source file at all.
  2395  	if p.errors.Len() != 0 {
  2396  		return nil
  2397  	}
  2398  
  2399  	p.openScope()
  2400  	p.pkgScope = p.topScope
  2401  	var decls []ast.Decl
  2402  	if p.mode&PackageClauseOnly == 0 {
  2403  		// import decls
  2404  		for p.tok == token.IMPORT {
  2405  			decls = append(decls, p.parseGenDecl(token.IMPORT, p.parseImportSpec))
  2406  		}
  2407  
  2408  		if p.mode&ImportsOnly == 0 {
  2409  			// rest of package body
  2410  			for p.tok != token.EOF {
  2411  				decls = append(decls, p.parseDecl(syncDecl))
  2412  			}
  2413  		}
  2414  	}
  2415  	p.closeScope()
  2416  	assert(p.topScope == nil, "unbalanced scopes")
  2417  	assert(p.labelScope == nil, "unbalanced label scopes")
  2418  
  2419  	// resolve global identifiers within the same file
  2420  	i := 0
  2421  	for _, ident := range p.unresolved {
  2422  		// i <= index for current ident
  2423  		assert(ident.Obj == unresolved, "object already resolved")
  2424  		ident.Obj = p.pkgScope.Lookup(ident.Name) // also removes unresolved sentinel
  2425  		if ident.Obj == nil {
  2426  			p.unresolved[i] = ident
  2427  			i++
  2428  		}
  2429  	}
  2430  
  2431  	return &ast.File{
  2432  		Doc:        doc,
  2433  		Package:    pos,
  2434  		Name:       ident,
  2435  		Decls:      decls,
  2436  		Scope:      p.pkgScope,
  2437  		Imports:    p.imports,
  2438  		Unresolved: p.unresolved[0:i],
  2439  		Comments:   p.comments,
  2440  	}
  2441  }