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