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 | [ TypeName ] 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 _Lbrace:
  1023  		return p.compositeLit()
  1024  
  1025  	case _Lparen:
  1026  		pos := p.pos()
  1027  		p.next()
  1028  		p.xnest++
  1029  		x := p.expr()
  1030  		p.xnest--
  1031  		p.want(_Rparen)
  1032  
  1033  		// Optimization: Record presence of ()'s only where needed
  1034  		// for error reporting. Don't bother in other cases; it is
  1035  		// just a waste of memory and time.
  1036  		//
  1037  		// Parentheses are not permitted around T in a composite
  1038  		// literal T{}. If the next token is a {, assume x is a
  1039  		// composite literal type T (it may not be, { could be
  1040  		// the opening brace of a block, but we don't know yet).
  1041  		if p.tok == _Lbrace {
  1042  			keep_parens = true
  1043  		}
  1044  
  1045  		// Parentheses are also not permitted around the expression
  1046  		// in a go/defer statement. In that case, operand is called
  1047  		// with keep_parens set.
  1048  		if keep_parens {
  1049  			px := new(ParenExpr)
  1050  			px.pos = pos
  1051  			px.X = x
  1052  			x = px
  1053  		}
  1054  		return x
  1055  
  1056  	case _Func:
  1057  		pos := p.pos()
  1058  		p.next()
  1059  		_, ftyp := p.funcType("function type")
  1060  		if p.tok == _Lbrace {
  1061  			p.xnest++
  1062  
  1063  			f := new(FuncLit)
  1064  			f.pos = pos
  1065  			f.Type = ftyp
  1066  			f.Body = p.funcBody()
  1067  
  1068  			p.xnest--
  1069  			return f
  1070  		}
  1071  		return ftyp
  1072  
  1073  	case _Lbrack, _Chan, _Map, _Struct, _Interface:
  1074  		return p.type_()
  1075  
  1076  	default:
  1077  		x := p.badExpr()
  1078  		p.syntaxError("expected expression")
  1079  		p.advance(_Rparen, _Rbrack, _Rbrace)
  1080  		return x
  1081  	}
  1082  
  1083  	// Syntactically, composite literals are operands. Because a complit
  1084  	// type may be a qualified identifier which is handled by pexpr
  1085  	// (together with selector expressions), complits are parsed there
  1086  	// as well (operand is only called from pexpr).
  1087  }
  1088  
  1089  // pexpr parses a PrimaryExpr.
  1090  //
  1091  //	PrimaryExpr =
  1092  //		Operand |
  1093  //		Conversion |
  1094  //		PrimaryExpr Selector |
  1095  //		PrimaryExpr Index |
  1096  //		PrimaryExpr Slice |
  1097  //		PrimaryExpr TypeAssertion |
  1098  //		PrimaryExpr Arguments .
  1099  //
  1100  //	Selector       = "." identifier .
  1101  //	Index          = "[" Expression "]" .
  1102  //	Slice          = "[" ( [ Expression ] ":" [ Expression ] ) |
  1103  //	                     ( [ Expression ] ":" Expression ":" Expression )
  1104  //	                 "]" .
  1105  //	TypeAssertion  = "." "(" Type ")" .
  1106  //	Arguments      = "(" [ ( ExpressionList | Type [ "," ExpressionList ] ) [ "..." ] [ "," ] ] ")" .
  1107  func (p *parser) pexpr(x Expr, keep_parens bool) Expr {
  1108  	if trace {
  1109  		defer p.trace("pexpr")()
  1110  	}
  1111  
  1112  	if x == nil {
  1113  		x = p.operand(keep_parens)
  1114  	}
  1115  
  1116  loop:
  1117  	for {
  1118  		pos := p.pos()
  1119  		switch p.tok {
  1120  		case _Dot:
  1121  			p.next()
  1122  			switch p.tok {
  1123  			case _Name:
  1124  				// pexpr '.' sym
  1125  				t := new(SelectorExpr)
  1126  				t.pos = pos
  1127  				t.X = x
  1128  				t.Sel = p.name()
  1129  				x = t
  1130  
  1131  			case _Lparen:
  1132  				p.next()
  1133  				if p.got(_Type) {
  1134  					t := new(TypeSwitchGuard)
  1135  					// t.Lhs is filled in by parser.simpleStmt
  1136  					t.pos = pos
  1137  					t.X = x
  1138  					x = t
  1139  				} else {
  1140  					t := new(AssertExpr)
  1141  					t.pos = pos
  1142  					t.X = x
  1143  					t.Type = p.type_()
  1144  					x = t
  1145  				}
  1146  				p.want(_Rparen)
  1147  
  1148  			default:
  1149  				p.syntaxError("expected name or (")
  1150  				p.advance(_Semi, _Rparen)
  1151  			}
  1152  
  1153  		case _Lbrack:
  1154  			p.next()
  1155  
  1156  			var i Expr
  1157  			if p.tok != _Colon {
  1158  				var comma bool
  1159  				if p.tok == _Rbrack {
  1160  					// invalid empty instance, slice or index expression; accept but complain
  1161  					p.syntaxError("expected operand")
  1162  					i = p.badExpr()
  1163  				} else {
  1164  					i, comma = p.typeList(false)
  1165  				}
  1166  				if comma || p.tok == _Rbrack {
  1167  					p.want(_Rbrack)
  1168  					// x[], x[i,] or x[i, j, ...]
  1169  					t := new(IndexExpr)
  1170  					t.pos = pos
  1171  					t.X = x
  1172  					t.Index = i
  1173  					x = t
  1174  					break
  1175  				}
  1176  			}
  1177  
  1178  			// x[i:...
  1179  			// For better error message, don't simply use p.want(_Colon) here (go.dev/issue/47704).
  1180  			if !p.got(_Colon) {
  1181  				p.syntaxError("expected comma, : or ]")
  1182  				p.advance(_Comma, _Colon, _Rbrack)
  1183  			}
  1184  			p.xnest++
  1185  			t := new(SliceExpr)
  1186  			t.pos = pos
  1187  			t.X = x
  1188  			t.Index[0] = i
  1189  			if p.tok != _Colon && p.tok != _Rbrack {
  1190  				// x[i:j...
  1191  				t.Index[1] = p.expr()
  1192  			}
  1193  			if p.tok == _Colon {
  1194  				t.Full = true
  1195  				// x[i:j:...]
  1196  				if t.Index[1] == nil {
  1197  					p.error("middle index required in 3-index slice")
  1198  					t.Index[1] = p.badExpr()
  1199  				}
  1200  				p.next()
  1201  				if p.tok != _Rbrack {
  1202  					// x[i:j:k...
  1203  					t.Index[2] = p.expr()
  1204  				} else {
  1205  					p.error("final index required in 3-index slice")
  1206  					t.Index[2] = p.badExpr()
  1207  				}
  1208  			}
  1209  			p.xnest--
  1210  			p.want(_Rbrack)
  1211  			x = t
  1212  
  1213  		case _Lparen:
  1214  			t := new(CallExpr)
  1215  			t.pos = pos
  1216  			p.next()
  1217  			t.Fun = x
  1218  			t.ArgList, t.HasDots = p.argList()
  1219  			x = t
  1220  
  1221  		case _Lbrace:
  1222  			// operand may have returned a parenthesized complit
  1223  			// type; accept it but complain if we have a complit
  1224  			t := Unparen(x)
  1225  			// determine if '{' belongs to a composite literal or a block statement
  1226  			complit_ok := false
  1227  			switch t.(type) {
  1228  			case *Name, *SelectorExpr:
  1229  				if p.xnest >= 0 {
  1230  					// x is possibly a composite literal type
  1231  					complit_ok = true
  1232  				}
  1233  			case *IndexExpr:
  1234  				if p.xnest >= 0 && !isValue(t) {
  1235  					// x is possibly a composite literal type
  1236  					complit_ok = true
  1237  				}
  1238  			case *ArrayType, *SliceType, *StructType, *MapType:
  1239  				// x is a comptype
  1240  				complit_ok = true
  1241  			}
  1242  			if !complit_ok {
  1243  				break loop
  1244  			}
  1245  			if t != x {
  1246  				p.syntaxError("cannot parenthesize type in composite literal")
  1247  				// already progressed, no need to advance
  1248  			}
  1249  			n := p.compositeLit()
  1250  			n.Type = x
  1251  			x = n
  1252  
  1253  		default:
  1254  			break loop
  1255  		}
  1256  	}
  1257  
  1258  	return x
  1259  }
  1260  
  1261  // isValue reports whether x syntactically must be a value (and not a type) expression.
  1262  func isValue(x Expr) bool {
  1263  	switch x := x.(type) {
  1264  	case *BasicLit, *CompositeLit, *FuncLit, *SliceExpr, *AssertExpr, *TypeSwitchGuard, *CallExpr:
  1265  		return true
  1266  	case *Operation:
  1267  		return x.Op != Mul || x.Y != nil // *T may be a type
  1268  	case *ParenExpr:
  1269  		return isValue(x.X)
  1270  	case *IndexExpr:
  1271  		return isValue(x.X) || isValue(x.Index)
  1272  	}
  1273  	return false
  1274  }
  1275  
  1276  // LiteralValue = "{" [ ElementList [ "," ] ] "}" .
  1277  func (p *parser) compositeLit() *CompositeLit {
  1278  	if trace {
  1279  		defer p.trace("compositeLit")()
  1280  	}
  1281  
  1282  	x := new(CompositeLit)
  1283  	x.pos = p.pos()
  1284  
  1285  	p.xnest++
  1286  	p.want(_Lbrace)
  1287  	x.Rbrace = p.list("composite literal", _Comma, _Rbrace, func() bool {
  1288  		// value
  1289  		e := p.expr()
  1290  		if p.tok == _Colon {
  1291  			// key ':' value
  1292  			l := new(KeyValueExpr)
  1293  			l.pos = p.pos()
  1294  			p.next()
  1295  			l.Key = e
  1296  			l.Value = p.expr()
  1297  			e = l
  1298  			x.NKeys++
  1299  		}
  1300  		x.ElemList = append(x.ElemList, e)
  1301  		return false
  1302  	})
  1303  	p.xnest--
  1304  
  1305  	return x
  1306  }
  1307  
  1308  // ----------------------------------------------------------------------------
  1309  // Types
  1310  
  1311  func (p *parser) type_() Expr {
  1312  	if trace {
  1313  		defer p.trace("type_")()
  1314  	}
  1315  
  1316  	typ := p.typeOrNil()
  1317  	if typ == nil {
  1318  		typ = p.badExpr()
  1319  		p.syntaxError("expected type")
  1320  		p.advance(_Comma, _Colon, _Semi, _Rparen, _Rbrack, _Rbrace)
  1321  	}
  1322  
  1323  	return typ
  1324  }
  1325  
  1326  func newIndirect(pos Pos, typ Expr) Expr {
  1327  	o := new(Operation)
  1328  	o.pos = pos
  1329  	o.Op = Mul
  1330  	o.X = typ
  1331  	return o
  1332  }
  1333  
  1334  // typeOrNil is like type_ but it returns nil if there was no type
  1335  // instead of reporting an error.
  1336  //
  1337  //	Type     = TypeName | TypeLit | "(" Type ")" .
  1338  //	TypeName = identifier | QualifiedIdent .
  1339  //	TypeLit  = ArrayType | StructType | PointerType | FunctionType | InterfaceType |
  1340  //		      SliceType | MapType | Channel_Type .
  1341  func (p *parser) typeOrNil() Expr {
  1342  	if trace {
  1343  		defer p.trace("typeOrNil")()
  1344  	}
  1345  
  1346  	pos := p.pos()
  1347  	switch p.tok {
  1348  	case _Star:
  1349  		// ptrtype
  1350  		p.next()
  1351  		return newIndirect(pos, p.type_())
  1352  
  1353  	case _Arrow:
  1354  		// recvchantype
  1355  		p.next()
  1356  		p.want(_Chan)
  1357  		t := new(ChanType)
  1358  		t.pos = pos
  1359  		t.Dir = RecvOnly
  1360  		t.Elem = p.chanElem()
  1361  		return t
  1362  
  1363  	case _Func:
  1364  		// fntype
  1365  		p.next()
  1366  		_, t := p.funcType("function type")
  1367  		return t
  1368  
  1369  	case _Lbrack:
  1370  		// '[' oexpr ']' ntype
  1371  		// '[' _DotDotDot ']' ntype
  1372  		p.next()
  1373  		if p.got(_Rbrack) {
  1374  			return p.sliceType(pos)
  1375  		}
  1376  		return p.arrayType(pos, nil)
  1377  
  1378  	case _Chan:
  1379  		// _Chan non_recvchantype
  1380  		// _Chan _Comm ntype
  1381  		p.next()
  1382  		t := new(ChanType)
  1383  		t.pos = pos
  1384  		if p.got(_Arrow) {
  1385  			t.Dir = SendOnly
  1386  		}
  1387  		t.Elem = p.chanElem()
  1388  		return t
  1389  
  1390  	case _Map:
  1391  		// _Map '[' ntype ']' ntype
  1392  		p.next()
  1393  		p.want(_Lbrack)
  1394  		t := new(MapType)
  1395  		t.pos = pos
  1396  		t.Key = p.type_()
  1397  		p.want(_Rbrack)
  1398  		t.Value = p.type_()
  1399  		return t
  1400  
  1401  	case _Struct:
  1402  		return p.structType()
  1403  
  1404  	case _Interface:
  1405  		return p.interfaceType()
  1406  
  1407  	case _Name:
  1408  		return p.qualifiedName(nil)
  1409  
  1410  	case _Lparen:
  1411  		p.next()
  1412  		t := p.type_()
  1413  		p.want(_Rparen)
  1414  		// The parser doesn't keep unnecessary parentheses.
  1415  		// Set the flag below to keep them, for testing
  1416  		// (see e.g. tests for go.dev/issue/68639).
  1417  		const keep_parens = false
  1418  		if keep_parens {
  1419  			px := new(ParenExpr)
  1420  			px.pos = pos
  1421  			px.X = t
  1422  			t = px
  1423  		}
  1424  		return t
  1425  	}
  1426  
  1427  	return nil
  1428  }
  1429  
  1430  func (p *parser) typeInstance(typ Expr) Expr {
  1431  	if trace {
  1432  		defer p.trace("typeInstance")()
  1433  	}
  1434  
  1435  	pos := p.pos()
  1436  	p.want(_Lbrack)
  1437  	x := new(IndexExpr)
  1438  	x.pos = pos
  1439  	x.X = typ
  1440  	if p.tok == _Rbrack {
  1441  		p.syntaxError("expected type argument list")
  1442  		x.Index = p.badExpr()
  1443  	} else {
  1444  		x.Index, _ = p.typeList(true)
  1445  	}
  1446  	p.want(_Rbrack)
  1447  	return x
  1448  }
  1449  
  1450  // If context != "", type parameters are not permitted.
  1451  func (p *parser) funcType(context string) ([]*Field, *FuncType) {
  1452  	if trace {
  1453  		defer p.trace("funcType")()
  1454  	}
  1455  
  1456  	typ := new(FuncType)
  1457  	typ.pos = p.pos()
  1458  
  1459  	var tparamList []*Field
  1460  	if p.got(_Lbrack) {
  1461  		if context != "" {
  1462  			// accept but complain
  1463  			p.syntaxErrorAt(typ.pos, context+" must have no type parameters")
  1464  		}
  1465  		if p.tok == _Rbrack {
  1466  			p.syntaxError("empty type parameter list")
  1467  			p.next()
  1468  		} else {
  1469  			tparamList = p.paramList(nil, nil, _Rbrack, true, false)
  1470  		}
  1471  	}
  1472  
  1473  	p.want(_Lparen)
  1474  	typ.ParamList = p.paramList(nil, nil, _Rparen, false, true)
  1475  	typ.ResultList = p.funcResult()
  1476  
  1477  	return tparamList, typ
  1478  }
  1479  
  1480  // "[" has already been consumed, and pos is its position.
  1481  // If len != nil it is the already consumed array length.
  1482  func (p *parser) arrayType(pos Pos, len Expr) Expr {
  1483  	if trace {
  1484  		defer p.trace("arrayType")()
  1485  	}
  1486  
  1487  	if len == nil && !p.got(_DotDotDot) {
  1488  		p.xnest++
  1489  		len = p.expr()
  1490  		p.xnest--
  1491  	}
  1492  	if p.tok == _Comma {
  1493  		// Trailing commas are accepted in type parameter
  1494  		// lists but not in array type declarations.
  1495  		// Accept for better error handling but complain.
  1496  		p.syntaxError("unexpected comma; expected ]")
  1497  		p.next()
  1498  	}
  1499  	p.want(_Rbrack)
  1500  	t := new(ArrayType)
  1501  	t.pos = pos
  1502  	t.Len = len
  1503  	t.Elem = p.type_()
  1504  	return t
  1505  }
  1506  
  1507  // "[" and "]" have already been consumed, and pos is the position of "[".
  1508  func (p *parser) sliceType(pos Pos) Expr {
  1509  	t := new(SliceType)
  1510  	t.pos = pos
  1511  	t.Elem = p.type_()
  1512  	return t
  1513  }
  1514  
  1515  func (p *parser) chanElem() Expr {
  1516  	if trace {
  1517  		defer p.trace("chanElem")()
  1518  	}
  1519  
  1520  	typ := p.typeOrNil()
  1521  	if typ == nil {
  1522  		typ = p.badExpr()
  1523  		p.syntaxError("missing channel element type")
  1524  		// assume element type is simply absent - don't advance
  1525  	}
  1526  
  1527  	return typ
  1528  }
  1529  
  1530  // StructType = "struct" "{" { FieldDecl ";" } "}" .
  1531  func (p *parser) structType() *StructType {
  1532  	if trace {
  1533  		defer p.trace("structType")()
  1534  	}
  1535  
  1536  	typ := new(StructType)
  1537  	typ.pos = p.pos()
  1538  
  1539  	p.want(_Struct)
  1540  	p.want(_Lbrace)
  1541  	p.list("struct type", _Semi, _Rbrace, func() bool {
  1542  		p.fieldDecl(typ)
  1543  		return false
  1544  	})
  1545  
  1546  	return typ
  1547  }
  1548  
  1549  // InterfaceType = "interface" "{" { ( MethodDecl | EmbeddedElem ) ";" } "}" .
  1550  func (p *parser) interfaceType() *InterfaceType {
  1551  	if trace {
  1552  		defer p.trace("interfaceType")()
  1553  	}
  1554  
  1555  	typ := new(InterfaceType)
  1556  	typ.pos = p.pos()
  1557  
  1558  	p.want(_Interface)
  1559  	p.want(_Lbrace)
  1560  	p.list("interface type", _Semi, _Rbrace, func() bool {
  1561  		var f *Field
  1562  		if p.tok == _Name {
  1563  			f = p.methodDecl()
  1564  		}
  1565  		if f == nil || f.Name == nil {
  1566  			f = p.embeddedElem(f)
  1567  		}
  1568  		typ.MethodList = append(typ.MethodList, f)
  1569  		return false
  1570  	})
  1571  
  1572  	return typ
  1573  }
  1574  
  1575  // Result = Parameters | Type .
  1576  func (p *parser) funcResult() []*Field {
  1577  	if trace {
  1578  		defer p.trace("funcResult")()
  1579  	}
  1580  
  1581  	if p.got(_Lparen) {
  1582  		return p.paramList(nil, nil, _Rparen, false, false)
  1583  	}
  1584  
  1585  	pos := p.pos()
  1586  	if typ := p.typeOrNil(); typ != nil {
  1587  		f := new(Field)
  1588  		f.pos = pos
  1589  		f.Type = typ
  1590  		return []*Field{f}
  1591  	}
  1592  
  1593  	return nil
  1594  }
  1595  
  1596  func (p *parser) addField(styp *StructType, pos Pos, name *Name, typ Expr, tag *BasicLit) {
  1597  	if tag != nil {
  1598  		for i := len(styp.FieldList) - len(styp.TagList); i > 0; i-- {
  1599  			styp.TagList = append(styp.TagList, nil)
  1600  		}
  1601  		styp.TagList = append(styp.TagList, tag)
  1602  	}
  1603  
  1604  	f := new(Field)
  1605  	f.pos = pos
  1606  	f.Name = name
  1607  	f.Type = typ
  1608  	styp.FieldList = append(styp.FieldList, f)
  1609  
  1610  	if debug && tag != nil && len(styp.FieldList) != len(styp.TagList) {
  1611  		panic("inconsistent struct field list")
  1612  	}
  1613  }
  1614  
  1615  // FieldDecl      = (IdentifierList Type | AnonymousField) [ Tag ] .
  1616  // AnonymousField = [ "*" ] TypeName .
  1617  // Tag            = string_lit .
  1618  func (p *parser) fieldDecl(styp *StructType) {
  1619  	if trace {
  1620  		defer p.trace("fieldDecl")()
  1621  	}
  1622  
  1623  	pos := p.pos()
  1624  	switch p.tok {
  1625  	case _Name:
  1626  		name := p.name()
  1627  		if p.tok == _Dot || p.tok == _Literal || p.tok == _Semi || p.tok == _Rbrace {
  1628  			// embedded type
  1629  			typ := p.qualifiedName(name)
  1630  			tag := p.oliteral()
  1631  			p.addField(styp, pos, nil, typ, tag)
  1632  			break
  1633  		}
  1634  
  1635  		// name1, name2, ... Type [ tag ]
  1636  		names := p.nameList(name)
  1637  		var typ Expr
  1638  
  1639  		// Careful dance: We don't know if we have an embedded instantiated
  1640  		// type T[P1, P2, ...] or a field T of array/slice type [P]E or []E.
  1641  		if len(names) == 1 && p.tok == _Lbrack {
  1642  			typ = p.arrayOrTArgs()
  1643  			if typ, ok := typ.(*IndexExpr); ok {
  1644  				// embedded type T[P1, P2, ...]
  1645  				typ.X = name // name == names[0]
  1646  				tag := p.oliteral()
  1647  				p.addField(styp, pos, nil, typ, tag)
  1648  				break
  1649  			}
  1650  		} else {
  1651  			// T P
  1652  			typ = p.type_()
  1653  		}
  1654  
  1655  		tag := p.oliteral()
  1656  
  1657  		for _, name := range names {
  1658  			p.addField(styp, name.Pos(), name, typ, tag)
  1659  		}
  1660  
  1661  	case _Star:
  1662  		p.next()
  1663  		var typ Expr
  1664  		if p.tok == _Lparen {
  1665  			// *(T)
  1666  			p.syntaxError("cannot parenthesize embedded type")
  1667  			p.next()
  1668  			typ = p.qualifiedName(nil)
  1669  			p.got(_Rparen) // no need to complain if missing
  1670  		} else {
  1671  			// *T
  1672  			typ = p.qualifiedName(nil)
  1673  		}
  1674  		tag := p.oliteral()
  1675  		p.addField(styp, pos, nil, newIndirect(pos, typ), tag)
  1676  
  1677  	case _Lparen:
  1678  		p.syntaxError("cannot parenthesize embedded type")
  1679  		p.next()
  1680  		var typ Expr
  1681  		if p.tok == _Star {
  1682  			// (*T)
  1683  			pos := p.pos()
  1684  			p.next()
  1685  			typ = newIndirect(pos, p.qualifiedName(nil))
  1686  		} else {
  1687  			// (T)
  1688  			typ = p.qualifiedName(nil)
  1689  		}
  1690  		p.got(_Rparen) // no need to complain if missing
  1691  		tag := p.oliteral()
  1692  		p.addField(styp, pos, nil, typ, tag)
  1693  
  1694  	default:
  1695  		p.syntaxError("expected field name or embedded type")
  1696  		p.advance(_Semi, _Rbrace)
  1697  	}
  1698  }
  1699  
  1700  func (p *parser) arrayOrTArgs() Expr {
  1701  	if trace {
  1702  		defer p.trace("arrayOrTArgs")()
  1703  	}
  1704  
  1705  	pos := p.pos()
  1706  	p.want(_Lbrack)
  1707  	if p.got(_Rbrack) {
  1708  		return p.sliceType(pos)
  1709  	}
  1710  
  1711  	// x [n]E or x[n,], x[n1, n2], ...
  1712  	n, comma := p.typeList(false)
  1713  	p.want(_Rbrack)
  1714  	if !comma {
  1715  		if elem := p.typeOrNil(); elem != nil {
  1716  			// x [n]E
  1717  			t := new(ArrayType)
  1718  			t.pos = pos
  1719  			t.Len = n
  1720  			t.Elem = elem
  1721  			return t
  1722  		}
  1723  	}
  1724  
  1725  	// x[n,], x[n1, n2], ...
  1726  	t := new(IndexExpr)
  1727  	t.pos = pos
  1728  	// t.X will be filled in by caller
  1729  	t.Index = n
  1730  	return t
  1731  }
  1732  
  1733  func (p *parser) oliteral() *BasicLit {
  1734  	if p.tok == _Literal {
  1735  		b := new(BasicLit)
  1736  		b.pos = p.pos()
  1737  		b.Value = p.lit
  1738  		b.Kind = p.kind
  1739  		b.Bad = p.bad
  1740  		p.next()
  1741  		return b
  1742  	}
  1743  	return nil
  1744  }
  1745  
  1746  // MethodSpec        = MethodName Signature | InterfaceTypeName .
  1747  // MethodName        = identifier .
  1748  // InterfaceTypeName = TypeName .
  1749  func (p *parser) methodDecl() *Field {
  1750  	if trace {
  1751  		defer p.trace("methodDecl")()
  1752  	}
  1753  
  1754  	f := new(Field)
  1755  	f.pos = p.pos()
  1756  	name := p.name()
  1757  
  1758  	const context = "interface method"
  1759  
  1760  	switch p.tok {
  1761  	case _Lparen:
  1762  		// method
  1763  		f.Name = name
  1764  		_, f.Type = p.funcType(context)
  1765  
  1766  	case _Lbrack:
  1767  		// Careful dance: We don't know if we have a generic method m[T C](x T)
  1768  		// or an embedded instantiated type T[P1, P2] (we accept generic methods
  1769  		// for generality and robustness of parsing but complain with an error).
  1770  		pos := p.pos()
  1771  		p.next()
  1772  
  1773  		// Empty type parameter or argument lists are not permitted.
  1774  		// Treat as if [] were absent.
  1775  		if p.tok == _Rbrack {
  1776  			// name[]
  1777  			pos := p.pos()
  1778  			p.next()
  1779  			if p.tok == _Lparen {
  1780  				// name[](
  1781  				p.errorAt(pos, "empty type parameter list")
  1782  				f.Name = name
  1783  				_, f.Type = p.funcType(context)
  1784  			} else {
  1785  				p.errorAt(pos, "empty type argument list")
  1786  				f.Type = name
  1787  			}
  1788  			break
  1789  		}
  1790  
  1791  		// A type argument list looks like a parameter list with only
  1792  		// types. Parse a parameter list and decide afterwards.
  1793  		list := p.paramList(nil, nil, _Rbrack, false, false)
  1794  		if len(list) == 0 {
  1795  			// The type parameter list is not [] but we got nothing
  1796  			// due to other errors (reported by paramList). Treat
  1797  			// as if [] were absent.
  1798  			if p.tok == _Lparen {
  1799  				f.Name = name
  1800  				_, f.Type = p.funcType(context)
  1801  			} else {
  1802  				f.Type = name
  1803  			}
  1804  			break
  1805  		}
  1806  
  1807  		// len(list) > 0
  1808  		if list[0].Name != nil {
  1809  			// generic method
  1810  			f.Name = name
  1811  			_, f.Type = p.funcType(context)
  1812  			p.errorAt(pos, "interface method must have no type parameters")
  1813  			break
  1814  		}
  1815  
  1816  		// embedded instantiated type
  1817  		t := new(IndexExpr)
  1818  		t.pos = pos
  1819  		t.X = name
  1820  		if len(list) == 1 {
  1821  			t.Index = list[0].Type
  1822  		} else {
  1823  			// len(list) > 1
  1824  			l := new(ListExpr)
  1825  			l.pos = list[0].Pos()
  1826  			l.ElemList = make([]Expr, len(list))
  1827  			for i := range list {
  1828  				l.ElemList[i] = list[i].Type
  1829  			}
  1830  			t.Index = l
  1831  		}
  1832  		f.Type = t
  1833  
  1834  	default:
  1835  		// embedded type
  1836  		f.Type = p.qualifiedName(name)
  1837  	}
  1838  
  1839  	return f
  1840  }
  1841  
  1842  // EmbeddedElem = MethodSpec | EmbeddedTerm { "|" EmbeddedTerm } .
  1843  func (p *parser) embeddedElem(f *Field) *Field {
  1844  	if trace {
  1845  		defer p.trace("embeddedElem")()
  1846  	}
  1847  
  1848  	if f == nil {
  1849  		f = new(Field)
  1850  		f.pos = p.pos()
  1851  		f.Type = p.embeddedTerm()
  1852  	}
  1853  
  1854  	for p.tok == _Operator && p.op == Or {
  1855  		t := new(Operation)
  1856  		t.pos = p.pos()
  1857  		t.Op = Or
  1858  		p.next()
  1859  		t.X = f.Type
  1860  		t.Y = p.embeddedTerm()
  1861  		f.Type = t
  1862  	}
  1863  
  1864  	return f
  1865  }
  1866  
  1867  // EmbeddedTerm = [ "~" ] Type .
  1868  func (p *parser) embeddedTerm() Expr {
  1869  	if trace {
  1870  		defer p.trace("embeddedTerm")()
  1871  	}
  1872  
  1873  	if p.tok == _Operator && p.op == Tilde {
  1874  		t := new(Operation)
  1875  		t.pos = p.pos()
  1876  		t.Op = Tilde
  1877  		p.next()
  1878  		t.X = p.type_()
  1879  		return t
  1880  	}
  1881  
  1882  	t := p.typeOrNil()
  1883  	if t == nil {
  1884  		t = p.badExpr()
  1885  		p.syntaxError("expected ~ term or type")
  1886  		p.advance(_Operator, _Semi, _Rparen, _Rbrack, _Rbrace)
  1887  	}
  1888  
  1889  	return t
  1890  }
  1891  
  1892  // ParameterDecl = [ IdentifierList ] [ "..." ] Type .
  1893  func (p *parser) paramDeclOrNil(name *Name, follow token) *Field {
  1894  	if trace {
  1895  		defer p.trace("paramDeclOrNil")()
  1896  	}
  1897  
  1898  	// type set notation is ok in type parameter lists
  1899  	typeSetsOk := follow == _Rbrack
  1900  
  1901  	pos := p.pos()
  1902  	if name != nil {
  1903  		pos = name.pos
  1904  	} else if typeSetsOk && p.tok == _Operator && p.op == Tilde {
  1905  		// "~" ...
  1906  		return p.embeddedElem(nil)
  1907  	}
  1908  
  1909  	f := new(Field)
  1910  	f.pos = pos
  1911  
  1912  	if p.tok == _Name || name != nil {
  1913  		// name
  1914  		if name == nil {
  1915  			name = p.name()
  1916  		}
  1917  
  1918  		if p.tok == _Lbrack {
  1919  			// name "[" ...
  1920  			f.Type = p.arrayOrTArgs()
  1921  			if typ, ok := f.Type.(*IndexExpr); ok {
  1922  				// name "[" ... "]"
  1923  				typ.X = name
  1924  			} else {
  1925  				// name "[" n "]" E
  1926  				f.Name = name
  1927  			}
  1928  			if typeSetsOk && p.tok == _Operator && p.op == Or {
  1929  				// name "[" ... "]" "|" ...
  1930  				// name "[" n "]" E "|" ...
  1931  				f = p.embeddedElem(f)
  1932  			}
  1933  			return f
  1934  		}
  1935  
  1936  		if p.tok == _Dot {
  1937  			// name "." ...
  1938  			f.Type = p.qualifiedName(name)
  1939  			if typeSetsOk && p.tok == _Operator && p.op == Or {
  1940  				// name "." name "|" ...
  1941  				f = p.embeddedElem(f)
  1942  			}
  1943  			return f
  1944  		}
  1945  
  1946  		if typeSetsOk && p.tok == _Operator && p.op == Or {
  1947  			// name "|" ...
  1948  			f.Type = name
  1949  			return p.embeddedElem(f)
  1950  		}
  1951  
  1952  		f.Name = name
  1953  	}
  1954  
  1955  	if p.tok == _DotDotDot {
  1956  		// [name] "..." ...
  1957  		t := new(DotsType)
  1958  		t.pos = p.pos()
  1959  		p.next()
  1960  		t.Elem = p.typeOrNil()
  1961  		if t.Elem == nil {
  1962  			f.Type = p.badExpr()
  1963  			p.syntaxError("... is missing type")
  1964  		} else {
  1965  			f.Type = t
  1966  		}
  1967  		return f
  1968  	}
  1969  
  1970  	if typeSetsOk && p.tok == _Operator && p.op == Tilde {
  1971  		// [name] "~" ...
  1972  		f.Type = p.embeddedElem(nil).Type
  1973  		return f
  1974  	}
  1975  
  1976  	f.Type = p.typeOrNil()
  1977  	if typeSetsOk && p.tok == _Operator && p.op == Or && f.Type != nil {
  1978  		// [name] type "|"
  1979  		f = p.embeddedElem(f)
  1980  	}
  1981  	if f.Name != nil || f.Type != nil {
  1982  		return f
  1983  	}
  1984  
  1985  	p.syntaxError("expected " + tokstring(follow))
  1986  	p.advance(_Comma, follow)
  1987  	return nil
  1988  }
  1989  
  1990  // Parameters    = "(" [ ParameterList [ "," ] ] ")" .
  1991  // ParameterList = ParameterDecl { "," ParameterDecl } .
  1992  // "(" or "[" has already been consumed.
  1993  // If name != nil, it is the first name after "(" or "[".
  1994  // If typ != nil, name must be != nil, and (name, typ) is the first field in the list.
  1995  // In the result list, either all fields have a name, or no field has a name.
  1996  func (p *parser) paramList(name *Name, typ Expr, close token, requireNames, dddok bool) (list []*Field) {
  1997  	if trace {
  1998  		defer p.trace("paramList")()
  1999  	}
  2000  
  2001  	// p.list won't invoke its function argument if we're at the end of the
  2002  	// parameter list. If we have a complete field, handle this case here.
  2003  	if name != nil && typ != nil && p.tok == close {
  2004  		p.next()
  2005  		par := new(Field)
  2006  		par.pos = name.pos
  2007  		par.Name = name
  2008  		par.Type = typ
  2009  		return []*Field{par}
  2010  	}
  2011  
  2012  	var named int // number of parameters that have an explicit name and type
  2013  	var typed int // number of parameters that have an explicit type
  2014  	end := p.list("parameter list", _Comma, close, func() bool {
  2015  		var par *Field
  2016  		if typ != nil {
  2017  			if debug && name == nil {
  2018  				panic("initial type provided without name")
  2019  			}
  2020  			par = new(Field)
  2021  			par.pos = name.pos
  2022  			par.Name = name
  2023  			par.Type = typ
  2024  		} else {
  2025  			par = p.paramDeclOrNil(name, close)
  2026  		}
  2027  		name = nil // 1st name was consumed if present
  2028  		typ = nil  // 1st type was consumed if present
  2029  		if par != nil {
  2030  			if debug && par.Name == nil && par.Type == nil {
  2031  				panic("parameter without name or type")
  2032  			}
  2033  			if par.Name != nil && par.Type != nil {
  2034  				named++
  2035  			}
  2036  			if par.Type != nil {
  2037  				typed++
  2038  			}
  2039  			list = append(list, par)
  2040  		}
  2041  		return false
  2042  	})
  2043  
  2044  	if len(list) == 0 {
  2045  		return
  2046  	}
  2047  
  2048  	// distribute parameter types (len(list) > 0)
  2049  	if named == 0 && !requireNames {
  2050  		// all unnamed and we're not in a type parameter list => found names are named types
  2051  		for _, par := range list {
  2052  			if typ := par.Name; typ != nil {
  2053  				par.Type = typ
  2054  				par.Name = nil
  2055  			}
  2056  		}
  2057  	} else if named != len(list) {
  2058  		// some named or we're in a type parameter list => all must be named
  2059  		var errPos Pos // left-most error position (or unknown)
  2060  		var typ Expr   // current type (from right to left)
  2061  		for i := len(list) - 1; i >= 0; i-- {
  2062  			par := list[i]
  2063  			if par.Type != nil {
  2064  				typ = par.Type
  2065  				if par.Name == nil {
  2066  					errPos = StartPos(typ)
  2067  					par.Name = NewName(errPos, "_")
  2068  				}
  2069  			} else if typ != nil {
  2070  				par.Type = typ
  2071  			} else {
  2072  				// par.Type == nil && typ == nil => we only have a par.Name
  2073  				errPos = par.Name.Pos()
  2074  				t := p.badExpr()
  2075  				t.pos = errPos // correct position
  2076  				par.Type = t
  2077  			}
  2078  		}
  2079  		if errPos.IsKnown() {
  2080  			// Not all parameters are named because named != len(list).
  2081  			// If named == typed, there must be parameters that have no types.
  2082  			// They must be at the end of the parameter list, otherwise types
  2083  			// would have been filled in by the right-to-left sweep above and
  2084  			// there would be no error.
  2085  			// If requireNames is set, the parameter list is a type parameter
  2086  			// list.
  2087  			var msg string
  2088  			if named == typed {
  2089  				errPos = end // position error at closing token ) or ]
  2090  				if requireNames {
  2091  					msg = "missing type constraint"
  2092  				} else {
  2093  					msg = "missing parameter type"
  2094  				}
  2095  			} else {
  2096  				if requireNames {
  2097  					msg = "missing type parameter name"
  2098  					// go.dev/issue/60812
  2099  					if len(list) == 1 {
  2100  						msg += " or invalid array length"
  2101  					}
  2102  				} else {
  2103  					msg = "missing parameter name"
  2104  				}
  2105  			}
  2106  			p.syntaxErrorAt(errPos, msg)
  2107  		}
  2108  	}
  2109  
  2110  	// check use of ...
  2111  	first := true // only report first occurrence
  2112  	for i, f := range list {
  2113  		if t, _ := f.Type.(*DotsType); t != nil && (!dddok || i+1 < len(list)) {
  2114  			if first {
  2115  				first = false
  2116  				if dddok {
  2117  					p.errorAt(t.pos, "can only use ... with final parameter")
  2118  				} else {
  2119  					p.errorAt(t.pos, "invalid use of ...")
  2120  				}
  2121  			}
  2122  			// use T instead of invalid ...T
  2123  			f.Type = t.Elem
  2124  		}
  2125  	}
  2126  
  2127  	return
  2128  }
  2129  
  2130  func (p *parser) badExpr() *BadExpr {
  2131  	b := new(BadExpr)
  2132  	b.pos = p.pos()
  2133  	return b
  2134  }
  2135  
  2136  // ----------------------------------------------------------------------------
  2137  // Statements
  2138  
  2139  // SimpleStmt = EmptyStmt | ExpressionStmt | SendStmt | IncDecStmt | Assignment | ShortVarDecl .
  2140  func (p *parser) simpleStmt(lhs Expr, keyword token) SimpleStmt {
  2141  	if trace {
  2142  		defer p.trace("simpleStmt")()
  2143  	}
  2144  
  2145  	if keyword == _For && p.tok == _Range {
  2146  		// _Range expr
  2147  		if debug && lhs != nil {
  2148  			panic("invalid call of simpleStmt")
  2149  		}
  2150  		return p.newRangeClause(nil, false)
  2151  	}
  2152  
  2153  	if lhs == nil {
  2154  		lhs = p.exprList()
  2155  	}
  2156  
  2157  	if _, ok := lhs.(*ListExpr); !ok && p.tok != _Assign && p.tok != _Define {
  2158  		// expr
  2159  		pos := p.pos()
  2160  		switch p.tok {
  2161  		case _AssignOp:
  2162  			// lhs op= rhs
  2163  			op := p.op
  2164  			p.next()
  2165  			return p.newAssignStmt(pos, op, lhs, p.expr())
  2166  
  2167  		case _IncOp:
  2168  			// lhs++ or lhs--
  2169  			op := p.op
  2170  			p.next()
  2171  			return p.newAssignStmt(pos, op, lhs, nil)
  2172  
  2173  		case _Arrow:
  2174  			// lhs <- rhs
  2175  			s := new(SendStmt)
  2176  			s.pos = pos
  2177  			p.next()
  2178  			s.Chan = lhs
  2179  			s.Value = p.expr()
  2180  			return s
  2181  
  2182  		default:
  2183  			// expr
  2184  			s := new(ExprStmt)
  2185  			s.pos = lhs.Pos()
  2186  			s.X = lhs
  2187  			return s
  2188  		}
  2189  	}
  2190  
  2191  	// expr_list
  2192  	switch p.tok {
  2193  	case _Assign, _Define:
  2194  		pos := p.pos()
  2195  		var op Operator
  2196  		if p.tok == _Define {
  2197  			op = Def
  2198  		}
  2199  		p.next()
  2200  
  2201  		if keyword == _For && p.tok == _Range {
  2202  			// expr_list op= _Range expr
  2203  			return p.newRangeClause(lhs, op == Def)
  2204  		}
  2205  
  2206  		// expr_list op= expr_list
  2207  		rhs := p.exprList()
  2208  
  2209  		if x, ok := rhs.(*TypeSwitchGuard); ok && keyword == _Switch && op == Def {
  2210  			if lhs, ok := lhs.(*Name); ok {
  2211  				// switch … lhs := rhs.(type)
  2212  				x.Lhs = lhs
  2213  				s := new(ExprStmt)
  2214  				s.pos = x.Pos()
  2215  				s.X = x
  2216  				return s
  2217  			}
  2218  		}
  2219  
  2220  		return p.newAssignStmt(pos, op, lhs, rhs)
  2221  
  2222  	default:
  2223  		p.syntaxError("expected := or = or comma")
  2224  		p.advance(_Semi, _Rbrace)
  2225  		// make the best of what we have
  2226  		if x, ok := lhs.(*ListExpr); ok {
  2227  			lhs = x.ElemList[0]
  2228  		}
  2229  		s := new(ExprStmt)
  2230  		s.pos = lhs.Pos()
  2231  		s.X = lhs
  2232  		return s
  2233  	}
  2234  }
  2235  
  2236  func (p *parser) newRangeClause(lhs Expr, def bool) *RangeClause {
  2237  	r := new(RangeClause)
  2238  	r.pos = p.pos()
  2239  	p.next() // consume _Range
  2240  	r.Lhs = lhs
  2241  	r.Def = def
  2242  	r.X = p.expr()
  2243  	return r
  2244  }
  2245  
  2246  func (p *parser) newAssignStmt(pos Pos, op Operator, lhs, rhs Expr) *AssignStmt {
  2247  	a := new(AssignStmt)
  2248  	a.pos = pos
  2249  	a.Op = op
  2250  	a.Lhs = lhs
  2251  	a.Rhs = rhs
  2252  	return a
  2253  }
  2254  
  2255  func (p *parser) labeledStmtOrNil(label *Name) Stmt {
  2256  	if trace {
  2257  		defer p.trace("labeledStmt")()
  2258  	}
  2259  
  2260  	s := new(LabeledStmt)
  2261  	s.pos = p.pos()
  2262  	s.Label = label
  2263  
  2264  	p.want(_Colon)
  2265  
  2266  	if p.tok == _Rbrace {
  2267  		// We expect a statement (incl. an empty statement), which must be
  2268  		// terminated by a semicolon. Because semicolons may be omitted before
  2269  		// an _Rbrace, seeing an _Rbrace implies an empty statement.
  2270  		e := new(EmptyStmt)
  2271  		e.pos = p.pos()
  2272  		s.Stmt = e
  2273  		return s
  2274  	}
  2275  
  2276  	s.Stmt = p.stmtOrNil()
  2277  	if s.Stmt != nil {
  2278  		return s
  2279  	}
  2280  
  2281  	// report error at line of ':' token
  2282  	p.syntaxErrorAt(s.pos, "missing statement after label")
  2283  	// we are already at the end of the labeled statement - no need to advance
  2284  	return nil // avoids follow-on errors (see e.g., fixedbugs/bug274.go)
  2285  }
  2286  
  2287  // context must be a non-empty string unless we know that p.tok == _Lbrace.
  2288  func (p *parser) blockStmt(context string) *BlockStmt {
  2289  	if trace {
  2290  		defer p.trace("blockStmt")()
  2291  	}
  2292  
  2293  	s := new(BlockStmt)
  2294  	s.pos = p.pos()
  2295  
  2296  	// people coming from C may forget that braces are mandatory in Go
  2297  	if !p.got(_Lbrace) {
  2298  		p.syntaxError("expected { after " + context)
  2299  		p.advance(_Name, _Rbrace)
  2300  		s.Rbrace = p.pos() // in case we found "}"
  2301  		if p.got(_Rbrace) {
  2302  			return s
  2303  		}
  2304  	}
  2305  
  2306  	s.List = p.stmtList()
  2307  	s.Rbrace = p.pos()
  2308  	p.want(_Rbrace)
  2309  
  2310  	return s
  2311  }
  2312  
  2313  func (p *parser) declStmt(f func(*Group) Decl) *DeclStmt {
  2314  	if trace {
  2315  		defer p.trace("declStmt")()
  2316  	}
  2317  
  2318  	s := new(DeclStmt)
  2319  	s.pos = p.pos()
  2320  
  2321  	p.next() // _Const, _Type, or _Var
  2322  	s.DeclList = p.appendGroup(nil, f)
  2323  
  2324  	return s
  2325  }
  2326  
  2327  func (p *parser) forStmt() Stmt {
  2328  	if trace {
  2329  		defer p.trace("forStmt")()
  2330  	}
  2331  
  2332  	s := new(ForStmt)
  2333  	s.pos = p.pos()
  2334  
  2335  	s.Init, s.Cond, s.Post = p.header(_For)
  2336  	s.Body = p.blockStmt("for clause")
  2337  
  2338  	return s
  2339  }
  2340  
  2341  func (p *parser) header(keyword token) (init SimpleStmt, cond Expr, post SimpleStmt) {
  2342  	p.want(keyword)
  2343  
  2344  	if p.tok == _Lbrace {
  2345  		if keyword == _If {
  2346  			p.syntaxError("missing condition in if statement")
  2347  			cond = p.badExpr()
  2348  		}
  2349  		return
  2350  	}
  2351  	// p.tok != _Lbrace
  2352  
  2353  	outer := p.xnest
  2354  	p.xnest = -1
  2355  
  2356  	if p.tok != _Semi {
  2357  		// accept potential varDecl but complain
  2358  		if p.got(_Var) {
  2359  			p.syntaxError(fmt.Sprintf("var declaration not allowed in %s initializer", keyword.String()))
  2360  		}
  2361  		init = p.simpleStmt(nil, keyword)
  2362  		// If we have a range clause, we are done (can only happen for keyword == _For).
  2363  		if _, ok := init.(*RangeClause); ok {
  2364  			p.xnest = outer
  2365  			return
  2366  		}
  2367  	}
  2368  
  2369  	var condStmt SimpleStmt
  2370  	var semi struct {
  2371  		pos Pos
  2372  		lit string // valid if pos.IsKnown()
  2373  	}
  2374  	if p.tok != _Lbrace {
  2375  		if p.tok == _Semi {
  2376  			semi.pos = p.pos()
  2377  			semi.lit = p.lit
  2378  			p.next()
  2379  		} else {
  2380  			// asking for a '{' rather than a ';' here leads to a better error message
  2381  			p.want(_Lbrace)
  2382  			if p.tok != _Lbrace {
  2383  				p.advance(_Lbrace, _Rbrace) // for better synchronization (e.g., go.dev/issue/22581)
  2384  			}
  2385  		}
  2386  		if keyword == _For {
  2387  			if p.tok != _Semi {
  2388  				if p.tok == _Lbrace {
  2389  					p.syntaxError("expected for loop condition")
  2390  					goto done
  2391  				}
  2392  				condStmt = p.simpleStmt(nil, 0 /* range not permitted */)
  2393  			}
  2394  			p.want(_Semi)
  2395  			if p.tok != _Lbrace {
  2396  				post = p.simpleStmt(nil, 0 /* range not permitted */)
  2397  				if a, _ := post.(*AssignStmt); a != nil && a.Op == Def {
  2398  					p.syntaxErrorAt(a.Pos(), "cannot declare in post statement of for loop")
  2399  				}
  2400  			}
  2401  		} else if p.tok != _Lbrace {
  2402  			condStmt = p.simpleStmt(nil, keyword)
  2403  		}
  2404  	} else {
  2405  		condStmt = init
  2406  		init = nil
  2407  	}
  2408  
  2409  done:
  2410  	// unpack condStmt
  2411  	switch s := condStmt.(type) {
  2412  	case nil:
  2413  		if keyword == _If && semi.pos.IsKnown() {
  2414  			if semi.lit != "semicolon" {
  2415  				p.syntaxErrorAt(semi.pos, fmt.Sprintf("unexpected %s, expected { after if clause", semi.lit))
  2416  			} else {
  2417  				p.syntaxErrorAt(semi.pos, "missing condition in if statement")
  2418  			}
  2419  			b := new(BadExpr)
  2420  			b.pos = semi.pos
  2421  			cond = b
  2422  		}
  2423  	case *ExprStmt:
  2424  		cond = s.X
  2425  	default:
  2426  		// A common syntax error is to write '=' instead of '==',
  2427  		// which turns an expression into an assignment. Provide
  2428  		// a more explicit error message in that case to prevent
  2429  		// further confusion.
  2430  		var str string
  2431  		if as, ok := s.(*AssignStmt); ok && as.Op == 0 {
  2432  			// Emphasize complex Lhs and Rhs of assignment with parentheses to highlight '='.
  2433  			str = "assignment " + emphasize(as.Lhs) + " = " + emphasize(as.Rhs)
  2434  		} else {
  2435  			str = String(s)
  2436  		}
  2437  		p.syntaxErrorAt(s.Pos(), fmt.Sprintf("cannot use %s as value", str))
  2438  	}
  2439  
  2440  	p.xnest = outer
  2441  	return
  2442  }
  2443  
  2444  // emphasize returns a string representation of x, with (top-level)
  2445  // binary expressions emphasized by enclosing them in parentheses.
  2446  func emphasize(x Expr) string {
  2447  	s := String(x)
  2448  	if op, _ := x.(*Operation); op != nil && op.Y != nil {
  2449  		// binary expression
  2450  		return "(" + s + ")"
  2451  	}
  2452  	return s
  2453  }
  2454  
  2455  func (p *parser) ifStmt() *IfStmt {
  2456  	if trace {
  2457  		defer p.trace("ifStmt")()
  2458  	}
  2459  
  2460  	s := new(IfStmt)
  2461  	s.pos = p.pos()
  2462  
  2463  	s.Init, s.Cond, _ = p.header(_If)
  2464  	s.Then = p.blockStmt("if clause")
  2465  
  2466  	if p.got(_Else) {
  2467  		switch p.tok {
  2468  		case _If:
  2469  			s.Else = p.ifStmt()
  2470  		case _Lbrace:
  2471  			s.Else = p.blockStmt("")
  2472  		default:
  2473  			p.syntaxError("else must be followed by if or statement block")
  2474  			p.advance(_Name, _Rbrace)
  2475  		}
  2476  	}
  2477  
  2478  	return s
  2479  }
  2480  
  2481  func (p *parser) switchStmt() *SwitchStmt {
  2482  	if trace {
  2483  		defer p.trace("switchStmt")()
  2484  	}
  2485  
  2486  	s := new(SwitchStmt)
  2487  	s.pos = p.pos()
  2488  
  2489  	s.Init, s.Tag, _ = p.header(_Switch)
  2490  
  2491  	if !p.got(_Lbrace) {
  2492  		p.syntaxError("missing { after switch clause")
  2493  		p.advance(_Case, _Default, _Rbrace)
  2494  	}
  2495  	for p.tok != _EOF && p.tok != _Rbrace {
  2496  		s.Body = append(s.Body, p.caseClause())
  2497  	}
  2498  	s.Rbrace = p.pos()
  2499  	p.want(_Rbrace)
  2500  
  2501  	return s
  2502  }
  2503  
  2504  func (p *parser) selectStmt() *SelectStmt {
  2505  	if trace {
  2506  		defer p.trace("selectStmt")()
  2507  	}
  2508  
  2509  	s := new(SelectStmt)
  2510  	s.pos = p.pos()
  2511  
  2512  	p.want(_Select)
  2513  	if !p.got(_Lbrace) {
  2514  		p.syntaxError("missing { after select clause")
  2515  		p.advance(_Case, _Default, _Rbrace)
  2516  	}
  2517  	for p.tok != _EOF && p.tok != _Rbrace {
  2518  		s.Body = append(s.Body, p.commClause())
  2519  	}
  2520  	s.Rbrace = p.pos()
  2521  	p.want(_Rbrace)
  2522  
  2523  	return s
  2524  }
  2525  
  2526  func (p *parser) caseClause() *CaseClause {
  2527  	if trace {
  2528  		defer p.trace("caseClause")()
  2529  	}
  2530  
  2531  	c := new(CaseClause)
  2532  	c.pos = p.pos()
  2533  
  2534  	switch p.tok {
  2535  	case _Case:
  2536  		p.next()
  2537  		c.Cases = p.exprList()
  2538  
  2539  	case _Default:
  2540  		p.next()
  2541  
  2542  	default:
  2543  		p.syntaxError("expected case or default or }")
  2544  		p.advance(_Colon, _Case, _Default, _Rbrace)
  2545  	}
  2546  
  2547  	c.Colon = p.pos()
  2548  	p.want(_Colon)
  2549  	c.Body = p.stmtList()
  2550  
  2551  	return c
  2552  }
  2553  
  2554  func (p *parser) commClause() *CommClause {
  2555  	if trace {
  2556  		defer p.trace("commClause")()
  2557  	}
  2558  
  2559  	c := new(CommClause)
  2560  	c.pos = p.pos()
  2561  
  2562  	switch p.tok {
  2563  	case _Case:
  2564  		p.next()
  2565  		c.Comm = p.simpleStmt(nil, 0)
  2566  
  2567  		// The syntax restricts the possible simple statements here to:
  2568  		//
  2569  		//     lhs <- x (send statement)
  2570  		//     <-x
  2571  		//     lhs = <-x
  2572  		//     lhs := <-x
  2573  		//
  2574  		// All these (and more) are recognized by simpleStmt and invalid
  2575  		// syntax trees are flagged later, during type checking.
  2576  
  2577  	case _Default:
  2578  		p.next()
  2579  
  2580  	default:
  2581  		p.syntaxError("expected case or default or }")
  2582  		p.advance(_Colon, _Case, _Default, _Rbrace)
  2583  	}
  2584  
  2585  	c.Colon = p.pos()
  2586  	p.want(_Colon)
  2587  	c.Body = p.stmtList()
  2588  
  2589  	return c
  2590  }
  2591  
  2592  // stmtOrNil parses a statement if one is present, or else returns nil.
  2593  //
  2594  //	Statement =
  2595  //		Declaration | LabeledStmt | SimpleStmt |
  2596  //		GoStmt | ReturnStmt | BreakStmt | ContinueStmt | GotoStmt |
  2597  //		FallthroughStmt | Block | IfStmt | SwitchStmt | SelectStmt | ForStmt |
  2598  //		DeferStmt .
  2599  func (p *parser) stmtOrNil() Stmt {
  2600  	if trace {
  2601  		defer p.trace("stmt " + p.tok.String())()
  2602  	}
  2603  
  2604  	// Most statements (assignments) start with an identifier;
  2605  	// look for it first before doing anything more expensive.
  2606  	if p.tok == _Name {
  2607  		p.clearPragma()
  2608  		lhs := p.exprList()
  2609  		if label, ok := lhs.(*Name); ok && p.tok == _Colon {
  2610  			return p.labeledStmtOrNil(label)
  2611  		}
  2612  		return p.simpleStmt(lhs, 0)
  2613  	}
  2614  
  2615  	switch p.tok {
  2616  	case _Var:
  2617  		return p.declStmt(p.varDecl)
  2618  
  2619  	case _Const:
  2620  		return p.declStmt(p.constDecl)
  2621  
  2622  	case _Type:
  2623  		return p.declStmt(p.typeDecl)
  2624  	}
  2625  
  2626  	p.clearPragma()
  2627  
  2628  	switch p.tok {
  2629  	case _Lbrace:
  2630  		return p.blockStmt("")
  2631  
  2632  	case _Operator, _Star:
  2633  		switch p.op {
  2634  		case Add, Sub, Mul, And, Xor, Not:
  2635  			return p.simpleStmt(nil, 0) // unary operators
  2636  		}
  2637  
  2638  	case _Literal, _Func, _Lparen, // operands
  2639  		_Lbrack, _Struct, _Map, _Chan, _Interface, // composite types
  2640  		_Arrow: // receive operator
  2641  		return p.simpleStmt(nil, 0)
  2642  
  2643  	case _For:
  2644  		return p.forStmt()
  2645  
  2646  	case _Switch:
  2647  		return p.switchStmt()
  2648  
  2649  	case _Select:
  2650  		return p.selectStmt()
  2651  
  2652  	case _If:
  2653  		return p.ifStmt()
  2654  
  2655  	case _Fallthrough:
  2656  		s := new(BranchStmt)
  2657  		s.pos = p.pos()
  2658  		p.next()
  2659  		s.Tok = _Fallthrough
  2660  		return s
  2661  
  2662  	case _Break, _Continue:
  2663  		s := new(BranchStmt)
  2664  		s.pos = p.pos()
  2665  		s.Tok = p.tok
  2666  		p.next()
  2667  		if p.tok == _Name {
  2668  			s.Label = p.name()
  2669  		}
  2670  		return s
  2671  
  2672  	case _Go, _Defer:
  2673  		return p.callStmt()
  2674  
  2675  	case _Goto:
  2676  		s := new(BranchStmt)
  2677  		s.pos = p.pos()
  2678  		s.Tok = _Goto
  2679  		p.next()
  2680  		s.Label = p.name()
  2681  		return s
  2682  
  2683  	case _Return:
  2684  		s := new(ReturnStmt)
  2685  		s.pos = p.pos()
  2686  		p.next()
  2687  		if p.tok != _Semi && p.tok != _Rbrace {
  2688  			s.Results = p.exprList()
  2689  		}
  2690  		return s
  2691  
  2692  	case _Semi:
  2693  		s := new(EmptyStmt)
  2694  		s.pos = p.pos()
  2695  		return s
  2696  	}
  2697  
  2698  	return nil
  2699  }
  2700  
  2701  // StatementList = { Statement ";" } .
  2702  func (p *parser) stmtList() (list []Stmt) {
  2703  	if trace {
  2704  		defer p.trace("stmtList")()
  2705  	}
  2706  
  2707  	for p.tok != _EOF && p.tok != _Rbrace && p.tok != _Case && p.tok != _Default {
  2708  		s := p.stmtOrNil()
  2709  		p.clearPragma()
  2710  		if s == nil {
  2711  			break
  2712  		}
  2713  		list = append(list, s)
  2714  		// ";" is optional before "}"
  2715  		if !p.got(_Semi) && p.tok != _Rbrace {
  2716  			p.syntaxError("at end of statement")
  2717  			p.advance(_Semi, _Rbrace, _Case, _Default)
  2718  			p.got(_Semi) // avoid spurious empty statement
  2719  		}
  2720  	}
  2721  	return
  2722  }
  2723  
  2724  // argList parses a possibly empty, comma-separated list of arguments,
  2725  // optionally followed by a comma (if not empty), and closed by ")".
  2726  // The last argument may be followed by "...".
  2727  //
  2728  // argList = [ arg { "," arg } [ "..." ] [ "," ] ] ")" .
  2729  func (p *parser) argList() (list []Expr, hasDots bool) {
  2730  	if trace {
  2731  		defer p.trace("argList")()
  2732  	}
  2733  
  2734  	p.xnest++
  2735  	p.list("argument list", _Comma, _Rparen, func() bool {
  2736  		list = append(list, p.expr())
  2737  		hasDots = p.got(_DotDotDot)
  2738  		return hasDots
  2739  	})
  2740  	p.xnest--
  2741  
  2742  	return
  2743  }
  2744  
  2745  // ----------------------------------------------------------------------------
  2746  // Common productions
  2747  
  2748  func (p *parser) name() *Name {
  2749  	// no tracing to avoid overly verbose output
  2750  
  2751  	if p.tok == _Name {
  2752  		n := NewName(p.pos(), p.lit)
  2753  		p.next()
  2754  		return n
  2755  	}
  2756  
  2757  	n := NewName(p.pos(), "_")
  2758  	p.syntaxError("expected name")
  2759  	p.advance()
  2760  	return n
  2761  }
  2762  
  2763  // IdentifierList = identifier { "," identifier } .
  2764  // The first name must be provided.
  2765  func (p *parser) nameList(first *Name) []*Name {
  2766  	if trace {
  2767  		defer p.trace("nameList")()
  2768  	}
  2769  
  2770  	if debug && first == nil {
  2771  		panic("first name not provided")
  2772  	}
  2773  
  2774  	l := []*Name{first}
  2775  	for p.got(_Comma) {
  2776  		l = append(l, p.name())
  2777  	}
  2778  
  2779  	return l
  2780  }
  2781  
  2782  // The first name may be provided, or nil.
  2783  func (p *parser) qualifiedName(name *Name) Expr {
  2784  	if trace {
  2785  		defer p.trace("qualifiedName")()
  2786  	}
  2787  
  2788  	var x Expr
  2789  	switch {
  2790  	case name != nil:
  2791  		x = name
  2792  	case p.tok == _Name:
  2793  		x = p.name()
  2794  	default:
  2795  		x = NewName(p.pos(), "_")
  2796  		p.syntaxError("expected name")
  2797  		p.advance(_Dot, _Semi, _Rbrace)
  2798  	}
  2799  
  2800  	if p.tok == _Dot {
  2801  		s := new(SelectorExpr)
  2802  		s.pos = p.pos()
  2803  		p.next()
  2804  		s.X = x
  2805  		s.Sel = p.name()
  2806  		x = s
  2807  	}
  2808  
  2809  	if p.tok == _Lbrack {
  2810  		x = p.typeInstance(x)
  2811  	}
  2812  
  2813  	return x
  2814  }
  2815  
  2816  // ExpressionList = Expression { "," Expression } .
  2817  func (p *parser) exprList() Expr {
  2818  	if trace {
  2819  		defer p.trace("exprList")()
  2820  	}
  2821  
  2822  	x := p.expr()
  2823  	if p.got(_Comma) {
  2824  		list := []Expr{x, p.expr()}
  2825  		for p.got(_Comma) {
  2826  			list = append(list, p.expr())
  2827  		}
  2828  		t := new(ListExpr)
  2829  		t.pos = x.Pos()
  2830  		t.ElemList = list
  2831  		x = t
  2832  	}
  2833  	return x
  2834  }
  2835  
  2836  // typeList parses a non-empty, comma-separated list of types,
  2837  // optionally followed by a comma. If strict is set to false,
  2838  // the first element may also be a (non-type) expression.
  2839  // If there is more than one argument, the result is a *ListExpr.
  2840  // The comma result indicates whether there was a (separating or
  2841  // trailing) comma.
  2842  //
  2843  // typeList = arg { "," arg } [ "," ] .
  2844  func (p *parser) typeList(strict bool) (x Expr, comma bool) {
  2845  	if trace {
  2846  		defer p.trace("typeList")()
  2847  	}
  2848  
  2849  	p.xnest++
  2850  	if strict {
  2851  		x = p.type_()
  2852  	} else {
  2853  		x = p.expr()
  2854  	}
  2855  	if p.got(_Comma) {
  2856  		comma = true
  2857  		if t := p.typeOrNil(); t != nil {
  2858  			list := []Expr{x, t}
  2859  			for p.got(_Comma) {
  2860  				if t = p.typeOrNil(); t == nil {
  2861  					break
  2862  				}
  2863  				list = append(list, t)
  2864  			}
  2865  			l := new(ListExpr)
  2866  			l.pos = x.Pos() // == list[0].Pos()
  2867  			l.ElemList = list
  2868  			x = l
  2869  		}
  2870  	}
  2871  	p.xnest--
  2872  	return
  2873  }
  2874  
  2875  // Unparen returns e with any enclosing parentheses stripped.
  2876  func Unparen(x Expr) Expr {
  2877  	for {
  2878  		p, ok := x.(*ParenExpr)
  2879  		if !ok {
  2880  			break
  2881  		}
  2882  		x = p.X
  2883  	}
  2884  	return x
  2885  }
  2886  
  2887  // UnpackListExpr unpacks a *ListExpr into a []Expr.
  2888  func UnpackListExpr(x Expr) []Expr {
  2889  	switch x := x.(type) {
  2890  	case nil:
  2891  		return nil
  2892  	case *ListExpr:
  2893  		return x.ElemList
  2894  	default:
  2895  		return []Expr{x}
  2896  	}
  2897  }
  2898  

View as plain text