github.com/megatontech/mynoteforgo@v0.0.0-20200507084910-5d0c6ea6e890/源码/cmd/compile/internal/syntax/parser.go (about)

     1  // Copyright 2016 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 syntax
     6  
     7  import (
     8  	"fmt"
     9  	"io"
    10  	"strconv"
    11  	"strings"
    12  )
    13  
    14  const debug = false
    15  const trace = false
    16  
    17  type parser struct {
    18  	file *PosBase
    19  	errh ErrorHandler
    20  	mode Mode
    21  	scanner
    22  
    23  	base   *PosBase // current position base
    24  	first  error    // first error encountered
    25  	errcnt int      // number of errors encountered
    26  	pragma Pragma   // pragma flags
    27  
    28  	fnest  int    // function nesting level (for error handling)
    29  	xnest  int    // expression nesting level (for complit ambiguity resolution)
    30  	indent []byte // tracing support
    31  }
    32  
    33  func (p *parser) init(file *PosBase, r io.Reader, errh ErrorHandler, pragh PragmaHandler, mode Mode) {
    34  	p.file = file
    35  	p.errh = errh
    36  	p.mode = mode
    37  	p.scanner.init(
    38  		r,
    39  		// Error and directive handler for scanner.
    40  		// Because the (line, col) positions passed to the
    41  		// handler is always at or after the current reading
    42  		// position, it is safe to use the most recent position
    43  		// base to compute the corresponding Pos value.
    44  		func(line, col uint, msg string) {
    45  			if msg[0] != '/' {
    46  				p.errorAt(p.posAt(line, col), msg)
    47  				return
    48  			}
    49  
    50  			// otherwise it must be a comment containing a line or go: directive
    51  			text := commentText(msg)
    52  			if strings.HasPrefix(text, "line ") {
    53  				var pos Pos // position immediately following the comment
    54  				if msg[1] == '/' {
    55  					// line comment (newline is part of the comment)
    56  					pos = MakePos(p.file, line+1, colbase)
    57  				} else {
    58  					// regular comment
    59  					// (if the comment spans multiple lines it's not
    60  					// a valid line directive and will be discarded
    61  					// by updateBase)
    62  					pos = MakePos(p.file, line, col+uint(len(msg)))
    63  				}
    64  				p.updateBase(pos, line, col+2+5, text[5:]) // +2 to skip over // or /*
    65  				return
    66  			}
    67  
    68  			// go: directive (but be conservative and test)
    69  			if pragh != nil && strings.HasPrefix(text, "go:") {
    70  				p.pragma |= pragh(p.posAt(line, col+2), text) // +2 to skip over // or /*
    71  			}
    72  		},
    73  		directives,
    74  	)
    75  
    76  	p.base = file
    77  	p.first = nil
    78  	p.errcnt = 0
    79  	p.pragma = 0
    80  
    81  	p.fnest = 0
    82  	p.xnest = 0
    83  	p.indent = nil
    84  }
    85  
    86  // updateBase sets the current position base to a new line base at pos.
    87  // The base's filename, line, and column values are extracted from text
    88  // which is positioned at (tline, tcol) (only needed for error messages).
    89  func (p *parser) updateBase(pos Pos, tline, tcol uint, text string) {
    90  	i, n, ok := trailingDigits(text)
    91  	if i == 0 {
    92  		return // ignore (not a line directive)
    93  	}
    94  	// i > 0
    95  
    96  	if !ok {
    97  		// text has a suffix :xxx but xxx is not a number
    98  		p.errorAt(p.posAt(tline, tcol+i), "invalid line number: "+text[i:])
    99  		return
   100  	}
   101  
   102  	var line, col uint
   103  	i2, n2, ok2 := trailingDigits(text[:i-1])
   104  	if ok2 {
   105  		//line filename:line:col
   106  		i, i2 = i2, i
   107  		line, col = n2, n
   108  		if col == 0 || col > PosMax {
   109  			p.errorAt(p.posAt(tline, tcol+i2), "invalid column number: "+text[i2:])
   110  			return
   111  		}
   112  		text = text[:i2-1] // lop off ":col"
   113  	} else {
   114  		//line filename:line
   115  		line = n
   116  	}
   117  
   118  	if line == 0 || line > PosMax {
   119  		p.errorAt(p.posAt(tline, tcol+i), "invalid line number: "+text[i:])
   120  		return
   121  	}
   122  
   123  	// If we have a column (//line filename:line:col form),
   124  	// an empty filename means to use the previous filename.
   125  	filename := text[:i-1] // lop off ":line"
   126  	if filename == "" && ok2 {
   127  		filename = p.base.Filename()
   128  	}
   129  
   130  	p.base = NewLineBase(pos, filename, line, col)
   131  }
   132  
   133  func commentText(s string) string {
   134  	if s[:2] == "/*" {
   135  		return s[2 : len(s)-2] // lop off /* and */
   136  	}
   137  
   138  	// line comment (does not include newline)
   139  	// (on Windows, the line comment may end in \r\n)
   140  	i := len(s)
   141  	if s[i-1] == '\r' {
   142  		i--
   143  	}
   144  	return s[2:i] // lop off //, and \r at end, if any
   145  }
   146  
   147  func trailingDigits(text string) (uint, uint, bool) {
   148  	// Want to use LastIndexByte below but it's not defined in Go1.4 and bootstrap fails.
   149  	i := strings.LastIndex(text, ":") // look from right (Windows filenames may contain ':')
   150  	if i < 0 {
   151  		return 0, 0, false // no ":"
   152  	}
   153  	// i >= 0
   154  	n, err := strconv.ParseUint(text[i+1:], 10, 0)
   155  	return uint(i + 1), uint(n), err == nil
   156  }
   157  
   158  func (p *parser) got(tok token) bool {
   159  	if p.tok == tok {
   160  		p.next()
   161  		return true
   162  	}
   163  	return false
   164  }
   165  
   166  func (p *parser) want(tok token) {
   167  	if !p.got(tok) {
   168  		p.syntaxError("expecting " + tokstring(tok))
   169  		p.advance()
   170  	}
   171  }
   172  
   173  // ----------------------------------------------------------------------------
   174  // Error handling
   175  
   176  // posAt returns the Pos value for (line, col) and the current position base.
   177  func (p *parser) posAt(line, col uint) Pos {
   178  	return MakePos(p.base, line, col)
   179  }
   180  
   181  // error reports an error at the given position.
   182  func (p *parser) errorAt(pos Pos, msg string) {
   183  	err := Error{pos, msg}
   184  	if p.first == nil {
   185  		p.first = err
   186  	}
   187  	p.errcnt++
   188  	if p.errh == nil {
   189  		panic(p.first)
   190  	}
   191  	p.errh(err)
   192  }
   193  
   194  // syntaxErrorAt reports a syntax error at the given position.
   195  func (p *parser) syntaxErrorAt(pos Pos, msg string) {
   196  	if trace {
   197  		p.print("syntax error: " + msg)
   198  	}
   199  
   200  	if p.tok == _EOF && p.first != nil {
   201  		return // avoid meaningless follow-up errors
   202  	}
   203  
   204  	// add punctuation etc. as needed to msg
   205  	switch {
   206  	case msg == "":
   207  		// nothing to do
   208  	case strings.HasPrefix(msg, "in "), strings.HasPrefix(msg, "at "), strings.HasPrefix(msg, "after "):
   209  		msg = " " + msg
   210  	case strings.HasPrefix(msg, "expecting "):
   211  		msg = ", " + msg
   212  	default:
   213  		// plain error - we don't care about current token
   214  		p.errorAt(pos, "syntax error: "+msg)
   215  		return
   216  	}
   217  
   218  	// determine token string
   219  	var tok string
   220  	switch p.tok {
   221  	case _Name, _Semi:
   222  		tok = p.lit
   223  	case _Literal:
   224  		tok = "literal " + p.lit
   225  	case _Operator:
   226  		tok = p.op.String()
   227  	case _AssignOp:
   228  		tok = p.op.String() + "="
   229  	case _IncOp:
   230  		tok = p.op.String()
   231  		tok += tok
   232  	default:
   233  		tok = tokstring(p.tok)
   234  	}
   235  
   236  	p.errorAt(pos, "syntax error: unexpected "+tok+msg)
   237  }
   238  
   239  // tokstring returns the English word for selected punctuation tokens
   240  // for more readable error messages.
   241  func tokstring(tok token) string {
   242  	switch tok {
   243  	case _Comma:
   244  		return "comma"
   245  	case _Semi:
   246  		return "semicolon or newline"
   247  	}
   248  	return tok.String()
   249  }
   250  
   251  // Convenience methods using the current token position.
   252  func (p *parser) pos() Pos               { return p.posAt(p.line, p.col) }
   253  func (p *parser) syntaxError(msg string) { p.syntaxErrorAt(p.pos(), msg) }
   254  
   255  // The stopset contains keywords that start a statement.
   256  // They are good synchronization points in case of syntax
   257  // errors and (usually) shouldn't be skipped over.
   258  const stopset uint64 = 1<<_Break |
   259  	1<<_Const |
   260  	1<<_Continue |
   261  	1<<_Defer |
   262  	1<<_Fallthrough |
   263  	1<<_For |
   264  	1<<_Go |
   265  	1<<_Goto |
   266  	1<<_If |
   267  	1<<_Return |
   268  	1<<_Select |
   269  	1<<_Switch |
   270  	1<<_Type |
   271  	1<<_Var
   272  
   273  // Advance consumes tokens until it finds a token of the stopset or followlist.
   274  // The stopset is only considered if we are inside a function (p.fnest > 0).
   275  // The followlist is the list of valid tokens that can follow a production;
   276  // if it is empty, exactly one (non-EOF) token is consumed to ensure progress.
   277  func (p *parser) advance(followlist ...token) {
   278  	if trace {
   279  		p.print(fmt.Sprintf("advance %s", followlist))
   280  	}
   281  
   282  	// compute follow set
   283  	// (not speed critical, advance is only called in error situations)
   284  	var followset uint64 = 1 << _EOF // don't skip over EOF
   285  	if len(followlist) > 0 {
   286  		if p.fnest > 0 {
   287  			followset |= stopset
   288  		}
   289  		for _, tok := range followlist {
   290  			followset |= 1 << tok
   291  		}
   292  	}
   293  
   294  	for !contains(followset, p.tok) {
   295  		if trace {
   296  			p.print("skip " + p.tok.String())
   297  		}
   298  		p.next()
   299  		if len(followlist) == 0 {
   300  			break
   301  		}
   302  	}
   303  
   304  	if trace {
   305  		p.print("next " + p.tok.String())
   306  	}
   307  }
   308  
   309  // usage: defer p.trace(msg)()
   310  func (p *parser) trace(msg string) func() {
   311  	p.print(msg + " (")
   312  	const tab = ". "
   313  	p.indent = append(p.indent, tab...)
   314  	return func() {
   315  		p.indent = p.indent[:len(p.indent)-len(tab)]
   316  		if x := recover(); x != nil {
   317  			panic(x) // skip print_trace
   318  		}
   319  		p.print(")")
   320  	}
   321  }
   322  
   323  func (p *parser) print(msg string) {
   324  	fmt.Printf("%5d: %s%s\n", p.line, p.indent, msg)
   325  }
   326  
   327  // ----------------------------------------------------------------------------
   328  // Package files
   329  //
   330  // Parse methods are annotated with matching Go productions as appropriate.
   331  // The annotations are intended as guidelines only since a single Go grammar
   332  // rule may be covered by multiple parse methods and vice versa.
   333  //
   334  // Excluding methods returning slices, parse methods named xOrNil may return
   335  // nil; all others are expected to return a valid non-nil node.
   336  
   337  // SourceFile = PackageClause ";" { ImportDecl ";" } { TopLevelDecl ";" } .
   338  func (p *parser) fileOrNil() *File {
   339  	if trace {
   340  		defer p.trace("file")()
   341  	}
   342  
   343  	f := new(File)
   344  	f.pos = p.pos()
   345  
   346  	// PackageClause
   347  	if !p.got(_Package) {
   348  		p.syntaxError("package statement must be first")
   349  		return nil
   350  	}
   351  	f.PkgName = p.name()
   352  	p.want(_Semi)
   353  
   354  	// don't bother continuing if package clause has errors
   355  	if p.first != nil {
   356  		return nil
   357  	}
   358  
   359  	// { ImportDecl ";" }
   360  	for p.got(_Import) {
   361  		f.DeclList = p.appendGroup(f.DeclList, p.importDecl)
   362  		p.want(_Semi)
   363  	}
   364  
   365  	// { TopLevelDecl ";" }
   366  	for p.tok != _EOF {
   367  		switch p.tok {
   368  		case _Const:
   369  			p.next()
   370  			f.DeclList = p.appendGroup(f.DeclList, p.constDecl)
   371  
   372  		case _Type:
   373  			p.next()
   374  			f.DeclList = p.appendGroup(f.DeclList, p.typeDecl)
   375  
   376  		case _Var:
   377  			p.next()
   378  			f.DeclList = p.appendGroup(f.DeclList, p.varDecl)
   379  
   380  		case _Func:
   381  			p.next()
   382  			if d := p.funcDeclOrNil(); d != nil {
   383  				f.DeclList = append(f.DeclList, d)
   384  			}
   385  
   386  		default:
   387  			if p.tok == _Lbrace && len(f.DeclList) > 0 && isEmptyFuncDecl(f.DeclList[len(f.DeclList)-1]) {
   388  				// opening { of function declaration on next line
   389  				p.syntaxError("unexpected semicolon or newline before {")
   390  			} else {
   391  				p.syntaxError("non-declaration statement outside function body")
   392  			}
   393  			p.advance(_Const, _Type, _Var, _Func)
   394  			continue
   395  		}
   396  
   397  		// Reset p.pragma BEFORE advancing to the next token (consuming ';')
   398  		// since comments before may set pragmas for the next function decl.
   399  		p.pragma = 0
   400  
   401  		if p.tok != _EOF && !p.got(_Semi) {
   402  			p.syntaxError("after top level declaration")
   403  			p.advance(_Const, _Type, _Var, _Func)
   404  		}
   405  	}
   406  	// p.tok == _EOF
   407  
   408  	f.Lines = p.source.line
   409  
   410  	return f
   411  }
   412  
   413  func isEmptyFuncDecl(dcl Decl) bool {
   414  	f, ok := dcl.(*FuncDecl)
   415  	return ok && f.Body == nil
   416  }
   417  
   418  // ----------------------------------------------------------------------------
   419  // Declarations
   420  
   421  // list parses a possibly empty, sep-separated list, optionally
   422  // followed by sep and enclosed by ( and ) or { and }. open is
   423  // one of _Lparen, or _Lbrace, sep is one of _Comma or _Semi,
   424  // and close is expected to be the (closing) opposite of open.
   425  // For each list element, f is called. After f returns true, no
   426  // more list elements are accepted. list returns the position
   427  // of the closing token.
   428  //
   429  // list = "(" { f sep } ")" |
   430  //        "{" { f sep } "}" . // sep is optional before ")" or "}"
   431  //
   432  func (p *parser) list(open, sep, close token, f func() bool) Pos {
   433  	p.want(open)
   434  
   435  	var done bool
   436  	for p.tok != _EOF && p.tok != close && !done {
   437  		done = f()
   438  		// sep is optional before close
   439  		if !p.got(sep) && p.tok != close {
   440  			p.syntaxError(fmt.Sprintf("expecting %s or %s", tokstring(sep), tokstring(close)))
   441  			p.advance(_Rparen, _Rbrack, _Rbrace)
   442  			if p.tok != close {
   443  				// position could be better but we had an error so we don't care
   444  				return p.pos()
   445  			}
   446  		}
   447  	}
   448  
   449  	pos := p.pos()
   450  	p.want(close)
   451  	return pos
   452  }
   453  
   454  // appendGroup(f) = f | "(" { f ";" } ")" . // ";" is optional before ")"
   455  func (p *parser) appendGroup(list []Decl, f func(*Group) Decl) []Decl {
   456  	if p.tok == _Lparen {
   457  		g := new(Group)
   458  		p.list(_Lparen, _Semi, _Rparen, func() bool {
   459  			list = append(list, f(g))
   460  			return false
   461  		})
   462  	} else {
   463  		list = append(list, f(nil))
   464  	}
   465  
   466  	if debug {
   467  		for _, d := range list {
   468  			if d == nil {
   469  				panic("nil list entry")
   470  			}
   471  		}
   472  	}
   473  
   474  	return list
   475  }
   476  
   477  // ImportSpec = [ "." | PackageName ] ImportPath .
   478  // ImportPath = string_lit .
   479  func (p *parser) importDecl(group *Group) Decl {
   480  	if trace {
   481  		defer p.trace("importDecl")()
   482  	}
   483  
   484  	d := new(ImportDecl)
   485  	d.pos = p.pos()
   486  
   487  	switch p.tok {
   488  	case _Name:
   489  		d.LocalPkgName = p.name()
   490  	case _Dot:
   491  		d.LocalPkgName = p.newName(".")
   492  		p.next()
   493  	}
   494  	d.Path = p.oliteral()
   495  	if d.Path == nil {
   496  		p.syntaxError("missing import path")
   497  		p.advance(_Semi, _Rparen)
   498  		return nil
   499  	}
   500  	d.Group = group
   501  
   502  	return d
   503  }
   504  
   505  // ConstSpec = IdentifierList [ [ Type ] "=" ExpressionList ] .
   506  func (p *parser) constDecl(group *Group) Decl {
   507  	if trace {
   508  		defer p.trace("constDecl")()
   509  	}
   510  
   511  	d := new(ConstDecl)
   512  	d.pos = p.pos()
   513  
   514  	d.NameList = p.nameList(p.name())
   515  	if p.tok != _EOF && p.tok != _Semi && p.tok != _Rparen {
   516  		d.Type = p.typeOrNil()
   517  		if p.got(_Assign) {
   518  			d.Values = p.exprList()
   519  		}
   520  	}
   521  	d.Group = group
   522  
   523  	return d
   524  }
   525  
   526  // TypeSpec = identifier [ "=" ] Type .
   527  func (p *parser) typeDecl(group *Group) Decl {
   528  	if trace {
   529  		defer p.trace("typeDecl")()
   530  	}
   531  
   532  	d := new(TypeDecl)
   533  	d.pos = p.pos()
   534  
   535  	d.Name = p.name()
   536  	d.Alias = p.got(_Assign)
   537  	d.Type = p.typeOrNil()
   538  	if d.Type == nil {
   539  		d.Type = p.bad()
   540  		p.syntaxError("in type declaration")
   541  		p.advance(_Semi, _Rparen)
   542  	}
   543  	d.Group = group
   544  	d.Pragma = p.pragma
   545  
   546  	return d
   547  }
   548  
   549  // VarSpec = IdentifierList ( Type [ "=" ExpressionList ] | "=" ExpressionList ) .
   550  func (p *parser) varDecl(group *Group) Decl {
   551  	if trace {
   552  		defer p.trace("varDecl")()
   553  	}
   554  
   555  	d := new(VarDecl)
   556  	d.pos = p.pos()
   557  
   558  	d.NameList = p.nameList(p.name())
   559  	if p.got(_Assign) {
   560  		d.Values = p.exprList()
   561  	} else {
   562  		d.Type = p.type_()
   563  		if p.got(_Assign) {
   564  			d.Values = p.exprList()
   565  		}
   566  	}
   567  	d.Group = group
   568  
   569  	return d
   570  }
   571  
   572  // FunctionDecl = "func" FunctionName ( Function | Signature ) .
   573  // FunctionName = identifier .
   574  // Function     = Signature FunctionBody .
   575  // MethodDecl   = "func" Receiver MethodName ( Function | Signature ) .
   576  // Receiver     = Parameters .
   577  func (p *parser) funcDeclOrNil() *FuncDecl {
   578  	if trace {
   579  		defer p.trace("funcDecl")()
   580  	}
   581  
   582  	f := new(FuncDecl)
   583  	f.pos = p.pos()
   584  
   585  	if p.tok == _Lparen {
   586  		rcvr := p.paramList()
   587  		switch len(rcvr) {
   588  		case 0:
   589  			p.error("method has no receiver")
   590  		default:
   591  			p.error("method has multiple receivers")
   592  			fallthrough
   593  		case 1:
   594  			f.Recv = rcvr[0]
   595  		}
   596  	}
   597  
   598  	if p.tok != _Name {
   599  		p.syntaxError("expecting name or (")
   600  		p.advance(_Lbrace, _Semi)
   601  		return nil
   602  	}
   603  
   604  	f.Name = p.name()
   605  	f.Type = p.funcType()
   606  	if p.tok == _Lbrace {
   607  		f.Body = p.funcBody()
   608  	}
   609  	f.Pragma = p.pragma
   610  
   611  	return f
   612  }
   613  
   614  func (p *parser) funcBody() *BlockStmt {
   615  	p.fnest++
   616  	errcnt := p.errcnt
   617  	body := p.blockStmt("")
   618  	p.fnest--
   619  
   620  	// Don't check branches if there were syntax errors in the function
   621  	// as it may lead to spurious errors (e.g., see test/switch2.go) or
   622  	// possibly crashes due to incomplete syntax trees.
   623  	if p.mode&CheckBranches != 0 && errcnt == p.errcnt {
   624  		checkBranches(body, p.errh)
   625  	}
   626  
   627  	return body
   628  }
   629  
   630  // ----------------------------------------------------------------------------
   631  // Expressions
   632  
   633  func (p *parser) expr() Expr {
   634  	if trace {
   635  		defer p.trace("expr")()
   636  	}
   637  
   638  	return p.binaryExpr(0)
   639  }
   640  
   641  // Expression = UnaryExpr | Expression binary_op Expression .
   642  func (p *parser) binaryExpr(prec int) Expr {
   643  	// don't trace binaryExpr - only leads to overly nested trace output
   644  
   645  	x := p.unaryExpr()
   646  	for (p.tok == _Operator || p.tok == _Star) && p.prec > prec {
   647  		t := new(Operation)
   648  		t.pos = p.pos()
   649  		t.Op = p.op
   650  		t.X = x
   651  		tprec := p.prec
   652  		p.next()
   653  		t.Y = p.binaryExpr(tprec)
   654  		x = t
   655  	}
   656  	return x
   657  }
   658  
   659  // UnaryExpr = PrimaryExpr | unary_op UnaryExpr .
   660  func (p *parser) unaryExpr() Expr {
   661  	if trace {
   662  		defer p.trace("unaryExpr")()
   663  	}
   664  
   665  	switch p.tok {
   666  	case _Operator, _Star:
   667  		switch p.op {
   668  		case Mul, Add, Sub, Not, Xor:
   669  			x := new(Operation)
   670  			x.pos = p.pos()
   671  			x.Op = p.op
   672  			p.next()
   673  			x.X = p.unaryExpr()
   674  			return x
   675  
   676  		case And:
   677  			x := new(Operation)
   678  			x.pos = p.pos()
   679  			x.Op = And
   680  			p.next()
   681  			// unaryExpr may have returned a parenthesized composite literal
   682  			// (see comment in operand) - remove parentheses if any
   683  			x.X = unparen(p.unaryExpr())
   684  			return x
   685  		}
   686  
   687  	case _Arrow:
   688  		// receive op (<-x) or receive-only channel (<-chan E)
   689  		pos := p.pos()
   690  		p.next()
   691  
   692  		// If the next token is _Chan we still don't know if it is
   693  		// a channel (<-chan int) or a receive op (<-chan int(ch)).
   694  		// We only know once we have found the end of the unaryExpr.
   695  
   696  		x := p.unaryExpr()
   697  
   698  		// There are two cases:
   699  		//
   700  		//   <-chan...  => <-x is a channel type
   701  		//   <-x        => <-x is a receive operation
   702  		//
   703  		// In the first case, <- must be re-associated with
   704  		// the channel type parsed already:
   705  		//
   706  		//   <-(chan E)   =>  (<-chan E)
   707  		//   <-(chan<-E)  =>  (<-chan (<-E))
   708  
   709  		if _, ok := x.(*ChanType); ok {
   710  			// x is a channel type => re-associate <-
   711  			dir := SendOnly
   712  			t := x
   713  			for dir == SendOnly {
   714  				c, ok := t.(*ChanType)
   715  				if !ok {
   716  					break
   717  				}
   718  				dir = c.Dir
   719  				if dir == RecvOnly {
   720  					// t is type <-chan E but <-<-chan E is not permitted
   721  					// (report same error as for "type _ <-<-chan E")
   722  					p.syntaxError("unexpected <-, expecting chan")
   723  					// already progressed, no need to advance
   724  				}
   725  				c.Dir = RecvOnly
   726  				t = c.Elem
   727  			}
   728  			if dir == SendOnly {
   729  				// channel dir is <- but channel element E is not a channel
   730  				// (report same error as for "type _ <-chan<-E")
   731  				p.syntaxError(fmt.Sprintf("unexpected %s, expecting chan", String(t)))
   732  				// already progressed, no need to advance
   733  			}
   734  			return x
   735  		}
   736  
   737  		// x is not a channel type => we have a receive op
   738  		o := new(Operation)
   739  		o.pos = pos
   740  		o.Op = Recv
   741  		o.X = x
   742  		return o
   743  	}
   744  
   745  	// TODO(mdempsky): We need parens here so we can report an
   746  	// error for "(x) := true". It should be possible to detect
   747  	// and reject that more efficiently though.
   748  	return p.pexpr(true)
   749  }
   750  
   751  // callStmt parses call-like statements that can be preceded by 'defer' and 'go'.
   752  func (p *parser) callStmt() *CallStmt {
   753  	if trace {
   754  		defer p.trace("callStmt")()
   755  	}
   756  
   757  	s := new(CallStmt)
   758  	s.pos = p.pos()
   759  	s.Tok = p.tok // _Defer or _Go
   760  	p.next()
   761  
   762  	x := p.pexpr(p.tok == _Lparen) // keep_parens so we can report error below
   763  	if t := unparen(x); t != x {
   764  		p.errorAt(x.Pos(), fmt.Sprintf("expression in %s must not be parenthesized", s.Tok))
   765  		// already progressed, no need to advance
   766  		x = t
   767  	}
   768  
   769  	cx, ok := x.(*CallExpr)
   770  	if !ok {
   771  		p.errorAt(x.Pos(), fmt.Sprintf("expression in %s must be function call", s.Tok))
   772  		// already progressed, no need to advance
   773  		cx = new(CallExpr)
   774  		cx.pos = x.Pos()
   775  		cx.Fun = x // assume common error of missing parentheses (function invocation)
   776  	}
   777  
   778  	s.Call = cx
   779  	return s
   780  }
   781  
   782  // Operand     = Literal | OperandName | MethodExpr | "(" Expression ")" .
   783  // Literal     = BasicLit | CompositeLit | FunctionLit .
   784  // BasicLit    = int_lit | float_lit | imaginary_lit | rune_lit | string_lit .
   785  // OperandName = identifier | QualifiedIdent.
   786  func (p *parser) operand(keep_parens bool) Expr {
   787  	if trace {
   788  		defer p.trace("operand " + p.tok.String())()
   789  	}
   790  
   791  	switch p.tok {
   792  	case _Name:
   793  		return p.name()
   794  
   795  	case _Literal:
   796  		return p.oliteral()
   797  
   798  	case _Lparen:
   799  		pos := p.pos()
   800  		p.next()
   801  		p.xnest++
   802  		x := p.expr()
   803  		p.xnest--
   804  		p.want(_Rparen)
   805  
   806  		// Optimization: Record presence of ()'s only where needed
   807  		// for error reporting. Don't bother in other cases; it is
   808  		// just a waste of memory and time.
   809  
   810  		// Parentheses are not permitted on lhs of := .
   811  		// switch x.Op {
   812  		// case ONAME, ONONAME, OPACK, OTYPE, OLITERAL, OTYPESW:
   813  		// 	keep_parens = true
   814  		// }
   815  
   816  		// Parentheses are not permitted around T in a composite
   817  		// literal T{}. If the next token is a {, assume x is a
   818  		// composite literal type T (it may not be, { could be
   819  		// the opening brace of a block, but we don't know yet).
   820  		if p.tok == _Lbrace {
   821  			keep_parens = true
   822  		}
   823  
   824  		// Parentheses are also not permitted around the expression
   825  		// in a go/defer statement. In that case, operand is called
   826  		// with keep_parens set.
   827  		if keep_parens {
   828  			px := new(ParenExpr)
   829  			px.pos = pos
   830  			px.X = x
   831  			x = px
   832  		}
   833  		return x
   834  
   835  	case _Func:
   836  		pos := p.pos()
   837  		p.next()
   838  		t := p.funcType()
   839  		if p.tok == _Lbrace {
   840  			p.xnest++
   841  
   842  			f := new(FuncLit)
   843  			f.pos = pos
   844  			f.Type = t
   845  			f.Body = p.funcBody()
   846  
   847  			p.xnest--
   848  			return f
   849  		}
   850  		return t
   851  
   852  	case _Lbrack, _Chan, _Map, _Struct, _Interface:
   853  		return p.type_() // othertype
   854  
   855  	default:
   856  		x := p.bad()
   857  		p.syntaxError("expecting expression")
   858  		p.advance()
   859  		return x
   860  	}
   861  
   862  	// Syntactically, composite literals are operands. Because a complit
   863  	// type may be a qualified identifier which is handled by pexpr
   864  	// (together with selector expressions), complits are parsed there
   865  	// as well (operand is only called from pexpr).
   866  }
   867  
   868  // PrimaryExpr =
   869  // 	Operand |
   870  // 	Conversion |
   871  // 	PrimaryExpr Selector |
   872  // 	PrimaryExpr Index |
   873  // 	PrimaryExpr Slice |
   874  // 	PrimaryExpr TypeAssertion |
   875  // 	PrimaryExpr Arguments .
   876  //
   877  // Selector       = "." identifier .
   878  // Index          = "[" Expression "]" .
   879  // Slice          = "[" ( [ Expression ] ":" [ Expression ] ) |
   880  //                      ( [ Expression ] ":" Expression ":" Expression )
   881  //                  "]" .
   882  // TypeAssertion  = "." "(" Type ")" .
   883  // Arguments      = "(" [ ( ExpressionList | Type [ "," ExpressionList ] ) [ "..." ] [ "," ] ] ")" .
   884  func (p *parser) pexpr(keep_parens bool) Expr {
   885  	if trace {
   886  		defer p.trace("pexpr")()
   887  	}
   888  
   889  	x := p.operand(keep_parens)
   890  
   891  loop:
   892  	for {
   893  		pos := p.pos()
   894  		switch p.tok {
   895  		case _Dot:
   896  			p.next()
   897  			switch p.tok {
   898  			case _Name:
   899  				// pexpr '.' sym
   900  				t := new(SelectorExpr)
   901  				t.pos = pos
   902  				t.X = x
   903  				t.Sel = p.name()
   904  				x = t
   905  
   906  			case _Lparen:
   907  				p.next()
   908  				if p.got(_Type) {
   909  					t := new(TypeSwitchGuard)
   910  					// t.Lhs is filled in by parser.simpleStmt
   911  					t.pos = pos
   912  					t.X = x
   913  					x = t
   914  				} else {
   915  					t := new(AssertExpr)
   916  					t.pos = pos
   917  					t.X = x
   918  					t.Type = p.type_()
   919  					x = t
   920  				}
   921  				p.want(_Rparen)
   922  
   923  			default:
   924  				p.syntaxError("expecting name or (")
   925  				p.advance(_Semi, _Rparen)
   926  			}
   927  
   928  		case _Lbrack:
   929  			p.next()
   930  			p.xnest++
   931  
   932  			var i Expr
   933  			if p.tok != _Colon {
   934  				i = p.expr()
   935  				if p.got(_Rbrack) {
   936  					// x[i]
   937  					t := new(IndexExpr)
   938  					t.pos = pos
   939  					t.X = x
   940  					t.Index = i
   941  					x = t
   942  					p.xnest--
   943  					break
   944  				}
   945  			}
   946  
   947  			// x[i:...
   948  			t := new(SliceExpr)
   949  			t.pos = pos
   950  			t.X = x
   951  			t.Index[0] = i
   952  			p.want(_Colon)
   953  			if p.tok != _Colon && p.tok != _Rbrack {
   954  				// x[i:j...
   955  				t.Index[1] = p.expr()
   956  			}
   957  			if p.got(_Colon) {
   958  				t.Full = true
   959  				// x[i:j:...]
   960  				if t.Index[1] == nil {
   961  					p.error("middle index required in 3-index slice")
   962  				}
   963  				if p.tok != _Rbrack {
   964  					// x[i:j:k...
   965  					t.Index[2] = p.expr()
   966  				} else {
   967  					p.error("final index required in 3-index slice")
   968  				}
   969  			}
   970  			p.want(_Rbrack)
   971  
   972  			x = t
   973  			p.xnest--
   974  
   975  		case _Lparen:
   976  			t := new(CallExpr)
   977  			t.pos = pos
   978  			t.Fun = x
   979  			t.ArgList, t.HasDots = p.argList()
   980  			x = t
   981  
   982  		case _Lbrace:
   983  			// operand may have returned a parenthesized complit
   984  			// type; accept it but complain if we have a complit
   985  			t := unparen(x)
   986  			// determine if '{' belongs to a composite literal or a block statement
   987  			complit_ok := false
   988  			switch t.(type) {
   989  			case *Name, *SelectorExpr:
   990  				if p.xnest >= 0 {
   991  					// x is considered a composite literal type
   992  					complit_ok = true
   993  				}
   994  			case *ArrayType, *SliceType, *StructType, *MapType:
   995  				// x is a comptype
   996  				complit_ok = true
   997  			}
   998  			if !complit_ok {
   999  				break loop
  1000  			}
  1001  			if t != x {
  1002  				p.syntaxError("cannot parenthesize type in composite literal")
  1003  				// already progressed, no need to advance
  1004  			}
  1005  			n := p.complitexpr()
  1006  			n.Type = x
  1007  			x = n
  1008  
  1009  		default:
  1010  			break loop
  1011  		}
  1012  	}
  1013  
  1014  	return x
  1015  }
  1016  
  1017  // Element = Expression | LiteralValue .
  1018  func (p *parser) bare_complitexpr() Expr {
  1019  	if trace {
  1020  		defer p.trace("bare_complitexpr")()
  1021  	}
  1022  
  1023  	if p.tok == _Lbrace {
  1024  		// '{' start_complit braced_keyval_list '}'
  1025  		return p.complitexpr()
  1026  	}
  1027  
  1028  	return p.expr()
  1029  }
  1030  
  1031  // LiteralValue = "{" [ ElementList [ "," ] ] "}" .
  1032  func (p *parser) complitexpr() *CompositeLit {
  1033  	if trace {
  1034  		defer p.trace("complitexpr")()
  1035  	}
  1036  
  1037  	x := new(CompositeLit)
  1038  	x.pos = p.pos()
  1039  
  1040  	p.xnest++
  1041  	x.Rbrace = p.list(_Lbrace, _Comma, _Rbrace, func() bool {
  1042  		// value
  1043  		e := p.bare_complitexpr()
  1044  		if p.tok == _Colon {
  1045  			// key ':' value
  1046  			l := new(KeyValueExpr)
  1047  			l.pos = p.pos()
  1048  			p.next()
  1049  			l.Key = e
  1050  			l.Value = p.bare_complitexpr()
  1051  			e = l
  1052  			x.NKeys++
  1053  		}
  1054  		x.ElemList = append(x.ElemList, e)
  1055  		return false
  1056  	})
  1057  	p.xnest--
  1058  
  1059  	return x
  1060  }
  1061  
  1062  // ----------------------------------------------------------------------------
  1063  // Types
  1064  
  1065  func (p *parser) type_() Expr {
  1066  	if trace {
  1067  		defer p.trace("type_")()
  1068  	}
  1069  
  1070  	typ := p.typeOrNil()
  1071  	if typ == nil {
  1072  		typ = p.bad()
  1073  		p.syntaxError("expecting type")
  1074  		p.advance(_Comma, _Colon, _Semi, _Rparen, _Rbrack, _Rbrace)
  1075  	}
  1076  
  1077  	return typ
  1078  }
  1079  
  1080  func newIndirect(pos Pos, typ Expr) Expr {
  1081  	o := new(Operation)
  1082  	o.pos = pos
  1083  	o.Op = Mul
  1084  	o.X = typ
  1085  	return o
  1086  }
  1087  
  1088  // typeOrNil is like type_ but it returns nil if there was no type
  1089  // instead of reporting an error.
  1090  //
  1091  // Type     = TypeName | TypeLit | "(" Type ")" .
  1092  // TypeName = identifier | QualifiedIdent .
  1093  // TypeLit  = ArrayType | StructType | PointerType | FunctionType | InterfaceType |
  1094  // 	      SliceType | MapType | Channel_Type .
  1095  func (p *parser) typeOrNil() Expr {
  1096  	if trace {
  1097  		defer p.trace("typeOrNil")()
  1098  	}
  1099  
  1100  	pos := p.pos()
  1101  	switch p.tok {
  1102  	case _Star:
  1103  		// ptrtype
  1104  		p.next()
  1105  		return newIndirect(pos, p.type_())
  1106  
  1107  	case _Arrow:
  1108  		// recvchantype
  1109  		p.next()
  1110  		p.want(_Chan)
  1111  		t := new(ChanType)
  1112  		t.pos = pos
  1113  		t.Dir = RecvOnly
  1114  		t.Elem = p.chanElem()
  1115  		return t
  1116  
  1117  	case _Func:
  1118  		// fntype
  1119  		p.next()
  1120  		return p.funcType()
  1121  
  1122  	case _Lbrack:
  1123  		// '[' oexpr ']' ntype
  1124  		// '[' _DotDotDot ']' ntype
  1125  		p.next()
  1126  		p.xnest++
  1127  		if p.got(_Rbrack) {
  1128  			// []T
  1129  			p.xnest--
  1130  			t := new(SliceType)
  1131  			t.pos = pos
  1132  			t.Elem = p.type_()
  1133  			return t
  1134  		}
  1135  
  1136  		// [n]T
  1137  		t := new(ArrayType)
  1138  		t.pos = pos
  1139  		if !p.got(_DotDotDot) {
  1140  			t.Len = p.expr()
  1141  		}
  1142  		p.want(_Rbrack)
  1143  		p.xnest--
  1144  		t.Elem = p.type_()
  1145  		return t
  1146  
  1147  	case _Chan:
  1148  		// _Chan non_recvchantype
  1149  		// _Chan _Comm ntype
  1150  		p.next()
  1151  		t := new(ChanType)
  1152  		t.pos = pos
  1153  		if p.got(_Arrow) {
  1154  			t.Dir = SendOnly
  1155  		}
  1156  		t.Elem = p.chanElem()
  1157  		return t
  1158  
  1159  	case _Map:
  1160  		// _Map '[' ntype ']' ntype
  1161  		p.next()
  1162  		p.want(_Lbrack)
  1163  		t := new(MapType)
  1164  		t.pos = pos
  1165  		t.Key = p.type_()
  1166  		p.want(_Rbrack)
  1167  		t.Value = p.type_()
  1168  		return t
  1169  
  1170  	case _Struct:
  1171  		return p.structType()
  1172  
  1173  	case _Interface:
  1174  		return p.interfaceType()
  1175  
  1176  	case _Name:
  1177  		return p.dotname(p.name())
  1178  
  1179  	case _Lparen:
  1180  		p.next()
  1181  		t := p.type_()
  1182  		p.want(_Rparen)
  1183  		return t
  1184  	}
  1185  
  1186  	return nil
  1187  }
  1188  
  1189  func (p *parser) funcType() *FuncType {
  1190  	if trace {
  1191  		defer p.trace("funcType")()
  1192  	}
  1193  
  1194  	typ := new(FuncType)
  1195  	typ.pos = p.pos()
  1196  	typ.ParamList = p.paramList()
  1197  	typ.ResultList = p.funcResult()
  1198  
  1199  	return typ
  1200  }
  1201  
  1202  func (p *parser) chanElem() Expr {
  1203  	if trace {
  1204  		defer p.trace("chanElem")()
  1205  	}
  1206  
  1207  	typ := p.typeOrNil()
  1208  	if typ == nil {
  1209  		typ = p.bad()
  1210  		p.syntaxError("missing channel element type")
  1211  		// assume element type is simply absent - don't advance
  1212  	}
  1213  
  1214  	return typ
  1215  }
  1216  
  1217  func (p *parser) dotname(name *Name) Expr {
  1218  	if trace {
  1219  		defer p.trace("dotname")()
  1220  	}
  1221  
  1222  	if p.tok == _Dot {
  1223  		s := new(SelectorExpr)
  1224  		s.pos = p.pos()
  1225  		p.next()
  1226  		s.X = name
  1227  		s.Sel = p.name()
  1228  		return s
  1229  	}
  1230  	return name
  1231  }
  1232  
  1233  // StructType = "struct" "{" { FieldDecl ";" } "}" .
  1234  func (p *parser) structType() *StructType {
  1235  	if trace {
  1236  		defer p.trace("structType")()
  1237  	}
  1238  
  1239  	typ := new(StructType)
  1240  	typ.pos = p.pos()
  1241  
  1242  	p.want(_Struct)
  1243  	p.list(_Lbrace, _Semi, _Rbrace, func() bool {
  1244  		p.fieldDecl(typ)
  1245  		return false
  1246  	})
  1247  
  1248  	return typ
  1249  }
  1250  
  1251  // InterfaceType = "interface" "{" { MethodSpec ";" } "}" .
  1252  func (p *parser) interfaceType() *InterfaceType {
  1253  	if trace {
  1254  		defer p.trace("interfaceType")()
  1255  	}
  1256  
  1257  	typ := new(InterfaceType)
  1258  	typ.pos = p.pos()
  1259  
  1260  	p.want(_Interface)
  1261  	p.list(_Lbrace, _Semi, _Rbrace, func() bool {
  1262  		if m := p.methodDecl(); m != nil {
  1263  			typ.MethodList = append(typ.MethodList, m)
  1264  		}
  1265  		return false
  1266  	})
  1267  
  1268  	return typ
  1269  }
  1270  
  1271  // Result = Parameters | Type .
  1272  func (p *parser) funcResult() []*Field {
  1273  	if trace {
  1274  		defer p.trace("funcResult")()
  1275  	}
  1276  
  1277  	if p.tok == _Lparen {
  1278  		return p.paramList()
  1279  	}
  1280  
  1281  	pos := p.pos()
  1282  	if typ := p.typeOrNil(); typ != nil {
  1283  		f := new(Field)
  1284  		f.pos = pos
  1285  		f.Type = typ
  1286  		return []*Field{f}
  1287  	}
  1288  
  1289  	return nil
  1290  }
  1291  
  1292  func (p *parser) addField(styp *StructType, pos Pos, name *Name, typ Expr, tag *BasicLit) {
  1293  	if tag != nil {
  1294  		for i := len(styp.FieldList) - len(styp.TagList); i > 0; i-- {
  1295  			styp.TagList = append(styp.TagList, nil)
  1296  		}
  1297  		styp.TagList = append(styp.TagList, tag)
  1298  	}
  1299  
  1300  	f := new(Field)
  1301  	f.pos = pos
  1302  	f.Name = name
  1303  	f.Type = typ
  1304  	styp.FieldList = append(styp.FieldList, f)
  1305  
  1306  	if debug && tag != nil && len(styp.FieldList) != len(styp.TagList) {
  1307  		panic("inconsistent struct field list")
  1308  	}
  1309  }
  1310  
  1311  // FieldDecl      = (IdentifierList Type | AnonymousField) [ Tag ] .
  1312  // AnonymousField = [ "*" ] TypeName .
  1313  // Tag            = string_lit .
  1314  func (p *parser) fieldDecl(styp *StructType) {
  1315  	if trace {
  1316  		defer p.trace("fieldDecl")()
  1317  	}
  1318  
  1319  	pos := p.pos()
  1320  	switch p.tok {
  1321  	case _Name:
  1322  		name := p.name()
  1323  		if p.tok == _Dot || p.tok == _Literal || p.tok == _Semi || p.tok == _Rbrace {
  1324  			// embed oliteral
  1325  			typ := p.qualifiedName(name)
  1326  			tag := p.oliteral()
  1327  			p.addField(styp, pos, nil, typ, tag)
  1328  			return
  1329  		}
  1330  
  1331  		// new_name_list ntype oliteral
  1332  		names := p.nameList(name)
  1333  		typ := p.type_()
  1334  		tag := p.oliteral()
  1335  
  1336  		for _, name := range names {
  1337  			p.addField(styp, name.Pos(), name, typ, tag)
  1338  		}
  1339  
  1340  	case _Lparen:
  1341  		p.next()
  1342  		if p.tok == _Star {
  1343  			// '(' '*' embed ')' oliteral
  1344  			pos := p.pos()
  1345  			p.next()
  1346  			typ := newIndirect(pos, p.qualifiedName(nil))
  1347  			p.want(_Rparen)
  1348  			tag := p.oliteral()
  1349  			p.addField(styp, pos, nil, typ, tag)
  1350  			p.syntaxError("cannot parenthesize embedded type")
  1351  
  1352  		} else {
  1353  			// '(' embed ')' oliteral
  1354  			typ := p.qualifiedName(nil)
  1355  			p.want(_Rparen)
  1356  			tag := p.oliteral()
  1357  			p.addField(styp, pos, nil, typ, tag)
  1358  			p.syntaxError("cannot parenthesize embedded type")
  1359  		}
  1360  
  1361  	case _Star:
  1362  		p.next()
  1363  		if p.got(_Lparen) {
  1364  			// '*' '(' embed ')' oliteral
  1365  			typ := newIndirect(pos, p.qualifiedName(nil))
  1366  			p.want(_Rparen)
  1367  			tag := p.oliteral()
  1368  			p.addField(styp, pos, nil, typ, tag)
  1369  			p.syntaxError("cannot parenthesize embedded type")
  1370  
  1371  		} else {
  1372  			// '*' embed oliteral
  1373  			typ := newIndirect(pos, p.qualifiedName(nil))
  1374  			tag := p.oliteral()
  1375  			p.addField(styp, pos, nil, typ, tag)
  1376  		}
  1377  
  1378  	default:
  1379  		p.syntaxError("expecting field name or embedded type")
  1380  		p.advance(_Semi, _Rbrace)
  1381  	}
  1382  }
  1383  
  1384  func (p *parser) oliteral() *BasicLit {
  1385  	if p.tok == _Literal {
  1386  		b := new(BasicLit)
  1387  		b.pos = p.pos()
  1388  		b.Value = p.lit
  1389  		b.Kind = p.kind
  1390  		p.next()
  1391  		return b
  1392  	}
  1393  	return nil
  1394  }
  1395  
  1396  // MethodSpec        = MethodName Signature | InterfaceTypeName .
  1397  // MethodName        = identifier .
  1398  // InterfaceTypeName = TypeName .
  1399  func (p *parser) methodDecl() *Field {
  1400  	if trace {
  1401  		defer p.trace("methodDecl")()
  1402  	}
  1403  
  1404  	switch p.tok {
  1405  	case _Name:
  1406  		name := p.name()
  1407  
  1408  		// accept potential name list but complain
  1409  		hasNameList := false
  1410  		for p.got(_Comma) {
  1411  			p.name()
  1412  			hasNameList = true
  1413  		}
  1414  		if hasNameList {
  1415  			p.syntaxError("name list not allowed in interface type")
  1416  			// already progressed, no need to advance
  1417  		}
  1418  
  1419  		f := new(Field)
  1420  		f.pos = name.Pos()
  1421  		if p.tok != _Lparen {
  1422  			// packname
  1423  			f.Type = p.qualifiedName(name)
  1424  			return f
  1425  		}
  1426  
  1427  		f.Name = name
  1428  		f.Type = p.funcType()
  1429  		return f
  1430  
  1431  	case _Lparen:
  1432  		p.syntaxError("cannot parenthesize embedded type")
  1433  		f := new(Field)
  1434  		f.pos = p.pos()
  1435  		p.next()
  1436  		f.Type = p.qualifiedName(nil)
  1437  		p.want(_Rparen)
  1438  		return f
  1439  
  1440  	default:
  1441  		p.syntaxError("expecting method or interface name")
  1442  		p.advance(_Semi, _Rbrace)
  1443  		return nil
  1444  	}
  1445  }
  1446  
  1447  // ParameterDecl = [ IdentifierList ] [ "..." ] Type .
  1448  func (p *parser) paramDeclOrNil() *Field {
  1449  	if trace {
  1450  		defer p.trace("paramDecl")()
  1451  	}
  1452  
  1453  	f := new(Field)
  1454  	f.pos = p.pos()
  1455  
  1456  	switch p.tok {
  1457  	case _Name:
  1458  		f.Name = p.name()
  1459  		switch p.tok {
  1460  		case _Name, _Star, _Arrow, _Func, _Lbrack, _Chan, _Map, _Struct, _Interface, _Lparen:
  1461  			// sym name_or_type
  1462  			f.Type = p.type_()
  1463  
  1464  		case _DotDotDot:
  1465  			// sym dotdotdot
  1466  			f.Type = p.dotsType()
  1467  
  1468  		case _Dot:
  1469  			// name_or_type
  1470  			// from dotname
  1471  			f.Type = p.dotname(f.Name)
  1472  			f.Name = nil
  1473  		}
  1474  
  1475  	case _Arrow, _Star, _Func, _Lbrack, _Chan, _Map, _Struct, _Interface, _Lparen:
  1476  		// name_or_type
  1477  		f.Type = p.type_()
  1478  
  1479  	case _DotDotDot:
  1480  		// dotdotdot
  1481  		f.Type = p.dotsType()
  1482  
  1483  	default:
  1484  		p.syntaxError("expecting )")
  1485  		p.advance(_Comma, _Rparen)
  1486  		return nil
  1487  	}
  1488  
  1489  	return f
  1490  }
  1491  
  1492  // ...Type
  1493  func (p *parser) dotsType() *DotsType {
  1494  	if trace {
  1495  		defer p.trace("dotsType")()
  1496  	}
  1497  
  1498  	t := new(DotsType)
  1499  	t.pos = p.pos()
  1500  
  1501  	p.want(_DotDotDot)
  1502  	t.Elem = p.typeOrNil()
  1503  	if t.Elem == nil {
  1504  		t.Elem = p.bad()
  1505  		p.syntaxError("final argument in variadic function missing type")
  1506  	}
  1507  
  1508  	return t
  1509  }
  1510  
  1511  // Parameters    = "(" [ ParameterList [ "," ] ] ")" .
  1512  // ParameterList = ParameterDecl { "," ParameterDecl } .
  1513  func (p *parser) paramList() (list []*Field) {
  1514  	if trace {
  1515  		defer p.trace("paramList")()
  1516  	}
  1517  
  1518  	pos := p.pos()
  1519  
  1520  	var named int // number of parameters that have an explicit name and type
  1521  	p.list(_Lparen, _Comma, _Rparen, func() bool {
  1522  		if par := p.paramDeclOrNil(); par != nil {
  1523  			if debug && par.Name == nil && par.Type == nil {
  1524  				panic("parameter without name or type")
  1525  			}
  1526  			if par.Name != nil && par.Type != nil {
  1527  				named++
  1528  			}
  1529  			list = append(list, par)
  1530  		}
  1531  		return false
  1532  	})
  1533  
  1534  	// distribute parameter types
  1535  	if named == 0 {
  1536  		// all unnamed => found names are named types
  1537  		for _, par := range list {
  1538  			if typ := par.Name; typ != nil {
  1539  				par.Type = typ
  1540  				par.Name = nil
  1541  			}
  1542  		}
  1543  	} else if named != len(list) {
  1544  		// some named => all must be named
  1545  		ok := true
  1546  		var typ Expr
  1547  		for i := len(list) - 1; i >= 0; i-- {
  1548  			if par := list[i]; par.Type != nil {
  1549  				typ = par.Type
  1550  				if par.Name == nil {
  1551  					ok = false
  1552  					n := p.newName("_")
  1553  					n.pos = typ.Pos() // correct position
  1554  					par.Name = n
  1555  				}
  1556  			} else if typ != nil {
  1557  				par.Type = typ
  1558  			} else {
  1559  				// par.Type == nil && typ == nil => we only have a par.Name
  1560  				ok = false
  1561  				t := p.bad()
  1562  				t.pos = par.Name.Pos() // correct position
  1563  				par.Type = t
  1564  			}
  1565  		}
  1566  		if !ok {
  1567  			p.syntaxErrorAt(pos, "mixed named and unnamed function parameters")
  1568  		}
  1569  	}
  1570  
  1571  	return
  1572  }
  1573  
  1574  func (p *parser) bad() *BadExpr {
  1575  	b := new(BadExpr)
  1576  	b.pos = p.pos()
  1577  	return b
  1578  }
  1579  
  1580  // ----------------------------------------------------------------------------
  1581  // Statements
  1582  
  1583  // We represent x++, x-- as assignments x += ImplicitOne, x -= ImplicitOne.
  1584  // ImplicitOne should not be used elsewhere.
  1585  var ImplicitOne = &BasicLit{Value: "1"}
  1586  
  1587  // SimpleStmt = EmptyStmt | ExpressionStmt | SendStmt | IncDecStmt | Assignment | ShortVarDecl .
  1588  func (p *parser) simpleStmt(lhs Expr, keyword token) SimpleStmt {
  1589  	if trace {
  1590  		defer p.trace("simpleStmt")()
  1591  	}
  1592  
  1593  	if keyword == _For && p.tok == _Range {
  1594  		// _Range expr
  1595  		if debug && lhs != nil {
  1596  			panic("invalid call of simpleStmt")
  1597  		}
  1598  		return p.newRangeClause(nil, false)
  1599  	}
  1600  
  1601  	if lhs == nil {
  1602  		lhs = p.exprList()
  1603  	}
  1604  
  1605  	if _, ok := lhs.(*ListExpr); !ok && p.tok != _Assign && p.tok != _Define {
  1606  		// expr
  1607  		pos := p.pos()
  1608  		switch p.tok {
  1609  		case _AssignOp:
  1610  			// lhs op= rhs
  1611  			op := p.op
  1612  			p.next()
  1613  			return p.newAssignStmt(pos, op, lhs, p.expr())
  1614  
  1615  		case _IncOp:
  1616  			// lhs++ or lhs--
  1617  			op := p.op
  1618  			p.next()
  1619  			return p.newAssignStmt(pos, op, lhs, ImplicitOne)
  1620  
  1621  		case _Arrow:
  1622  			// lhs <- rhs
  1623  			s := new(SendStmt)
  1624  			s.pos = pos
  1625  			p.next()
  1626  			s.Chan = lhs
  1627  			s.Value = p.expr()
  1628  			return s
  1629  
  1630  		default:
  1631  			// expr
  1632  			s := new(ExprStmt)
  1633  			s.pos = lhs.Pos()
  1634  			s.X = lhs
  1635  			return s
  1636  		}
  1637  	}
  1638  
  1639  	// expr_list
  1640  	switch p.tok {
  1641  	case _Assign, _Define:
  1642  		pos := p.pos()
  1643  		var op Operator
  1644  		if p.tok == _Define {
  1645  			op = Def
  1646  		}
  1647  		p.next()
  1648  
  1649  		if keyword == _For && p.tok == _Range {
  1650  			// expr_list op= _Range expr
  1651  			return p.newRangeClause(lhs, op == Def)
  1652  		}
  1653  
  1654  		// expr_list op= expr_list
  1655  		rhs := p.exprList()
  1656  
  1657  		if x, ok := rhs.(*TypeSwitchGuard); ok && keyword == _Switch && op == Def {
  1658  			if lhs, ok := lhs.(*Name); ok {
  1659  				// switch … lhs := rhs.(type)
  1660  				x.Lhs = lhs
  1661  				s := new(ExprStmt)
  1662  				s.pos = x.Pos()
  1663  				s.X = x
  1664  				return s
  1665  			}
  1666  		}
  1667  
  1668  		return p.newAssignStmt(pos, op, lhs, rhs)
  1669  
  1670  	default:
  1671  		p.syntaxError("expecting := or = or comma")
  1672  		p.advance(_Semi, _Rbrace)
  1673  		// make the best of what we have
  1674  		if x, ok := lhs.(*ListExpr); ok {
  1675  			lhs = x.ElemList[0]
  1676  		}
  1677  		s := new(ExprStmt)
  1678  		s.pos = lhs.Pos()
  1679  		s.X = lhs
  1680  		return s
  1681  	}
  1682  }
  1683  
  1684  func (p *parser) newRangeClause(lhs Expr, def bool) *RangeClause {
  1685  	r := new(RangeClause)
  1686  	r.pos = p.pos()
  1687  	p.next() // consume _Range
  1688  	r.Lhs = lhs
  1689  	r.Def = def
  1690  	r.X = p.expr()
  1691  	return r
  1692  }
  1693  
  1694  func (p *parser) newAssignStmt(pos Pos, op Operator, lhs, rhs Expr) *AssignStmt {
  1695  	a := new(AssignStmt)
  1696  	a.pos = pos
  1697  	a.Op = op
  1698  	a.Lhs = lhs
  1699  	a.Rhs = rhs
  1700  	return a
  1701  }
  1702  
  1703  func (p *parser) labeledStmtOrNil(label *Name) Stmt {
  1704  	if trace {
  1705  		defer p.trace("labeledStmt")()
  1706  	}
  1707  
  1708  	s := new(LabeledStmt)
  1709  	s.pos = p.pos()
  1710  	s.Label = label
  1711  
  1712  	p.want(_Colon)
  1713  
  1714  	if p.tok == _Rbrace {
  1715  		// We expect a statement (incl. an empty statement), which must be
  1716  		// terminated by a semicolon. Because semicolons may be omitted before
  1717  		// an _Rbrace, seeing an _Rbrace implies an empty statement.
  1718  		e := new(EmptyStmt)
  1719  		e.pos = p.pos()
  1720  		s.Stmt = e
  1721  		return s
  1722  	}
  1723  
  1724  	s.Stmt = p.stmtOrNil()
  1725  	if s.Stmt != nil {
  1726  		return s
  1727  	}
  1728  
  1729  	// report error at line of ':' token
  1730  	p.syntaxErrorAt(s.pos, "missing statement after label")
  1731  	// we are already at the end of the labeled statement - no need to advance
  1732  	return nil // avoids follow-on errors (see e.g., fixedbugs/bug274.go)
  1733  }
  1734  
  1735  // context must be a non-empty string unless we know that p.tok == _Lbrace.
  1736  func (p *parser) blockStmt(context string) *BlockStmt {
  1737  	if trace {
  1738  		defer p.trace("blockStmt")()
  1739  	}
  1740  
  1741  	s := new(BlockStmt)
  1742  	s.pos = p.pos()
  1743  
  1744  	// people coming from C may forget that braces are mandatory in Go
  1745  	if !p.got(_Lbrace) {
  1746  		p.syntaxError("expecting { after " + context)
  1747  		p.advance(_Name, _Rbrace)
  1748  		s.Rbrace = p.pos() // in case we found "}"
  1749  		if p.got(_Rbrace) {
  1750  			return s
  1751  		}
  1752  	}
  1753  
  1754  	s.List = p.stmtList()
  1755  	s.Rbrace = p.pos()
  1756  	p.want(_Rbrace)
  1757  
  1758  	return s
  1759  }
  1760  
  1761  func (p *parser) declStmt(f func(*Group) Decl) *DeclStmt {
  1762  	if trace {
  1763  		defer p.trace("declStmt")()
  1764  	}
  1765  
  1766  	s := new(DeclStmt)
  1767  	s.pos = p.pos()
  1768  
  1769  	p.next() // _Const, _Type, or _Var
  1770  	s.DeclList = p.appendGroup(nil, f)
  1771  
  1772  	return s
  1773  }
  1774  
  1775  func (p *parser) forStmt() Stmt {
  1776  	if trace {
  1777  		defer p.trace("forStmt")()
  1778  	}
  1779  
  1780  	s := new(ForStmt)
  1781  	s.pos = p.pos()
  1782  
  1783  	s.Init, s.Cond, s.Post = p.header(_For)
  1784  	s.Body = p.blockStmt("for clause")
  1785  
  1786  	return s
  1787  }
  1788  
  1789  func (p *parser) header(keyword token) (init SimpleStmt, cond Expr, post SimpleStmt) {
  1790  	p.want(keyword)
  1791  
  1792  	if p.tok == _Lbrace {
  1793  		if keyword == _If {
  1794  			p.syntaxError("missing condition in if statement")
  1795  		}
  1796  		return
  1797  	}
  1798  	// p.tok != _Lbrace
  1799  
  1800  	outer := p.xnest
  1801  	p.xnest = -1
  1802  
  1803  	if p.tok != _Semi {
  1804  		// accept potential varDecl but complain
  1805  		if p.got(_Var) {
  1806  			p.syntaxError(fmt.Sprintf("var declaration not allowed in %s initializer", keyword.String()))
  1807  		}
  1808  		init = p.simpleStmt(nil, keyword)
  1809  		// If we have a range clause, we are done (can only happen for keyword == _For).
  1810  		if _, ok := init.(*RangeClause); ok {
  1811  			p.xnest = outer
  1812  			return
  1813  		}
  1814  	}
  1815  
  1816  	var condStmt SimpleStmt
  1817  	var semi struct {
  1818  		pos Pos
  1819  		lit string // valid if pos.IsKnown()
  1820  	}
  1821  	if p.tok != _Lbrace {
  1822  		if p.tok == _Semi {
  1823  			semi.pos = p.pos()
  1824  			semi.lit = p.lit
  1825  			p.next()
  1826  		} else {
  1827  			// asking for a '{' rather than a ';' here leads to a better error message
  1828  			p.want(_Lbrace)
  1829  		}
  1830  		if keyword == _For {
  1831  			if p.tok != _Semi {
  1832  				if p.tok == _Lbrace {
  1833  					p.syntaxError("expecting for loop condition")
  1834  					goto done
  1835  				}
  1836  				condStmt = p.simpleStmt(nil, 0 /* range not permitted */)
  1837  			}
  1838  			p.want(_Semi)
  1839  			if p.tok != _Lbrace {
  1840  				post = p.simpleStmt(nil, 0 /* range not permitted */)
  1841  				if a, _ := post.(*AssignStmt); a != nil && a.Op == Def {
  1842  					p.syntaxErrorAt(a.Pos(), "cannot declare in post statement of for loop")
  1843  				}
  1844  			}
  1845  		} else if p.tok != _Lbrace {
  1846  			condStmt = p.simpleStmt(nil, keyword)
  1847  		}
  1848  	} else {
  1849  		condStmt = init
  1850  		init = nil
  1851  	}
  1852  
  1853  done:
  1854  	// unpack condStmt
  1855  	switch s := condStmt.(type) {
  1856  	case nil:
  1857  		if keyword == _If && semi.pos.IsKnown() {
  1858  			if semi.lit != "semicolon" {
  1859  				p.syntaxErrorAt(semi.pos, fmt.Sprintf("unexpected %s, expecting { after if clause", semi.lit))
  1860  			} else {
  1861  				p.syntaxErrorAt(semi.pos, "missing condition in if statement")
  1862  			}
  1863  		}
  1864  	case *ExprStmt:
  1865  		cond = s.X
  1866  	default:
  1867  		// A common syntax error is to write '=' instead of '==',
  1868  		// which turns an expression into an assignment. Provide
  1869  		// a more explicit error message in that case to prevent
  1870  		// further confusion.
  1871  		str := String(s)
  1872  		if as, ok := s.(*AssignStmt); ok && as.Op == 0 {
  1873  			str = "assignment " + str
  1874  		}
  1875  		p.syntaxError(fmt.Sprintf("%s used as value", str))
  1876  	}
  1877  
  1878  	p.xnest = outer
  1879  	return
  1880  }
  1881  
  1882  func (p *parser) ifStmt() *IfStmt {
  1883  	if trace {
  1884  		defer p.trace("ifStmt")()
  1885  	}
  1886  
  1887  	s := new(IfStmt)
  1888  	s.pos = p.pos()
  1889  
  1890  	s.Init, s.Cond, _ = p.header(_If)
  1891  	s.Then = p.blockStmt("if clause")
  1892  
  1893  	if p.got(_Else) {
  1894  		switch p.tok {
  1895  		case _If:
  1896  			s.Else = p.ifStmt()
  1897  		case _Lbrace:
  1898  			s.Else = p.blockStmt("")
  1899  		default:
  1900  			p.syntaxError("else must be followed by if or statement block")
  1901  			p.advance(_Name, _Rbrace)
  1902  		}
  1903  	}
  1904  
  1905  	return s
  1906  }
  1907  
  1908  func (p *parser) switchStmt() *SwitchStmt {
  1909  	if trace {
  1910  		defer p.trace("switchStmt")()
  1911  	}
  1912  
  1913  	s := new(SwitchStmt)
  1914  	s.pos = p.pos()
  1915  
  1916  	s.Init, s.Tag, _ = p.header(_Switch)
  1917  
  1918  	if !p.got(_Lbrace) {
  1919  		p.syntaxError("missing { after switch clause")
  1920  		p.advance(_Case, _Default, _Rbrace)
  1921  	}
  1922  	for p.tok != _EOF && p.tok != _Rbrace {
  1923  		s.Body = append(s.Body, p.caseClause())
  1924  	}
  1925  	s.Rbrace = p.pos()
  1926  	p.want(_Rbrace)
  1927  
  1928  	return s
  1929  }
  1930  
  1931  func (p *parser) selectStmt() *SelectStmt {
  1932  	if trace {
  1933  		defer p.trace("selectStmt")()
  1934  	}
  1935  
  1936  	s := new(SelectStmt)
  1937  	s.pos = p.pos()
  1938  
  1939  	p.want(_Select)
  1940  	if !p.got(_Lbrace) {
  1941  		p.syntaxError("missing { after select clause")
  1942  		p.advance(_Case, _Default, _Rbrace)
  1943  	}
  1944  	for p.tok != _EOF && p.tok != _Rbrace {
  1945  		s.Body = append(s.Body, p.commClause())
  1946  	}
  1947  	s.Rbrace = p.pos()
  1948  	p.want(_Rbrace)
  1949  
  1950  	return s
  1951  }
  1952  
  1953  func (p *parser) caseClause() *CaseClause {
  1954  	if trace {
  1955  		defer p.trace("caseClause")()
  1956  	}
  1957  
  1958  	c := new(CaseClause)
  1959  	c.pos = p.pos()
  1960  
  1961  	switch p.tok {
  1962  	case _Case:
  1963  		p.next()
  1964  		c.Cases = p.exprList()
  1965  
  1966  	case _Default:
  1967  		p.next()
  1968  
  1969  	default:
  1970  		p.syntaxError("expecting case or default or }")
  1971  		p.advance(_Colon, _Case, _Default, _Rbrace)
  1972  	}
  1973  
  1974  	c.Colon = p.pos()
  1975  	p.want(_Colon)
  1976  	c.Body = p.stmtList()
  1977  
  1978  	return c
  1979  }
  1980  
  1981  func (p *parser) commClause() *CommClause {
  1982  	if trace {
  1983  		defer p.trace("commClause")()
  1984  	}
  1985  
  1986  	c := new(CommClause)
  1987  	c.pos = p.pos()
  1988  
  1989  	switch p.tok {
  1990  	case _Case:
  1991  		p.next()
  1992  		c.Comm = p.simpleStmt(nil, 0)
  1993  
  1994  		// The syntax restricts the possible simple statements here to:
  1995  		//
  1996  		//     lhs <- x (send statement)
  1997  		//     <-x
  1998  		//     lhs = <-x
  1999  		//     lhs := <-x
  2000  		//
  2001  		// All these (and more) are recognized by simpleStmt and invalid
  2002  		// syntax trees are flagged later, during type checking.
  2003  		// TODO(gri) eventually may want to restrict valid syntax trees
  2004  		// here.
  2005  
  2006  	case _Default:
  2007  		p.next()
  2008  
  2009  	default:
  2010  		p.syntaxError("expecting case or default or }")
  2011  		p.advance(_Colon, _Case, _Default, _Rbrace)
  2012  	}
  2013  
  2014  	c.Colon = p.pos()
  2015  	p.want(_Colon)
  2016  	c.Body = p.stmtList()
  2017  
  2018  	return c
  2019  }
  2020  
  2021  // Statement =
  2022  // 	Declaration | LabeledStmt | SimpleStmt |
  2023  // 	GoStmt | ReturnStmt | BreakStmt | ContinueStmt | GotoStmt |
  2024  // 	FallthroughStmt | Block | IfStmt | SwitchStmt | SelectStmt | ForStmt |
  2025  // 	DeferStmt .
  2026  func (p *parser) stmtOrNil() Stmt {
  2027  	if trace {
  2028  		defer p.trace("stmt " + p.tok.String())()
  2029  	}
  2030  
  2031  	// Most statements (assignments) start with an identifier;
  2032  	// look for it first before doing anything more expensive.
  2033  	if p.tok == _Name {
  2034  		lhs := p.exprList()
  2035  		if label, ok := lhs.(*Name); ok && p.tok == _Colon {
  2036  			return p.labeledStmtOrNil(label)
  2037  		}
  2038  		return p.simpleStmt(lhs, 0)
  2039  	}
  2040  
  2041  	switch p.tok {
  2042  	case _Lbrace:
  2043  		return p.blockStmt("")
  2044  
  2045  	case _Var:
  2046  		return p.declStmt(p.varDecl)
  2047  
  2048  	case _Const:
  2049  		return p.declStmt(p.constDecl)
  2050  
  2051  	case _Type:
  2052  		return p.declStmt(p.typeDecl)
  2053  
  2054  	case _Operator, _Star:
  2055  		switch p.op {
  2056  		case Add, Sub, Mul, And, Xor, Not:
  2057  			return p.simpleStmt(nil, 0) // unary operators
  2058  		}
  2059  
  2060  	case _Literal, _Func, _Lparen, // operands
  2061  		_Lbrack, _Struct, _Map, _Chan, _Interface, // composite types
  2062  		_Arrow: // receive operator
  2063  		return p.simpleStmt(nil, 0)
  2064  
  2065  	case _For:
  2066  		return p.forStmt()
  2067  
  2068  	case _Switch:
  2069  		return p.switchStmt()
  2070  
  2071  	case _Select:
  2072  		return p.selectStmt()
  2073  
  2074  	case _If:
  2075  		return p.ifStmt()
  2076  
  2077  	case _Fallthrough:
  2078  		s := new(BranchStmt)
  2079  		s.pos = p.pos()
  2080  		p.next()
  2081  		s.Tok = _Fallthrough
  2082  		return s
  2083  
  2084  	case _Break, _Continue:
  2085  		s := new(BranchStmt)
  2086  		s.pos = p.pos()
  2087  		s.Tok = p.tok
  2088  		p.next()
  2089  		if p.tok == _Name {
  2090  			s.Label = p.name()
  2091  		}
  2092  		return s
  2093  
  2094  	case _Go, _Defer:
  2095  		return p.callStmt()
  2096  
  2097  	case _Goto:
  2098  		s := new(BranchStmt)
  2099  		s.pos = p.pos()
  2100  		s.Tok = _Goto
  2101  		p.next()
  2102  		s.Label = p.name()
  2103  		return s
  2104  
  2105  	case _Return:
  2106  		s := new(ReturnStmt)
  2107  		s.pos = p.pos()
  2108  		p.next()
  2109  		if p.tok != _Semi && p.tok != _Rbrace {
  2110  			s.Results = p.exprList()
  2111  		}
  2112  		return s
  2113  
  2114  	case _Semi:
  2115  		s := new(EmptyStmt)
  2116  		s.pos = p.pos()
  2117  		return s
  2118  	}
  2119  
  2120  	return nil
  2121  }
  2122  
  2123  // StatementList = { Statement ";" } .
  2124  func (p *parser) stmtList() (l []Stmt) {
  2125  	if trace {
  2126  		defer p.trace("stmtList")()
  2127  	}
  2128  
  2129  	for p.tok != _EOF && p.tok != _Rbrace && p.tok != _Case && p.tok != _Default {
  2130  		s := p.stmtOrNil()
  2131  		if s == nil {
  2132  			break
  2133  		}
  2134  		l = append(l, s)
  2135  		// ";" is optional before "}"
  2136  		if !p.got(_Semi) && p.tok != _Rbrace {
  2137  			p.syntaxError("at end of statement")
  2138  			p.advance(_Semi, _Rbrace, _Case, _Default)
  2139  			p.got(_Semi) // avoid spurious empty statement
  2140  		}
  2141  	}
  2142  	return
  2143  }
  2144  
  2145  // Arguments = "(" [ ( ExpressionList | Type [ "," ExpressionList ] ) [ "..." ] [ "," ] ] ")" .
  2146  func (p *parser) argList() (list []Expr, hasDots bool) {
  2147  	if trace {
  2148  		defer p.trace("argList")()
  2149  	}
  2150  
  2151  	p.xnest++
  2152  	p.list(_Lparen, _Comma, _Rparen, func() bool {
  2153  		list = append(list, p.expr())
  2154  		hasDots = p.got(_DotDotDot)
  2155  		return hasDots
  2156  	})
  2157  	p.xnest--
  2158  
  2159  	return
  2160  }
  2161  
  2162  // ----------------------------------------------------------------------------
  2163  // Common productions
  2164  
  2165  func (p *parser) newName(value string) *Name {
  2166  	n := new(Name)
  2167  	n.pos = p.pos()
  2168  	n.Value = value
  2169  	return n
  2170  }
  2171  
  2172  func (p *parser) name() *Name {
  2173  	// no tracing to avoid overly verbose output
  2174  
  2175  	if p.tok == _Name {
  2176  		n := p.newName(p.lit)
  2177  		p.next()
  2178  		return n
  2179  	}
  2180  
  2181  	n := p.newName("_")
  2182  	p.syntaxError("expecting name")
  2183  	p.advance()
  2184  	return n
  2185  }
  2186  
  2187  // IdentifierList = identifier { "," identifier } .
  2188  // The first name must be provided.
  2189  func (p *parser) nameList(first *Name) []*Name {
  2190  	if trace {
  2191  		defer p.trace("nameList")()
  2192  	}
  2193  
  2194  	if debug && first == nil {
  2195  		panic("first name not provided")
  2196  	}
  2197  
  2198  	l := []*Name{first}
  2199  	for p.got(_Comma) {
  2200  		l = append(l, p.name())
  2201  	}
  2202  
  2203  	return l
  2204  }
  2205  
  2206  // The first name may be provided, or nil.
  2207  func (p *parser) qualifiedName(name *Name) Expr {
  2208  	if trace {
  2209  		defer p.trace("qualifiedName")()
  2210  	}
  2211  
  2212  	switch {
  2213  	case name != nil:
  2214  		// name is provided
  2215  	case p.tok == _Name:
  2216  		name = p.name()
  2217  	default:
  2218  		name = p.newName("_")
  2219  		p.syntaxError("expecting name")
  2220  		p.advance(_Dot, _Semi, _Rbrace)
  2221  	}
  2222  
  2223  	return p.dotname(name)
  2224  }
  2225  
  2226  // ExpressionList = Expression { "," Expression } .
  2227  func (p *parser) exprList() Expr {
  2228  	if trace {
  2229  		defer p.trace("exprList")()
  2230  	}
  2231  
  2232  	x := p.expr()
  2233  	if p.got(_Comma) {
  2234  		list := []Expr{x, p.expr()}
  2235  		for p.got(_Comma) {
  2236  			list = append(list, p.expr())
  2237  		}
  2238  		t := new(ListExpr)
  2239  		t.pos = x.Pos()
  2240  		t.ElemList = list
  2241  		x = t
  2242  	}
  2243  	return x
  2244  }
  2245  
  2246  // unparen removes all parentheses around an expression.
  2247  func unparen(x Expr) Expr {
  2248  	for {
  2249  		p, ok := x.(*ParenExpr)
  2250  		if !ok {
  2251  			break
  2252  		}
  2253  		x = p.X
  2254  	}
  2255  	return x
  2256  }