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