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