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