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, false) // 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, 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, false)
  1473  		}
  1474  	}
  1475  
  1476  	p.want(_Lparen)
  1477  	typ.ParamList = p.paramList(nil, nil, _Rparen, false, true)
  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, 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, 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  			f.Type = p.badExpr()
  1966  			p.syntaxError("... is missing type")
  1967  		} else {
  1968  			f.Type = t
  1969  		}
  1970  		return f
  1971  	}
  1972  
  1973  	if typeSetsOk && p.tok == _Operator && p.op == Tilde {
  1974  		// [name] "~" ...
  1975  		f.Type = p.embeddedElem(nil).Type
  1976  		return f
  1977  	}
  1978  
  1979  	f.Type = p.typeOrNil()
  1980  	if typeSetsOk && p.tok == _Operator && p.op == Or && f.Type != nil {
  1981  		// [name] type "|"
  1982  		f = p.embeddedElem(f)
  1983  	}
  1984  	if f.Name != nil || f.Type != nil {
  1985  		return f
  1986  	}
  1987  
  1988  	p.syntaxError("expected " + tokstring(follow))
  1989  	p.advance(_Comma, follow)
  1990  	return nil
  1991  }
  1992  
  1993  // Parameters    = "(" [ ParameterList [ "," ] ] ")" .
  1994  // ParameterList = ParameterDecl { "," ParameterDecl } .
  1995  // "(" or "[" has already been consumed.
  1996  // If name != nil, it is the first name after "(" or "[".
  1997  // If typ != nil, name must be != nil, and (name, typ) is the first field in the list.
  1998  // In the result list, either all fields have a name, or no field has a name.
  1999  func (p *parser) paramList(name *Name, typ Expr, close token, requireNames, dddok bool) (list []*Field) {
  2000  	if trace {
  2001  		defer p.trace("paramList")()
  2002  	}
  2003  
  2004  	// p.list won't invoke its function argument if we're at the end of the
  2005  	// parameter list. If we have a complete field, handle this case here.
  2006  	if name != nil && typ != nil && p.tok == close {
  2007  		p.next()
  2008  		par := new(Field)
  2009  		par.pos = name.pos
  2010  		par.Name = name
  2011  		par.Type = typ
  2012  		return []*Field{par}
  2013  	}
  2014  
  2015  	var named int // number of parameters that have an explicit name and type
  2016  	var typed int // number of parameters that have an explicit type
  2017  	end := p.list("parameter list", _Comma, close, func() bool {
  2018  		var par *Field
  2019  		if typ != nil {
  2020  			if debug && name == nil {
  2021  				panic("initial type provided without name")
  2022  			}
  2023  			par = new(Field)
  2024  			par.pos = name.pos
  2025  			par.Name = name
  2026  			par.Type = typ
  2027  		} else {
  2028  			par = p.paramDeclOrNil(name, close)
  2029  		}
  2030  		name = nil // 1st name was consumed if present
  2031  		typ = nil  // 1st type was consumed if present
  2032  		if par != nil {
  2033  			if debug && par.Name == nil && par.Type == nil {
  2034  				panic("parameter without name or type")
  2035  			}
  2036  			if par.Name != nil && par.Type != nil {
  2037  				named++
  2038  			}
  2039  			if par.Type != nil {
  2040  				typed++
  2041  			}
  2042  			list = append(list, par)
  2043  		}
  2044  		return false
  2045  	})
  2046  
  2047  	if len(list) == 0 {
  2048  		return
  2049  	}
  2050  
  2051  	// distribute parameter types (len(list) > 0)
  2052  	if named == 0 && !requireNames {
  2053  		// all unnamed and we're not in a type parameter list => found names are named types
  2054  		for _, par := range list {
  2055  			if typ := par.Name; typ != nil {
  2056  				par.Type = typ
  2057  				par.Name = nil
  2058  			}
  2059  		}
  2060  	} else if named != len(list) {
  2061  		// some named or we're in a type parameter list => all must be named
  2062  		var errPos Pos // left-most error position (or unknown)
  2063  		var typ Expr   // current type (from right to left)
  2064  		for i := len(list) - 1; i >= 0; i-- {
  2065  			par := list[i]
  2066  			if par.Type != nil {
  2067  				typ = par.Type
  2068  				if par.Name == nil {
  2069  					errPos = StartPos(typ)
  2070  					par.Name = NewName(errPos, "_")
  2071  				}
  2072  			} else if typ != nil {
  2073  				par.Type = typ
  2074  			} else {
  2075  				// par.Type == nil && typ == nil => we only have a par.Name
  2076  				errPos = par.Name.Pos()
  2077  				t := p.badExpr()
  2078  				t.pos = errPos // correct position
  2079  				par.Type = t
  2080  			}
  2081  		}
  2082  		if errPos.IsKnown() {
  2083  			// Not all parameters are named because named != len(list).
  2084  			// If named == typed, there must be parameters that have no types.
  2085  			// They must be at the end of the parameter list, otherwise types
  2086  			// would have been filled in by the right-to-left sweep above and
  2087  			// there would be no error.
  2088  			// If requireNames is set, the parameter list is a type parameter
  2089  			// list.
  2090  			var msg string
  2091  			if named == typed {
  2092  				errPos = end // position error at closing token ) or ]
  2093  				if requireNames {
  2094  					msg = "missing type constraint"
  2095  				} else {
  2096  					msg = "missing parameter type"
  2097  				}
  2098  			} else {
  2099  				if requireNames {
  2100  					msg = "missing type parameter name"
  2101  					// go.dev/issue/60812
  2102  					if len(list) == 1 {
  2103  						msg += " or invalid array length"
  2104  					}
  2105  				} else {
  2106  					msg = "missing parameter name"
  2107  				}
  2108  			}
  2109  			p.syntaxErrorAt(errPos, msg)
  2110  		}
  2111  	}
  2112  
  2113  	// check use of ...
  2114  	first := true // only report first occurrence
  2115  	for i, f := range list {
  2116  		if t, _ := f.Type.(*DotsType); t != nil && (!dddok || i+1 < len(list)) {
  2117  			if first {
  2118  				first = false
  2119  				if dddok {
  2120  					p.errorAt(t.pos, "can only use ... with final parameter")
  2121  				} else {
  2122  					p.errorAt(t.pos, "invalid use of ...")
  2123  				}
  2124  			}
  2125  			// use T instead of invalid ...T
  2126  			f.Type = t.Elem
  2127  		}
  2128  	}
  2129  
  2130  	return
  2131  }
  2132  
  2133  func (p *parser) badExpr() *BadExpr {
  2134  	b := new(BadExpr)
  2135  	b.pos = p.pos()
  2136  	return b
  2137  }
  2138  
  2139  // ----------------------------------------------------------------------------
  2140  // Statements
  2141  
  2142  // SimpleStmt = EmptyStmt | ExpressionStmt | SendStmt | IncDecStmt | Assignment | ShortVarDecl .
  2143  func (p *parser) simpleStmt(lhs Expr, keyword token) SimpleStmt {
  2144  	if trace {
  2145  		defer p.trace("simpleStmt")()
  2146  	}
  2147  
  2148  	if keyword == _For && p.tok == _Range {
  2149  		// _Range expr
  2150  		if debug && lhs != nil {
  2151  			panic("invalid call of simpleStmt")
  2152  		}
  2153  		return p.newRangeClause(nil, false)
  2154  	}
  2155  
  2156  	if lhs == nil {
  2157  		lhs = p.exprList()
  2158  	}
  2159  
  2160  	if _, ok := lhs.(*ListExpr); !ok && p.tok != _Assign && p.tok != _Define {
  2161  		// expr
  2162  		pos := p.pos()
  2163  		switch p.tok {
  2164  		case _AssignOp:
  2165  			// lhs op= rhs
  2166  			op := p.op
  2167  			p.next()
  2168  			return p.newAssignStmt(pos, op, lhs, p.expr())
  2169  
  2170  		case _IncOp:
  2171  			// lhs++ or lhs--
  2172  			op := p.op
  2173  			p.next()
  2174  			return p.newAssignStmt(pos, op, lhs, nil)
  2175  
  2176  		case _Arrow:
  2177  			// lhs <- rhs
  2178  			s := new(SendStmt)
  2179  			s.pos = pos
  2180  			p.next()
  2181  			s.Chan = lhs
  2182  			s.Value = p.expr()
  2183  			return s
  2184  
  2185  		default:
  2186  			// expr
  2187  			s := new(ExprStmt)
  2188  			s.pos = lhs.Pos()
  2189  			s.X = lhs
  2190  			return s
  2191  		}
  2192  	}
  2193  
  2194  	// expr_list
  2195  	switch p.tok {
  2196  	case _Assign, _Define:
  2197  		pos := p.pos()
  2198  		var op Operator
  2199  		if p.tok == _Define {
  2200  			op = Def
  2201  		}
  2202  		p.next()
  2203  
  2204  		if keyword == _For && p.tok == _Range {
  2205  			// expr_list op= _Range expr
  2206  			return p.newRangeClause(lhs, op == Def)
  2207  		}
  2208  
  2209  		// expr_list op= expr_list
  2210  		rhs := p.exprList()
  2211  
  2212  		if x, ok := rhs.(*TypeSwitchGuard); ok && keyword == _Switch && op == Def {
  2213  			if lhs, ok := lhs.(*Name); ok {
  2214  				// switch … lhs := rhs.(type)
  2215  				x.Lhs = lhs
  2216  				s := new(ExprStmt)
  2217  				s.pos = x.Pos()
  2218  				s.X = x
  2219  				return s
  2220  			}
  2221  		}
  2222  
  2223  		return p.newAssignStmt(pos, op, lhs, rhs)
  2224  
  2225  	default:
  2226  		p.syntaxError("expected := or = or comma")
  2227  		p.advance(_Semi, _Rbrace)
  2228  		// make the best of what we have
  2229  		if x, ok := lhs.(*ListExpr); ok {
  2230  			lhs = x.ElemList[0]
  2231  		}
  2232  		s := new(ExprStmt)
  2233  		s.pos = lhs.Pos()
  2234  		s.X = lhs
  2235  		return s
  2236  	}
  2237  }
  2238  
  2239  func (p *parser) newRangeClause(lhs Expr, def bool) *RangeClause {
  2240  	r := new(RangeClause)
  2241  	r.pos = p.pos()
  2242  	p.next() // consume _Range
  2243  	r.Lhs = lhs
  2244  	r.Def = def
  2245  	r.X = p.expr()
  2246  	return r
  2247  }
  2248  
  2249  func (p *parser) newAssignStmt(pos Pos, op Operator, lhs, rhs Expr) *AssignStmt {
  2250  	a := new(AssignStmt)
  2251  	a.pos = pos
  2252  	a.Op = op
  2253  	a.Lhs = lhs
  2254  	a.Rhs = rhs
  2255  	return a
  2256  }
  2257  
  2258  func (p *parser) labeledStmtOrNil(label *Name) Stmt {
  2259  	if trace {
  2260  		defer p.trace("labeledStmt")()
  2261  	}
  2262  
  2263  	s := new(LabeledStmt)
  2264  	s.pos = p.pos()
  2265  	s.Label = label
  2266  
  2267  	p.want(_Colon)
  2268  
  2269  	if p.tok == _Rbrace {
  2270  		// We expect a statement (incl. an empty statement), which must be
  2271  		// terminated by a semicolon. Because semicolons may be omitted before
  2272  		// an _Rbrace, seeing an _Rbrace implies an empty statement.
  2273  		e := new(EmptyStmt)
  2274  		e.pos = p.pos()
  2275  		s.Stmt = e
  2276  		return s
  2277  	}
  2278  
  2279  	s.Stmt = p.stmtOrNil()
  2280  	if s.Stmt != nil {
  2281  		return s
  2282  	}
  2283  
  2284  	// report error at line of ':' token
  2285  	p.syntaxErrorAt(s.pos, "missing statement after label")
  2286  	// we are already at the end of the labeled statement - no need to advance
  2287  	return nil // avoids follow-on errors (see e.g., fixedbugs/bug274.go)
  2288  }
  2289  
  2290  // context must be a non-empty string unless we know that p.tok == _Lbrace.
  2291  func (p *parser) blockStmt(context string) *BlockStmt {
  2292  	if trace {
  2293  		defer p.trace("blockStmt")()
  2294  	}
  2295  
  2296  	s := new(BlockStmt)
  2297  	s.pos = p.pos()
  2298  
  2299  	// people coming from C may forget that braces are mandatory in Go
  2300  	if !p.got(_Lbrace) {
  2301  		p.syntaxError("expected { after " + context)
  2302  		p.advance(_Name, _Rbrace)
  2303  		s.Rbrace = p.pos() // in case we found "}"
  2304  		if p.got(_Rbrace) {
  2305  			return s
  2306  		}
  2307  	}
  2308  
  2309  	s.List = p.stmtList()
  2310  	s.Rbrace = p.pos()
  2311  	p.want(_Rbrace)
  2312  
  2313  	return s
  2314  }
  2315  
  2316  func (p *parser) declStmt(f func(*Group) Decl) *DeclStmt {
  2317  	if trace {
  2318  		defer p.trace("declStmt")()
  2319  	}
  2320  
  2321  	s := new(DeclStmt)
  2322  	s.pos = p.pos()
  2323  
  2324  	p.next() // _Const, _Type, or _Var
  2325  	s.DeclList = p.appendGroup(nil, f)
  2326  
  2327  	return s
  2328  }
  2329  
  2330  func (p *parser) forStmt() Stmt {
  2331  	if trace {
  2332  		defer p.trace("forStmt")()
  2333  	}
  2334  
  2335  	s := new(ForStmt)
  2336  	s.pos = p.pos()
  2337  
  2338  	s.Init, s.Cond, s.Post = p.header(_For)
  2339  	s.Body = p.blockStmt("for clause")
  2340  
  2341  	return s
  2342  }
  2343  
  2344  func (p *parser) header(keyword token) (init SimpleStmt, cond Expr, post SimpleStmt) {
  2345  	p.want(keyword)
  2346  
  2347  	if p.tok == _Lbrace {
  2348  		if keyword == _If {
  2349  			p.syntaxError("missing condition in if statement")
  2350  			cond = p.badExpr()
  2351  		}
  2352  		return
  2353  	}
  2354  	// p.tok != _Lbrace
  2355  
  2356  	outer := p.xnest
  2357  	p.xnest = -1
  2358  
  2359  	if p.tok != _Semi {
  2360  		// accept potential varDecl but complain
  2361  		if p.got(_Var) {
  2362  			p.syntaxError(fmt.Sprintf("var declaration not allowed in %s initializer", keyword.String()))
  2363  		}
  2364  		init = p.simpleStmt(nil, keyword)
  2365  		// If we have a range clause, we are done (can only happen for keyword == _For).
  2366  		if _, ok := init.(*RangeClause); ok {
  2367  			p.xnest = outer
  2368  			return
  2369  		}
  2370  	}
  2371  
  2372  	var condStmt SimpleStmt
  2373  	var semi struct {
  2374  		pos Pos
  2375  		lit string // valid if pos.IsKnown()
  2376  	}
  2377  	if p.tok != _Lbrace {
  2378  		if p.tok == _Semi {
  2379  			semi.pos = p.pos()
  2380  			semi.lit = p.lit
  2381  			p.next()
  2382  		} else {
  2383  			// asking for a '{' rather than a ';' here leads to a better error message
  2384  			p.want(_Lbrace)
  2385  			if p.tok != _Lbrace {
  2386  				p.advance(_Lbrace, _Rbrace) // for better synchronization (e.g., go.dev/issue/22581)
  2387  			}
  2388  		}
  2389  		if keyword == _For {
  2390  			if p.tok != _Semi {
  2391  				if p.tok == _Lbrace {
  2392  					p.syntaxError("expected for loop condition")
  2393  					goto done
  2394  				}
  2395  				condStmt = p.simpleStmt(nil, 0 /* range not permitted */)
  2396  			}
  2397  			p.want(_Semi)
  2398  			if p.tok != _Lbrace {
  2399  				post = p.simpleStmt(nil, 0 /* range not permitted */)
  2400  				if a, _ := post.(*AssignStmt); a != nil && a.Op == Def {
  2401  					p.syntaxErrorAt(a.Pos(), "cannot declare in post statement of for loop")
  2402  				}
  2403  			}
  2404  		} else if p.tok != _Lbrace {
  2405  			condStmt = p.simpleStmt(nil, keyword)
  2406  		}
  2407  	} else {
  2408  		condStmt = init
  2409  		init = nil
  2410  	}
  2411  
  2412  done:
  2413  	// unpack condStmt
  2414  	switch s := condStmt.(type) {
  2415  	case nil:
  2416  		if keyword == _If && semi.pos.IsKnown() {
  2417  			if semi.lit != "semicolon" {
  2418  				p.syntaxErrorAt(semi.pos, fmt.Sprintf("unexpected %s, expected { after if clause", semi.lit))
  2419  			} else {
  2420  				p.syntaxErrorAt(semi.pos, "missing condition in if statement")
  2421  			}
  2422  			b := new(BadExpr)
  2423  			b.pos = semi.pos
  2424  			cond = b
  2425  		}
  2426  	case *ExprStmt:
  2427  		cond = s.X
  2428  	default:
  2429  		// A common syntax error is to write '=' instead of '==',
  2430  		// which turns an expression into an assignment. Provide
  2431  		// a more explicit error message in that case to prevent
  2432  		// further confusion.
  2433  		var str string
  2434  		if as, ok := s.(*AssignStmt); ok && as.Op == 0 {
  2435  			// Emphasize complex Lhs and Rhs of assignment with parentheses to highlight '='.
  2436  			str = "assignment " + emphasize(as.Lhs) + " = " + emphasize(as.Rhs)
  2437  		} else {
  2438  			str = String(s)
  2439  		}
  2440  		p.syntaxErrorAt(s.Pos(), fmt.Sprintf("cannot use %s as value", str))
  2441  	}
  2442  
  2443  	p.xnest = outer
  2444  	return
  2445  }
  2446  
  2447  // emphasize returns a string representation of x, with (top-level)
  2448  // binary expressions emphasized by enclosing them in parentheses.
  2449  func emphasize(x Expr) string {
  2450  	s := String(x)
  2451  	if op, _ := x.(*Operation); op != nil && op.Y != nil {
  2452  		// binary expression
  2453  		return "(" + s + ")"
  2454  	}
  2455  	return s
  2456  }
  2457  
  2458  func (p *parser) ifStmt() *IfStmt {
  2459  	if trace {
  2460  		defer p.trace("ifStmt")()
  2461  	}
  2462  
  2463  	s := new(IfStmt)
  2464  	s.pos = p.pos()
  2465  
  2466  	s.Init, s.Cond, _ = p.header(_If)
  2467  	s.Then = p.blockStmt("if clause")
  2468  
  2469  	if p.got(_Else) {
  2470  		switch p.tok {
  2471  		case _If:
  2472  			s.Else = p.ifStmt()
  2473  		case _Lbrace:
  2474  			s.Else = p.blockStmt("")
  2475  		default:
  2476  			p.syntaxError("else must be followed by if or statement block")
  2477  			p.advance(_Name, _Rbrace)
  2478  		}
  2479  	}
  2480  
  2481  	return s
  2482  }
  2483  
  2484  func (p *parser) switchStmt() *SwitchStmt {
  2485  	if trace {
  2486  		defer p.trace("switchStmt")()
  2487  	}
  2488  
  2489  	s := new(SwitchStmt)
  2490  	s.pos = p.pos()
  2491  
  2492  	s.Init, s.Tag, _ = p.header(_Switch)
  2493  
  2494  	if !p.got(_Lbrace) {
  2495  		p.syntaxError("missing { after switch clause")
  2496  		p.advance(_Case, _Default, _Rbrace)
  2497  	}
  2498  	for p.tok != _EOF && p.tok != _Rbrace {
  2499  		s.Body = append(s.Body, p.caseClause())
  2500  	}
  2501  	s.Rbrace = p.pos()
  2502  	p.want(_Rbrace)
  2503  
  2504  	return s
  2505  }
  2506  
  2507  func (p *parser) selectStmt() *SelectStmt {
  2508  	if trace {
  2509  		defer p.trace("selectStmt")()
  2510  	}
  2511  
  2512  	s := new(SelectStmt)
  2513  	s.pos = p.pos()
  2514  
  2515  	p.want(_Select)
  2516  	if !p.got(_Lbrace) {
  2517  		p.syntaxError("missing { after select clause")
  2518  		p.advance(_Case, _Default, _Rbrace)
  2519  	}
  2520  	for p.tok != _EOF && p.tok != _Rbrace {
  2521  		s.Body = append(s.Body, p.commClause())
  2522  	}
  2523  	s.Rbrace = p.pos()
  2524  	p.want(_Rbrace)
  2525  
  2526  	return s
  2527  }
  2528  
  2529  func (p *parser) caseClause() *CaseClause {
  2530  	if trace {
  2531  		defer p.trace("caseClause")()
  2532  	}
  2533  
  2534  	c := new(CaseClause)
  2535  	c.pos = p.pos()
  2536  
  2537  	switch p.tok {
  2538  	case _Case:
  2539  		p.next()
  2540  		c.Cases = p.exprList()
  2541  
  2542  	case _Default:
  2543  		p.next()
  2544  
  2545  	default:
  2546  		p.syntaxError("expected case or default or }")
  2547  		p.advance(_Colon, _Case, _Default, _Rbrace)
  2548  	}
  2549  
  2550  	c.Colon = p.pos()
  2551  	p.want(_Colon)
  2552  	c.Body = p.stmtList()
  2553  
  2554  	return c
  2555  }
  2556  
  2557  func (p *parser) commClause() *CommClause {
  2558  	if trace {
  2559  		defer p.trace("commClause")()
  2560  	}
  2561  
  2562  	c := new(CommClause)
  2563  	c.pos = p.pos()
  2564  
  2565  	switch p.tok {
  2566  	case _Case:
  2567  		p.next()
  2568  		c.Comm = p.simpleStmt(nil, 0)
  2569  
  2570  		// The syntax restricts the possible simple statements here to:
  2571  		//
  2572  		//     lhs <- x (send statement)
  2573  		//     <-x
  2574  		//     lhs = <-x
  2575  		//     lhs := <-x
  2576  		//
  2577  		// All these (and more) are recognized by simpleStmt and invalid
  2578  		// syntax trees are flagged later, during type checking.
  2579  
  2580  	case _Default:
  2581  		p.next()
  2582  
  2583  	default:
  2584  		p.syntaxError("expected case or default or }")
  2585  		p.advance(_Colon, _Case, _Default, _Rbrace)
  2586  	}
  2587  
  2588  	c.Colon = p.pos()
  2589  	p.want(_Colon)
  2590  	c.Body = p.stmtList()
  2591  
  2592  	return c
  2593  }
  2594  
  2595  // stmtOrNil parses a statement if one is present, or else returns nil.
  2596  //
  2597  //	Statement =
  2598  //		Declaration | LabeledStmt | SimpleStmt |
  2599  //		GoStmt | ReturnStmt | BreakStmt | ContinueStmt | GotoStmt |
  2600  //		FallthroughStmt | Block | IfStmt | SwitchStmt | SelectStmt | ForStmt |
  2601  //		DeferStmt .
  2602  func (p *parser) stmtOrNil() Stmt {
  2603  	if trace {
  2604  		defer p.trace("stmt " + p.tok.String())()
  2605  	}
  2606  
  2607  	// Most statements (assignments) start with an identifier;
  2608  	// look for it first before doing anything more expensive.
  2609  	if p.tok == _Name {
  2610  		p.clearPragma()
  2611  		lhs := p.exprList()
  2612  		if label, ok := lhs.(*Name); ok && p.tok == _Colon {
  2613  			return p.labeledStmtOrNil(label)
  2614  		}
  2615  		return p.simpleStmt(lhs, 0)
  2616  	}
  2617  
  2618  	switch p.tok {
  2619  	case _Var:
  2620  		return p.declStmt(p.varDecl)
  2621  
  2622  	case _Const:
  2623  		return p.declStmt(p.constDecl)
  2624  
  2625  	case _Type:
  2626  		return p.declStmt(p.typeDecl)
  2627  	}
  2628  
  2629  	p.clearPragma()
  2630  
  2631  	switch p.tok {
  2632  	case _Lbrace:
  2633  		return p.blockStmt("")
  2634  
  2635  	case _Operator, _Star:
  2636  		switch p.op {
  2637  		case Add, Sub, Mul, And, Xor, Not:
  2638  			return p.simpleStmt(nil, 0) // unary operators
  2639  		}
  2640  
  2641  	case _Literal, _Func, _Lparen, // operands
  2642  		_Lbrack, _Struct, _Map, _Chan, _Interface, // composite types
  2643  		_Arrow: // receive operator
  2644  		return p.simpleStmt(nil, 0)
  2645  
  2646  	case _For:
  2647  		return p.forStmt()
  2648  
  2649  	case _Switch:
  2650  		return p.switchStmt()
  2651  
  2652  	case _Select:
  2653  		return p.selectStmt()
  2654  
  2655  	case _If:
  2656  		return p.ifStmt()
  2657  
  2658  	case _Fallthrough:
  2659  		s := new(BranchStmt)
  2660  		s.pos = p.pos()
  2661  		p.next()
  2662  		s.Tok = _Fallthrough
  2663  		return s
  2664  
  2665  	case _Break, _Continue:
  2666  		s := new(BranchStmt)
  2667  		s.pos = p.pos()
  2668  		s.Tok = p.tok
  2669  		p.next()
  2670  		if p.tok == _Name {
  2671  			s.Label = p.name()
  2672  		}
  2673  		return s
  2674  
  2675  	case _Go, _Defer:
  2676  		return p.callStmt()
  2677  
  2678  	case _Goto:
  2679  		s := new(BranchStmt)
  2680  		s.pos = p.pos()
  2681  		s.Tok = _Goto
  2682  		p.next()
  2683  		s.Label = p.name()
  2684  		return s
  2685  
  2686  	case _Return:
  2687  		s := new(ReturnStmt)
  2688  		s.pos = p.pos()
  2689  		p.next()
  2690  		if p.tok != _Semi && p.tok != _Rbrace {
  2691  			s.Results = p.exprList()
  2692  		}
  2693  		return s
  2694  
  2695  	case _Semi:
  2696  		s := new(EmptyStmt)
  2697  		s.pos = p.pos()
  2698  		return s
  2699  	}
  2700  
  2701  	return nil
  2702  }
  2703  
  2704  // StatementList = { Statement ";" } .
  2705  func (p *parser) stmtList() (l []Stmt) {
  2706  	if trace {
  2707  		defer p.trace("stmtList")()
  2708  	}
  2709  
  2710  	for p.tok != _EOF && p.tok != _Rbrace && p.tok != _Case && p.tok != _Default {
  2711  		s := p.stmtOrNil()
  2712  		p.clearPragma()
  2713  		if s == nil {
  2714  			break
  2715  		}
  2716  		l = append(l, s)
  2717  		// ";" is optional before "}"
  2718  		if !p.got(_Semi) && p.tok != _Rbrace {
  2719  			p.syntaxError("at end of statement")
  2720  			p.advance(_Semi, _Rbrace, _Case, _Default)
  2721  			p.got(_Semi) // avoid spurious empty statement
  2722  		}
  2723  	}
  2724  	return
  2725  }
  2726  
  2727  // argList parses a possibly empty, comma-separated list of arguments,
  2728  // optionally followed by a comma (if not empty), and closed by ")".
  2729  // The last argument may be followed by "...".
  2730  //
  2731  // argList = [ arg { "," arg } [ "..." ] [ "," ] ] ")" .
  2732  func (p *parser) argList() (list []Expr, hasDots bool) {
  2733  	if trace {
  2734  		defer p.trace("argList")()
  2735  	}
  2736  
  2737  	p.xnest++
  2738  	p.list("argument list", _Comma, _Rparen, func() bool {
  2739  		list = append(list, p.expr())
  2740  		hasDots = p.got(_DotDotDot)
  2741  		return hasDots
  2742  	})
  2743  	p.xnest--
  2744  
  2745  	return
  2746  }
  2747  
  2748  // ----------------------------------------------------------------------------
  2749  // Common productions
  2750  
  2751  func (p *parser) name() *Name {
  2752  	// no tracing to avoid overly verbose output
  2753  
  2754  	if p.tok == _Name {
  2755  		n := NewName(p.pos(), p.lit)
  2756  		p.next()
  2757  		return n
  2758  	}
  2759  
  2760  	n := NewName(p.pos(), "_")
  2761  	p.syntaxError("expected name")
  2762  	p.advance()
  2763  	return n
  2764  }
  2765  
  2766  // IdentifierList = identifier { "," identifier } .
  2767  // The first name must be provided.
  2768  func (p *parser) nameList(first *Name) []*Name {
  2769  	if trace {
  2770  		defer p.trace("nameList")()
  2771  	}
  2772  
  2773  	if debug && first == nil {
  2774  		panic("first name not provided")
  2775  	}
  2776  
  2777  	l := []*Name{first}
  2778  	for p.got(_Comma) {
  2779  		l = append(l, p.name())
  2780  	}
  2781  
  2782  	return l
  2783  }
  2784  
  2785  // The first name may be provided, or nil.
  2786  func (p *parser) qualifiedName(name *Name) Expr {
  2787  	if trace {
  2788  		defer p.trace("qualifiedName")()
  2789  	}
  2790  
  2791  	var x Expr
  2792  	switch {
  2793  	case name != nil:
  2794  		x = name
  2795  	case p.tok == _Name:
  2796  		x = p.name()
  2797  	default:
  2798  		x = NewName(p.pos(), "_")
  2799  		p.syntaxError("expected name")
  2800  		p.advance(_Dot, _Semi, _Rbrace)
  2801  	}
  2802  
  2803  	if p.tok == _Dot {
  2804  		s := new(SelectorExpr)
  2805  		s.pos = p.pos()
  2806  		p.next()
  2807  		s.X = x
  2808  		s.Sel = p.name()
  2809  		x = s
  2810  	}
  2811  
  2812  	if p.tok == _Lbrack {
  2813  		x = p.typeInstance(x)
  2814  	}
  2815  
  2816  	return x
  2817  }
  2818  
  2819  // ExpressionList = Expression { "," Expression } .
  2820  func (p *parser) exprList() Expr {
  2821  	if trace {
  2822  		defer p.trace("exprList")()
  2823  	}
  2824  
  2825  	x := p.expr()
  2826  	if p.got(_Comma) {
  2827  		list := []Expr{x, p.expr()}
  2828  		for p.got(_Comma) {
  2829  			list = append(list, p.expr())
  2830  		}
  2831  		t := new(ListExpr)
  2832  		t.pos = x.Pos()
  2833  		t.ElemList = list
  2834  		x = t
  2835  	}
  2836  	return x
  2837  }
  2838  
  2839  // typeList parses a non-empty, comma-separated list of types,
  2840  // optionally followed by a comma. If strict is set to false,
  2841  // the first element may also be a (non-type) expression.
  2842  // If there is more than one argument, the result is a *ListExpr.
  2843  // The comma result indicates whether there was a (separating or
  2844  // trailing) comma.
  2845  //
  2846  // typeList = arg { "," arg } [ "," ] .
  2847  func (p *parser) typeList(strict bool) (x Expr, comma bool) {
  2848  	if trace {
  2849  		defer p.trace("typeList")()
  2850  	}
  2851  
  2852  	p.xnest++
  2853  	if strict {
  2854  		x = p.type_()
  2855  	} else {
  2856  		x = p.expr()
  2857  	}
  2858  	if p.got(_Comma) {
  2859  		comma = true
  2860  		if t := p.typeOrNil(); t != nil {
  2861  			list := []Expr{x, t}
  2862  			for p.got(_Comma) {
  2863  				if t = p.typeOrNil(); t == nil {
  2864  					break
  2865  				}
  2866  				list = append(list, t)
  2867  			}
  2868  			l := new(ListExpr)
  2869  			l.pos = x.Pos() // == list[0].Pos()
  2870  			l.ElemList = list
  2871  			x = l
  2872  		}
  2873  	}
  2874  	p.xnest--
  2875  	return
  2876  }
  2877  
  2878  // Unparen returns e with any enclosing parentheses stripped.
  2879  func Unparen(x Expr) Expr {
  2880  	for {
  2881  		p, ok := x.(*ParenExpr)
  2882  		if !ok {
  2883  			break
  2884  		}
  2885  		x = p.X
  2886  	}
  2887  	return x
  2888  }
  2889  
  2890  // UnpackListExpr unpacks a *ListExpr into a []Expr.
  2891  func UnpackListExpr(x Expr) []Expr {
  2892  	switch x := x.(type) {
  2893  	case nil:
  2894  		return nil
  2895  	case *ListExpr:
  2896  		return x.ElemList
  2897  	default:
  2898  		return []Expr{x}
  2899  	}
  2900  }
  2901  

View as plain text