github.com/sanprasirt/go@v0.0.0-20170607001320-a027466e4b6d/src/cmd/compile/internal/syntax/parser.go (about)

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