github.com/epfl-dcsl/gotee@v0.0.0-20200909122901-014b35f5e5e9/src/cmd/compile/internal/syntax/parser.go (about)

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