github.com/bir3/gocompiler@v0.3.205/src/cmd/compile/internal/syntax/parser.go (about)

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