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

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

View as plain text