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