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

View as plain text