parser.mx raw

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