Black Lives Matter. Support the Equal Justice Initiative.

Source file src/cmd/compile/internal/syntax/parser.go

Documentation: cmd/compile/internal/syntax

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

View as plain text