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