Source file src/go/parser/parser.go

     1  // Copyright 2009 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 parser implements a parser for Go source files. Input may be
     6  // provided in a variety of forms (see the various Parse* functions); the
     7  // output is an abstract syntax tree (AST) representing the Go source. The
     8  // parser is invoked through one of the Parse* functions.
     9  //
    10  // The parser accepts a larger language than is syntactically permitted by
    11  // the Go spec, for simplicity, and for improved robustness in the presence
    12  // of syntax errors. For instance, in method declarations, the receiver is
    13  // treated like an ordinary parameter list and thus may contain multiple
    14  // entries where the spec permits exactly one. Consequently, the corresponding
    15  // field in the AST (ast.FuncDecl.Recv) field is not restricted to one entry.
    16  package parser
    17  
    18  import (
    19  	"fmt"
    20  	"go/ast"
    21  	"go/build/constraint"
    22  	"go/scanner"
    23  	"go/token"
    24  	"strings"
    25  )
    26  
    27  // The parser structure holds the parser's internal state.
    28  type parser struct {
    29  	file    *token.File
    30  	errors  scanner.ErrorList
    31  	scanner scanner.Scanner
    32  
    33  	// Tracing/debugging
    34  	mode   Mode // parsing mode
    35  	trace  bool // == (mode&Trace != 0)
    36  	indent int  // indentation used for tracing output
    37  
    38  	// Comments
    39  	comments    []*ast.CommentGroup
    40  	leadComment *ast.CommentGroup // last lead comment
    41  	lineComment *ast.CommentGroup // last line comment
    42  	top         bool              // in top of file (before package clause)
    43  	goVersion   string            // minimum Go version found in //go:build comment
    44  
    45  	// Next token
    46  	pos token.Pos   // token position
    47  	tok token.Token // one token look-ahead
    48  	lit string      // token literal
    49  
    50  	// Error recovery
    51  	// (used to limit the number of calls to parser.advance
    52  	// w/o making scanning progress - avoids potential endless
    53  	// loops across multiple parser functions during error recovery)
    54  	syncPos token.Pos // last synchronization position
    55  	syncCnt int       // number of parser.advance calls without progress
    56  
    57  	// Non-syntactic parser control
    58  	exprLev int  // < 0: in control clause, >= 0: in expression
    59  	inRhs   bool // if set, the parser is parsing a rhs expression
    60  
    61  	imports []*ast.ImportSpec // list of imports
    62  
    63  	// nestLev is used to track and limit the recursion depth
    64  	// during parsing.
    65  	nestLev int
    66  }
    67  
    68  func (p *parser) init(file *token.File, src []byte, mode Mode) {
    69  	p.file = file
    70  	eh := func(pos token.Position, msg string) { p.errors.Add(pos, msg) }
    71  	p.scanner.Init(p.file, src, eh, scanner.ScanComments)
    72  
    73  	p.top = true
    74  	p.mode = mode
    75  	p.trace = mode&Trace != 0 // for convenience (p.trace is used frequently)
    76  	p.next()
    77  }
    78  
    79  // ----------------------------------------------------------------------------
    80  // Parsing support
    81  
    82  func (p *parser) printTrace(a ...any) {
    83  	const dots = ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
    84  	const n = len(dots)
    85  	pos := p.file.Position(p.pos)
    86  	fmt.Printf("%5d:%3d: ", pos.Line, pos.Column)
    87  	i := 2 * p.indent
    88  	for i > n {
    89  		fmt.Print(dots)
    90  		i -= n
    91  	}
    92  	// i <= n
    93  	fmt.Print(dots[0:i])
    94  	fmt.Println(a...)
    95  }
    96  
    97  func trace(p *parser, msg string) *parser {
    98  	p.printTrace(msg, "(")
    99  	p.indent++
   100  	return p
   101  }
   102  
   103  // Usage pattern: defer un(trace(p, "..."))
   104  func un(p *parser) {
   105  	p.indent--
   106  	p.printTrace(")")
   107  }
   108  
   109  // maxNestLev is the deepest we're willing to recurse during parsing
   110  const maxNestLev int = 1e5
   111  
   112  func incNestLev(p *parser) *parser {
   113  	p.nestLev++
   114  	if p.nestLev > maxNestLev {
   115  		p.error(p.pos, "exceeded max nesting depth")
   116  		panic(bailout{})
   117  	}
   118  	return p
   119  }
   120  
   121  // decNestLev is used to track nesting depth during parsing to prevent stack exhaustion.
   122  // It is used along with incNestLev in a similar fashion to how un and trace are used.
   123  func decNestLev(p *parser) {
   124  	p.nestLev--
   125  }
   126  
   127  // Advance to the next token.
   128  func (p *parser) next0() {
   129  	// Because of one-token look-ahead, print the previous token
   130  	// when tracing as it provides a more readable output. The
   131  	// very first token (!p.pos.IsValid()) is not initialized
   132  	// (it is token.ILLEGAL), so don't print it.
   133  	if p.trace && p.pos.IsValid() {
   134  		s := p.tok.String()
   135  		switch {
   136  		case p.tok.IsLiteral():
   137  			p.printTrace(s, p.lit)
   138  		case p.tok.IsOperator(), p.tok.IsKeyword():
   139  			p.printTrace("\"" + s + "\"")
   140  		default:
   141  			p.printTrace(s)
   142  		}
   143  	}
   144  
   145  	for {
   146  		p.pos, p.tok, p.lit = p.scanner.Scan()
   147  		if p.tok == token.COMMENT {
   148  			if p.top && strings.HasPrefix(p.lit, "//go:build") {
   149  				if x, err := constraint.Parse(p.lit); err == nil {
   150  					p.goVersion = constraint.GoVersion(x)
   151  				}
   152  			}
   153  			if p.mode&ParseComments == 0 {
   154  				continue
   155  			}
   156  		} else {
   157  			// Found a non-comment; top of file is over.
   158  			p.top = false
   159  		}
   160  		break
   161  	}
   162  }
   163  
   164  // Consume a comment and return it and the line on which it ends.
   165  func (p *parser) consumeComment() (comment *ast.Comment, endline int) {
   166  	// /*-style comments may end on a different line than where they start.
   167  	// Scan the comment for '\n' chars and adjust endline accordingly.
   168  	endline = p.file.Line(p.pos)
   169  	if p.lit[1] == '*' {
   170  		// don't use range here - no need to decode Unicode code points
   171  		for i := 0; i < len(p.lit); i++ {
   172  			if p.lit[i] == '\n' {
   173  				endline++
   174  			}
   175  		}
   176  	}
   177  
   178  	comment = &ast.Comment{Slash: p.pos, Text: p.lit}
   179  	p.next0()
   180  
   181  	return
   182  }
   183  
   184  // Consume a group of adjacent comments, add it to the parser's
   185  // comments list, and return it together with the line at which
   186  // the last comment in the group ends. A non-comment token or n
   187  // empty lines terminate a comment group.
   188  func (p *parser) consumeCommentGroup(n int) (comments *ast.CommentGroup, endline int) {
   189  	var list []*ast.Comment
   190  	endline = p.file.Line(p.pos)
   191  	for p.tok == token.COMMENT && p.file.Line(p.pos) <= endline+n {
   192  		var comment *ast.Comment
   193  		comment, endline = p.consumeComment()
   194  		list = append(list, comment)
   195  	}
   196  
   197  	// add comment group to the comments list
   198  	comments = &ast.CommentGroup{List: list}
   199  	p.comments = append(p.comments, comments)
   200  
   201  	return
   202  }
   203  
   204  // Advance to the next non-comment token. In the process, collect
   205  // any comment groups encountered, and remember the last lead and
   206  // line comments.
   207  //
   208  // A lead comment is a comment group that starts and ends in a
   209  // line without any other tokens and that is followed by a non-comment
   210  // token on the line immediately after the comment group.
   211  //
   212  // A line comment is a comment group that follows a non-comment
   213  // token on the same line, and that has no tokens after it on the line
   214  // where it ends.
   215  //
   216  // Lead and line comments may be considered documentation that is
   217  // stored in the AST.
   218  func (p *parser) next() {
   219  	p.leadComment = nil
   220  	p.lineComment = nil
   221  	prev := p.pos
   222  	p.next0()
   223  
   224  	if p.tok == token.COMMENT {
   225  		var comment *ast.CommentGroup
   226  		var endline int
   227  
   228  		if p.file.Line(p.pos) == p.file.Line(prev) {
   229  			// The comment is on same line as the previous token; it
   230  			// cannot be a lead comment but may be a line comment.
   231  			comment, endline = p.consumeCommentGroup(0)
   232  			if p.file.Line(p.pos) != endline || p.tok == token.SEMICOLON || p.tok == token.EOF {
   233  				// The next token is on a different line, thus
   234  				// the last comment group is a line comment.
   235  				p.lineComment = comment
   236  			}
   237  		}
   238  
   239  		// consume successor comments, if any
   240  		endline = -1
   241  		for p.tok == token.COMMENT {
   242  			comment, endline = p.consumeCommentGroup(1)
   243  		}
   244  
   245  		if endline+1 == p.file.Line(p.pos) {
   246  			// The next token is following on the line immediately after the
   247  			// comment group, thus the last comment group is a lead comment.
   248  			p.leadComment = comment
   249  		}
   250  	}
   251  }
   252  
   253  // A bailout panic is raised to indicate early termination. pos and msg are
   254  // only populated when bailing out of object resolution.
   255  type bailout struct {
   256  	pos token.Pos
   257  	msg string
   258  }
   259  
   260  func (p *parser) error(pos token.Pos, msg string) {
   261  	if p.trace {
   262  		defer un(trace(p, "error: "+msg))
   263  	}
   264  
   265  	epos := p.file.Position(pos)
   266  
   267  	// If AllErrors is not set, discard errors reported on the same line
   268  	// as the last recorded error and stop parsing if there are more than
   269  	// 10 errors.
   270  	if p.mode&AllErrors == 0 {
   271  		n := len(p.errors)
   272  		if n > 0 && p.errors[n-1].Pos.Line == epos.Line {
   273  			return // discard - likely a spurious error
   274  		}
   275  		if n > 10 {
   276  			panic(bailout{})
   277  		}
   278  	}
   279  
   280  	p.errors.Add(epos, msg)
   281  }
   282  
   283  func (p *parser) errorExpected(pos token.Pos, msg string) {
   284  	msg = "expected " + msg
   285  	if pos == p.pos {
   286  		// the error happened at the current position;
   287  		// make the error message more specific
   288  		switch {
   289  		case p.tok == token.SEMICOLON && p.lit == "\n":
   290  			msg += ", found newline"
   291  		case p.tok.IsLiteral():
   292  			// print 123 rather than 'INT', etc.
   293  			msg += ", found " + p.lit
   294  		default:
   295  			msg += ", found '" + p.tok.String() + "'"
   296  		}
   297  	}
   298  	p.error(pos, msg)
   299  }
   300  
   301  func (p *parser) expect(tok token.Token) token.Pos {
   302  	pos := p.pos
   303  	if p.tok != tok {
   304  		p.errorExpected(pos, "'"+tok.String()+"'")
   305  	}
   306  	p.next() // make progress
   307  	return pos
   308  }
   309  
   310  // expect2 is like expect, but it returns an invalid position
   311  // if the expected token is not found.
   312  func (p *parser) expect2(tok token.Token) (pos token.Pos) {
   313  	if p.tok == tok {
   314  		pos = p.pos
   315  	} else {
   316  		p.errorExpected(p.pos, "'"+tok.String()+"'")
   317  	}
   318  	p.next() // make progress
   319  	return
   320  }
   321  
   322  // expectClosing is like expect but provides a better error message
   323  // for the common case of a missing comma before a newline.
   324  func (p *parser) expectClosing(tok token.Token, context string) token.Pos {
   325  	if p.tok != tok && p.tok == token.SEMICOLON && p.lit == "\n" {
   326  		p.error(p.pos, "missing ',' before newline in "+context)
   327  		p.next()
   328  	}
   329  	return p.expect(tok)
   330  }
   331  
   332  // expectSemi consumes a semicolon and returns the applicable line comment.
   333  func (p *parser) expectSemi() (comment *ast.CommentGroup) {
   334  	// semicolon is optional before a closing ')' or '}'
   335  	if p.tok != token.RPAREN && p.tok != token.RBRACE {
   336  		switch p.tok {
   337  		case token.COMMA:
   338  			// permit a ',' instead of a ';' but complain
   339  			p.errorExpected(p.pos, "';'")
   340  			fallthrough
   341  		case token.SEMICOLON:
   342  			if p.lit == ";" {
   343  				// explicit semicolon
   344  				p.next()
   345  				comment = p.lineComment // use following comments
   346  			} else {
   347  				// artificial semicolon
   348  				comment = p.lineComment // use preceding comments
   349  				p.next()
   350  			}
   351  			return comment
   352  		default:
   353  			p.errorExpected(p.pos, "';'")
   354  			p.advance(stmtStart)
   355  		}
   356  	}
   357  	return nil
   358  }
   359  
   360  func (p *parser) atComma(context string, follow token.Token) bool {
   361  	if p.tok == token.COMMA {
   362  		return true
   363  	}
   364  	if p.tok != follow {
   365  		msg := "missing ','"
   366  		if p.tok == token.SEMICOLON && p.lit == "\n" {
   367  			msg += " before newline"
   368  		}
   369  		p.error(p.pos, msg+" in "+context)
   370  		return true // "insert" comma and continue
   371  	}
   372  	return false
   373  }
   374  
   375  func assert(cond bool, msg string) {
   376  	if !cond {
   377  		panic("go/parser internal error: " + msg)
   378  	}
   379  }
   380  
   381  // advance consumes tokens until the current token p.tok
   382  // is in the 'to' set, or token.EOF. For error recovery.
   383  func (p *parser) advance(to map[token.Token]bool) {
   384  	for ; p.tok != token.EOF; p.next() {
   385  		if to[p.tok] {
   386  			// Return only if parser made some progress since last
   387  			// sync or if it has not reached 10 advance calls without
   388  			// progress. Otherwise consume at least one token to
   389  			// avoid an endless parser loop (it is possible that
   390  			// both parseOperand and parseStmt call advance and
   391  			// correctly do not advance, thus the need for the
   392  			// invocation limit p.syncCnt).
   393  			if p.pos == p.syncPos && p.syncCnt < 10 {
   394  				p.syncCnt++
   395  				return
   396  			}
   397  			if p.pos > p.syncPos {
   398  				p.syncPos = p.pos
   399  				p.syncCnt = 0
   400  				return
   401  			}
   402  			// Reaching here indicates a parser bug, likely an
   403  			// incorrect token list in this function, but it only
   404  			// leads to skipping of possibly correct code if a
   405  			// previous error is present, and thus is preferred
   406  			// over a non-terminating parse.
   407  		}
   408  	}
   409  }
   410  
   411  var stmtStart = map[token.Token]bool{
   412  	token.BREAK:       true,
   413  	token.CONST:       true,
   414  	token.CONTINUE:    true,
   415  	token.DEFER:       true,
   416  	token.FALLTHROUGH: true,
   417  	token.FOR:         true,
   418  	token.GO:          true,
   419  	token.GOTO:        true,
   420  	token.IF:          true,
   421  	token.RETURN:      true,
   422  	token.SELECT:      true,
   423  	token.SWITCH:      true,
   424  	token.TYPE:        true,
   425  	token.VAR:         true,
   426  }
   427  
   428  var declStart = map[token.Token]bool{
   429  	token.IMPORT: true,
   430  	token.CONST:  true,
   431  	token.TYPE:   true,
   432  	token.VAR:    true,
   433  }
   434  
   435  var exprEnd = map[token.Token]bool{
   436  	token.COMMA:     true,
   437  	token.COLON:     true,
   438  	token.SEMICOLON: true,
   439  	token.RPAREN:    true,
   440  	token.RBRACK:    true,
   441  	token.RBRACE:    true,
   442  }
   443  
   444  // safePos returns a valid file position for a given position: If pos
   445  // is valid to begin with, safePos returns pos. If pos is out-of-range,
   446  // safePos returns the EOF position.
   447  //
   448  // This is hack to work around "artificial" end positions in the AST which
   449  // are computed by adding 1 to (presumably valid) token positions. If the
   450  // token positions are invalid due to parse errors, the resulting end position
   451  // may be past the file's EOF position, which would lead to panics if used
   452  // later on.
   453  func (p *parser) safePos(pos token.Pos) (res token.Pos) {
   454  	defer func() {
   455  		if recover() != nil {
   456  			res = token.Pos(p.file.Base() + p.file.Size()) // EOF position
   457  		}
   458  	}()
   459  	_ = p.file.Offset(pos) // trigger a panic if position is out-of-range
   460  	return pos
   461  }
   462  
   463  // ----------------------------------------------------------------------------
   464  // Identifiers
   465  
   466  func (p *parser) parseIdent() *ast.Ident {
   467  	pos := p.pos
   468  	name := "_"
   469  	if p.tok == token.IDENT {
   470  		name = p.lit
   471  		p.next()
   472  	} else {
   473  		p.expect(token.IDENT) // use expect() error handling
   474  	}
   475  	return &ast.Ident{NamePos: pos, Name: name}
   476  }
   477  
   478  func (p *parser) parseIdentList() (list []*ast.Ident) {
   479  	if p.trace {
   480  		defer un(trace(p, "IdentList"))
   481  	}
   482  
   483  	list = append(list, p.parseIdent())
   484  	for p.tok == token.COMMA {
   485  		p.next()
   486  		list = append(list, p.parseIdent())
   487  	}
   488  
   489  	return
   490  }
   491  
   492  // ----------------------------------------------------------------------------
   493  // Common productions
   494  
   495  // If lhs is set, result list elements which are identifiers are not resolved.
   496  func (p *parser) parseExprList() (list []ast.Expr) {
   497  	if p.trace {
   498  		defer un(trace(p, "ExpressionList"))
   499  	}
   500  
   501  	list = append(list, p.parseExpr())
   502  	for p.tok == token.COMMA {
   503  		p.next()
   504  		list = append(list, p.parseExpr())
   505  	}
   506  
   507  	return
   508  }
   509  
   510  func (p *parser) parseList(inRhs bool) []ast.Expr {
   511  	old := p.inRhs
   512  	p.inRhs = inRhs
   513  	list := p.parseExprList()
   514  	p.inRhs = old
   515  	return list
   516  }
   517  
   518  // ----------------------------------------------------------------------------
   519  // Types
   520  
   521  func (p *parser) parseType() ast.Expr {
   522  	if p.trace {
   523  		defer un(trace(p, "Type"))
   524  	}
   525  
   526  	typ := p.tryIdentOrType()
   527  
   528  	if typ == nil {
   529  		pos := p.pos
   530  		p.errorExpected(pos, "type")
   531  		p.advance(exprEnd)
   532  		return &ast.BadExpr{From: pos, To: p.pos}
   533  	}
   534  
   535  	return typ
   536  }
   537  
   538  func (p *parser) parseQualifiedIdent(ident *ast.Ident) ast.Expr {
   539  	if p.trace {
   540  		defer un(trace(p, "QualifiedIdent"))
   541  	}
   542  
   543  	typ := p.parseTypeName(ident)
   544  	if p.tok == token.LBRACK {
   545  		typ = p.parseTypeInstance(typ)
   546  	}
   547  
   548  	return typ
   549  }
   550  
   551  // If the result is an identifier, it is not resolved.
   552  func (p *parser) parseTypeName(ident *ast.Ident) ast.Expr {
   553  	if p.trace {
   554  		defer un(trace(p, "TypeName"))
   555  	}
   556  
   557  	if ident == nil {
   558  		ident = p.parseIdent()
   559  	}
   560  
   561  	if p.tok == token.PERIOD {
   562  		// ident is a package name
   563  		p.next()
   564  		sel := p.parseIdent()
   565  		return &ast.SelectorExpr{X: ident, Sel: sel}
   566  	}
   567  
   568  	return ident
   569  }
   570  
   571  // "[" has already been consumed, and lbrack is its position.
   572  // If len != nil it is the already consumed array length.
   573  func (p *parser) parseArrayType(lbrack token.Pos, len ast.Expr) *ast.ArrayType {
   574  	if p.trace {
   575  		defer un(trace(p, "ArrayType"))
   576  	}
   577  
   578  	if len == nil {
   579  		p.exprLev++
   580  		// always permit ellipsis for more fault-tolerant parsing
   581  		if p.tok == token.ELLIPSIS {
   582  			len = &ast.Ellipsis{Ellipsis: p.pos}
   583  			p.next()
   584  		} else if p.tok != token.RBRACK {
   585  			len = p.parseRhs()
   586  		}
   587  		p.exprLev--
   588  	}
   589  	if p.tok == token.COMMA {
   590  		// Trailing commas are accepted in type parameter
   591  		// lists but not in array type declarations.
   592  		// Accept for better error handling but complain.
   593  		p.error(p.pos, "unexpected comma; expecting ]")
   594  		p.next()
   595  	}
   596  	p.expect(token.RBRACK)
   597  	elt := p.parseType()
   598  	return &ast.ArrayType{Lbrack: lbrack, Len: len, Elt: elt}
   599  }
   600  
   601  func (p *parser) parseArrayFieldOrTypeInstance(x *ast.Ident) (*ast.Ident, ast.Expr) {
   602  	if p.trace {
   603  		defer un(trace(p, "ArrayFieldOrTypeInstance"))
   604  	}
   605  
   606  	lbrack := p.expect(token.LBRACK)
   607  	trailingComma := token.NoPos // if valid, the position of a trailing comma preceding the ']'
   608  	var args []ast.Expr
   609  	if p.tok != token.RBRACK {
   610  		p.exprLev++
   611  		args = append(args, p.parseRhs())
   612  		for p.tok == token.COMMA {
   613  			comma := p.pos
   614  			p.next()
   615  			if p.tok == token.RBRACK {
   616  				trailingComma = comma
   617  				break
   618  			}
   619  			args = append(args, p.parseRhs())
   620  		}
   621  		p.exprLev--
   622  	}
   623  	rbrack := p.expect(token.RBRACK)
   624  
   625  	if len(args) == 0 {
   626  		// x []E
   627  		elt := p.parseType()
   628  		return x, &ast.ArrayType{Lbrack: lbrack, Elt: elt}
   629  	}
   630  
   631  	// x [P]E or x[P]
   632  	if len(args) == 1 {
   633  		elt := p.tryIdentOrType()
   634  		if elt != nil {
   635  			// x [P]E
   636  			if trailingComma.IsValid() {
   637  				// Trailing commas are invalid in array type fields.
   638  				p.error(trailingComma, "unexpected comma; expecting ]")
   639  			}
   640  			return x, &ast.ArrayType{Lbrack: lbrack, Len: args[0], Elt: elt}
   641  		}
   642  	}
   643  
   644  	// x[P], x[P1, P2], ...
   645  	return nil, packIndexExpr(x, lbrack, args, rbrack)
   646  }
   647  
   648  func (p *parser) parseFieldDecl() *ast.Field {
   649  	if p.trace {
   650  		defer un(trace(p, "FieldDecl"))
   651  	}
   652  
   653  	doc := p.leadComment
   654  
   655  	var names []*ast.Ident
   656  	var typ ast.Expr
   657  	switch p.tok {
   658  	case token.IDENT:
   659  		name := p.parseIdent()
   660  		if p.tok == token.PERIOD || p.tok == token.STRING || p.tok == token.SEMICOLON || p.tok == token.RBRACE {
   661  			// embedded type
   662  			typ = name
   663  			if p.tok == token.PERIOD {
   664  				typ = p.parseQualifiedIdent(name)
   665  			}
   666  		} else {
   667  			// name1, name2, ... T
   668  			names = []*ast.Ident{name}
   669  			for p.tok == token.COMMA {
   670  				p.next()
   671  				names = append(names, p.parseIdent())
   672  			}
   673  			// Careful dance: We don't know if we have an embedded instantiated
   674  			// type T[P1, P2, ...] or a field T of array type []E or [P]E.
   675  			if len(names) == 1 && p.tok == token.LBRACK {
   676  				name, typ = p.parseArrayFieldOrTypeInstance(name)
   677  				if name == nil {
   678  					names = nil
   679  				}
   680  			} else {
   681  				// T P
   682  				typ = p.parseType()
   683  			}
   684  		}
   685  	case token.MUL:
   686  		star := p.pos
   687  		p.next()
   688  		if p.tok == token.LPAREN {
   689  			// *(T)
   690  			p.error(p.pos, "cannot parenthesize embedded type")
   691  			p.next()
   692  			typ = p.parseQualifiedIdent(nil)
   693  			// expect closing ')' but no need to complain if missing
   694  			if p.tok == token.RPAREN {
   695  				p.next()
   696  			}
   697  		} else {
   698  			// *T
   699  			typ = p.parseQualifiedIdent(nil)
   700  		}
   701  		typ = &ast.StarExpr{Star: star, X: typ}
   702  
   703  	case token.LPAREN:
   704  		p.error(p.pos, "cannot parenthesize embedded type")
   705  		p.next()
   706  		if p.tok == token.MUL {
   707  			// (*T)
   708  			star := p.pos
   709  			p.next()
   710  			typ = &ast.StarExpr{Star: star, X: p.parseQualifiedIdent(nil)}
   711  		} else {
   712  			// (T)
   713  			typ = p.parseQualifiedIdent(nil)
   714  		}
   715  		// expect closing ')' but no need to complain if missing
   716  		if p.tok == token.RPAREN {
   717  			p.next()
   718  		}
   719  
   720  	default:
   721  		pos := p.pos
   722  		p.errorExpected(pos, "field name or embedded type")
   723  		p.advance(exprEnd)
   724  		typ = &ast.BadExpr{From: pos, To: p.pos}
   725  	}
   726  
   727  	var tag *ast.BasicLit
   728  	if p.tok == token.STRING {
   729  		tag = &ast.BasicLit{ValuePos: p.pos, Kind: p.tok, Value: p.lit}
   730  		p.next()
   731  	}
   732  
   733  	comment := p.expectSemi()
   734  
   735  	field := &ast.Field{Doc: doc, Names: names, Type: typ, Tag: tag, Comment: comment}
   736  	return field
   737  }
   738  
   739  func (p *parser) parseStructType() *ast.StructType {
   740  	if p.trace {
   741  		defer un(trace(p, "StructType"))
   742  	}
   743  
   744  	pos := p.expect(token.STRUCT)
   745  	lbrace := p.expect(token.LBRACE)
   746  	var list []*ast.Field
   747  	for p.tok == token.IDENT || p.tok == token.MUL || p.tok == token.LPAREN {
   748  		// a field declaration cannot start with a '(' but we accept
   749  		// it here for more robust parsing and better error messages
   750  		// (parseFieldDecl will check and complain if necessary)
   751  		list = append(list, p.parseFieldDecl())
   752  	}
   753  	rbrace := p.expect(token.RBRACE)
   754  
   755  	return &ast.StructType{
   756  		Struct: pos,
   757  		Fields: &ast.FieldList{
   758  			Opening: lbrace,
   759  			List:    list,
   760  			Closing: rbrace,
   761  		},
   762  	}
   763  }
   764  
   765  func (p *parser) parsePointerType() *ast.StarExpr {
   766  	if p.trace {
   767  		defer un(trace(p, "PointerType"))
   768  	}
   769  
   770  	star := p.expect(token.MUL)
   771  	base := p.parseType()
   772  
   773  	return &ast.StarExpr{Star: star, X: base}
   774  }
   775  
   776  func (p *parser) parseDotsType() *ast.Ellipsis {
   777  	if p.trace {
   778  		defer un(trace(p, "DotsType"))
   779  	}
   780  
   781  	pos := p.expect(token.ELLIPSIS)
   782  	elt := p.parseType()
   783  
   784  	return &ast.Ellipsis{Ellipsis: pos, Elt: elt}
   785  }
   786  
   787  type field struct {
   788  	name *ast.Ident
   789  	typ  ast.Expr
   790  }
   791  
   792  func (p *parser) parseParamDecl(name *ast.Ident, typeSetsOK bool) (f field) {
   793  	// TODO(rFindley) refactor to be more similar to paramDeclOrNil in the syntax
   794  	// package
   795  	if p.trace {
   796  		defer un(trace(p, "ParamDeclOrNil"))
   797  	}
   798  
   799  	ptok := p.tok
   800  	if name != nil {
   801  		p.tok = token.IDENT // force token.IDENT case in switch below
   802  	} else if typeSetsOK && p.tok == token.TILDE {
   803  		// "~" ...
   804  		return field{nil, p.embeddedElem(nil)}
   805  	}
   806  
   807  	switch p.tok {
   808  	case token.IDENT:
   809  		// name
   810  		if name != nil {
   811  			f.name = name
   812  			p.tok = ptok
   813  		} else {
   814  			f.name = p.parseIdent()
   815  		}
   816  		switch p.tok {
   817  		case token.IDENT, token.MUL, token.ARROW, token.FUNC, token.CHAN, token.MAP, token.STRUCT, token.INTERFACE, token.LPAREN:
   818  			// name type
   819  			f.typ = p.parseType()
   820  
   821  		case token.LBRACK:
   822  			// name "[" type1, ..., typeN "]" or name "[" n "]" type
   823  			f.name, f.typ = p.parseArrayFieldOrTypeInstance(f.name)
   824  
   825  		case token.ELLIPSIS:
   826  			// name "..." type
   827  			f.typ = p.parseDotsType()
   828  			return // don't allow ...type "|" ...
   829  
   830  		case token.PERIOD:
   831  			// name "." ...
   832  			f.typ = p.parseQualifiedIdent(f.name)
   833  			f.name = nil
   834  
   835  		case token.TILDE:
   836  			if typeSetsOK {
   837  				f.typ = p.embeddedElem(nil)
   838  				return
   839  			}
   840  
   841  		case token.OR:
   842  			if typeSetsOK {
   843  				// name "|" typeset
   844  				f.typ = p.embeddedElem(f.name)
   845  				f.name = nil
   846  				return
   847  			}
   848  		}
   849  
   850  	case token.MUL, token.ARROW, token.FUNC, token.LBRACK, token.CHAN, token.MAP, token.STRUCT, token.INTERFACE, token.LPAREN:
   851  		// type
   852  		f.typ = p.parseType()
   853  
   854  	case token.ELLIPSIS:
   855  		// "..." type
   856  		// (always accepted)
   857  		f.typ = p.parseDotsType()
   858  		return // don't allow ...type "|" ...
   859  
   860  	default:
   861  		// TODO(rfindley): this is incorrect in the case of type parameter lists
   862  		//                 (should be "']'" in that case)
   863  		p.errorExpected(p.pos, "')'")
   864  		p.advance(exprEnd)
   865  	}
   866  
   867  	// [name] type "|"
   868  	if typeSetsOK && p.tok == token.OR && f.typ != nil {
   869  		f.typ = p.embeddedElem(f.typ)
   870  	}
   871  
   872  	return
   873  }
   874  
   875  func (p *parser) parseParameterList(name0 *ast.Ident, typ0 ast.Expr, closing token.Token) (params []*ast.Field) {
   876  	if p.trace {
   877  		defer un(trace(p, "ParameterList"))
   878  	}
   879  
   880  	// Type parameters are the only parameter list closed by ']'.
   881  	tparams := closing == token.RBRACK
   882  
   883  	pos0 := p.pos
   884  	if name0 != nil {
   885  		pos0 = name0.Pos()
   886  	} else if typ0 != nil {
   887  		pos0 = typ0.Pos()
   888  	}
   889  
   890  	// Note: The code below matches the corresponding code in the syntax
   891  	//       parser closely. Changes must be reflected in either parser.
   892  	//       For the code to match, we use the local []field list that
   893  	//       corresponds to []syntax.Field. At the end, the list must be
   894  	//       converted into an []*ast.Field.
   895  
   896  	var list []field
   897  	var named int // number of parameters that have an explicit name and type
   898  	var typed int // number of parameters that have an explicit type
   899  
   900  	for name0 != nil || p.tok != closing && p.tok != token.EOF {
   901  		var par field
   902  		if typ0 != nil {
   903  			if tparams {
   904  				typ0 = p.embeddedElem(typ0)
   905  			}
   906  			par = field{name0, typ0}
   907  		} else {
   908  			par = p.parseParamDecl(name0, tparams)
   909  		}
   910  		name0 = nil // 1st name was consumed if present
   911  		typ0 = nil  // 1st typ was consumed if present
   912  		if par.name != nil || par.typ != nil {
   913  			list = append(list, par)
   914  			if par.name != nil && par.typ != nil {
   915  				named++
   916  			}
   917  			if par.typ != nil {
   918  				typed++
   919  			}
   920  		}
   921  		if !p.atComma("parameter list", closing) {
   922  			break
   923  		}
   924  		p.next()
   925  	}
   926  
   927  	if len(list) == 0 {
   928  		return // not uncommon
   929  	}
   930  
   931  	// distribute parameter types (len(list) > 0)
   932  	if named == 0 {
   933  		// all unnamed => found names are type names
   934  		for i := 0; i < len(list); i++ {
   935  			par := &list[i]
   936  			if typ := par.name; typ != nil {
   937  				par.typ = typ
   938  				par.name = nil
   939  			}
   940  		}
   941  		if tparams {
   942  			// This is the same error handling as below, adjusted for type parameters only.
   943  			// See comment below for details. (go.dev/issue/64534)
   944  			var errPos token.Pos
   945  			var msg string
   946  			if named == typed /* same as typed == 0 */ {
   947  				errPos = p.pos // position error at closing ]
   948  				msg = "missing type constraint"
   949  			} else {
   950  				errPos = pos0 // position at opening [ or first name
   951  				msg = "missing type parameter name"
   952  				if len(list) == 1 {
   953  					msg += " or invalid array length"
   954  				}
   955  			}
   956  			p.error(errPos, msg)
   957  		}
   958  	} else if named != len(list) {
   959  		// some named or we're in a type parameter list => all must be named
   960  		var errPos token.Pos // left-most error position (or invalid)
   961  		var typ ast.Expr     // current type (from right to left)
   962  		for i := len(list) - 1; i >= 0; i-- {
   963  			if par := &list[i]; par.typ != nil {
   964  				typ = par.typ
   965  				if par.name == nil {
   966  					errPos = typ.Pos()
   967  					n := ast.NewIdent("_")
   968  					n.NamePos = errPos // correct position
   969  					par.name = n
   970  				}
   971  			} else if typ != nil {
   972  				par.typ = typ
   973  			} else {
   974  				// par.typ == nil && typ == nil => we only have a par.name
   975  				errPos = par.name.Pos()
   976  				par.typ = &ast.BadExpr{From: errPos, To: p.pos}
   977  			}
   978  		}
   979  		if errPos.IsValid() {
   980  			// Not all parameters are named because named != len(list).
   981  			// If named == typed, there must be parameters that have no types.
   982  			// They must be at the end of the parameter list, otherwise types
   983  			// would have been filled in by the right-to-left sweep above and
   984  			// there would be no error.
   985  			// If tparams is set, the parameter list is a type parameter list.
   986  			var msg string
   987  			if named == typed {
   988  				errPos = p.pos // position error at closing token ) or ]
   989  				if tparams {
   990  					msg = "missing type constraint"
   991  				} else {
   992  					msg = "missing parameter type"
   993  				}
   994  			} else {
   995  				if tparams {
   996  					msg = "missing type parameter name"
   997  					// go.dev/issue/60812
   998  					if len(list) == 1 {
   999  						msg += " or invalid array length"
  1000  					}
  1001  				} else {
  1002  					msg = "missing parameter name"
  1003  				}
  1004  			}
  1005  			p.error(errPos, msg)
  1006  		}
  1007  	}
  1008  
  1009  	// Convert list to []*ast.Field.
  1010  	// If list contains types only, each type gets its own ast.Field.
  1011  	if named == 0 {
  1012  		// parameter list consists of types only
  1013  		for _, par := range list {
  1014  			assert(par.typ != nil, "nil type in unnamed parameter list")
  1015  			params = append(params, &ast.Field{Type: par.typ})
  1016  		}
  1017  		return
  1018  	}
  1019  
  1020  	// If the parameter list consists of named parameters with types,
  1021  	// collect all names with the same types into a single ast.Field.
  1022  	var names []*ast.Ident
  1023  	var typ ast.Expr
  1024  	addParams := func() {
  1025  		assert(typ != nil, "nil type in named parameter list")
  1026  		field := &ast.Field{Names: names, Type: typ}
  1027  		params = append(params, field)
  1028  		names = nil
  1029  	}
  1030  	for _, par := range list {
  1031  		if par.typ != typ {
  1032  			if len(names) > 0 {
  1033  				addParams()
  1034  			}
  1035  			typ = par.typ
  1036  		}
  1037  		names = append(names, par.name)
  1038  	}
  1039  	if len(names) > 0 {
  1040  		addParams()
  1041  	}
  1042  	return
  1043  }
  1044  
  1045  func (p *parser) parseParameters(acceptTParams bool) (tparams, params *ast.FieldList) {
  1046  	if p.trace {
  1047  		defer un(trace(p, "Parameters"))
  1048  	}
  1049  
  1050  	if acceptTParams && p.tok == token.LBRACK {
  1051  		opening := p.pos
  1052  		p.next()
  1053  		// [T any](params) syntax
  1054  		list := p.parseParameterList(nil, nil, token.RBRACK)
  1055  		rbrack := p.expect(token.RBRACK)
  1056  		tparams = &ast.FieldList{Opening: opening, List: list, Closing: rbrack}
  1057  		// Type parameter lists must not be empty.
  1058  		if tparams.NumFields() == 0 {
  1059  			p.error(tparams.Closing, "empty type parameter list")
  1060  			tparams = nil // avoid follow-on errors
  1061  		}
  1062  	}
  1063  
  1064  	opening := p.expect(token.LPAREN)
  1065  
  1066  	var fields []*ast.Field
  1067  	if p.tok != token.RPAREN {
  1068  		fields = p.parseParameterList(nil, nil, token.RPAREN)
  1069  	}
  1070  
  1071  	rparen := p.expect(token.RPAREN)
  1072  	params = &ast.FieldList{Opening: opening, List: fields, Closing: rparen}
  1073  
  1074  	return
  1075  }
  1076  
  1077  func (p *parser) parseResult() *ast.FieldList {
  1078  	if p.trace {
  1079  		defer un(trace(p, "Result"))
  1080  	}
  1081  
  1082  	if p.tok == token.LPAREN {
  1083  		_, results := p.parseParameters(false)
  1084  		return results
  1085  	}
  1086  
  1087  	typ := p.tryIdentOrType()
  1088  	if typ != nil {
  1089  		list := make([]*ast.Field, 1)
  1090  		list[0] = &ast.Field{Type: typ}
  1091  		return &ast.FieldList{List: list}
  1092  	}
  1093  
  1094  	return nil
  1095  }
  1096  
  1097  func (p *parser) parseFuncType() *ast.FuncType {
  1098  	if p.trace {
  1099  		defer un(trace(p, "FuncType"))
  1100  	}
  1101  
  1102  	pos := p.expect(token.FUNC)
  1103  	tparams, params := p.parseParameters(true)
  1104  	if tparams != nil {
  1105  		p.error(tparams.Pos(), "function type must have no type parameters")
  1106  	}
  1107  	results := p.parseResult()
  1108  
  1109  	return &ast.FuncType{Func: pos, Params: params, Results: results}
  1110  }
  1111  
  1112  func (p *parser) parseMethodSpec() *ast.Field {
  1113  	if p.trace {
  1114  		defer un(trace(p, "MethodSpec"))
  1115  	}
  1116  
  1117  	doc := p.leadComment
  1118  	var idents []*ast.Ident
  1119  	var typ ast.Expr
  1120  	x := p.parseTypeName(nil)
  1121  	if ident, _ := x.(*ast.Ident); ident != nil {
  1122  		switch {
  1123  		case p.tok == token.LBRACK:
  1124  			// generic method or embedded instantiated type
  1125  			lbrack := p.pos
  1126  			p.next()
  1127  			p.exprLev++
  1128  			x := p.parseExpr()
  1129  			p.exprLev--
  1130  			if name0, _ := x.(*ast.Ident); name0 != nil && p.tok != token.COMMA && p.tok != token.RBRACK {
  1131  				// generic method m[T any]
  1132  				//
  1133  				// Interface methods do not have type parameters. We parse them for a
  1134  				// better error message and improved error recovery.
  1135  				_ = p.parseParameterList(name0, nil, token.RBRACK)
  1136  				_ = p.expect(token.RBRACK)
  1137  				p.error(lbrack, "interface method must have no type parameters")
  1138  
  1139  				// TODO(rfindley) refactor to share code with parseFuncType.
  1140  				_, params := p.parseParameters(false)
  1141  				results := p.parseResult()
  1142  				idents = []*ast.Ident{ident}
  1143  				typ = &ast.FuncType{
  1144  					Func:    token.NoPos,
  1145  					Params:  params,
  1146  					Results: results,
  1147  				}
  1148  			} else {
  1149  				// embedded instantiated type
  1150  				// TODO(rfindley) should resolve all identifiers in x.
  1151  				list := []ast.Expr{x}
  1152  				if p.atComma("type argument list", token.RBRACK) {
  1153  					p.exprLev++
  1154  					p.next()
  1155  					for p.tok != token.RBRACK && p.tok != token.EOF {
  1156  						list = append(list, p.parseType())
  1157  						if !p.atComma("type argument list", token.RBRACK) {
  1158  							break
  1159  						}
  1160  						p.next()
  1161  					}
  1162  					p.exprLev--
  1163  				}
  1164  				rbrack := p.expectClosing(token.RBRACK, "type argument list")
  1165  				typ = packIndexExpr(ident, lbrack, list, rbrack)
  1166  			}
  1167  		case p.tok == token.LPAREN:
  1168  			// ordinary method
  1169  			// TODO(rfindley) refactor to share code with parseFuncType.
  1170  			_, params := p.parseParameters(false)
  1171  			results := p.parseResult()
  1172  			idents = []*ast.Ident{ident}
  1173  			typ = &ast.FuncType{Func: token.NoPos, Params: params, Results: results}
  1174  		default:
  1175  			// embedded type
  1176  			typ = x
  1177  		}
  1178  	} else {
  1179  		// embedded, possibly instantiated type
  1180  		typ = x
  1181  		if p.tok == token.LBRACK {
  1182  			// embedded instantiated interface
  1183  			typ = p.parseTypeInstance(typ)
  1184  		}
  1185  	}
  1186  
  1187  	// Comment is added at the callsite: the field below may joined with
  1188  	// additional type specs using '|'.
  1189  	// TODO(rfindley) this should be refactored.
  1190  	// TODO(rfindley) add more tests for comment handling.
  1191  	return &ast.Field{Doc: doc, Names: idents, Type: typ}
  1192  }
  1193  
  1194  func (p *parser) embeddedElem(x ast.Expr) ast.Expr {
  1195  	if p.trace {
  1196  		defer un(trace(p, "EmbeddedElem"))
  1197  	}
  1198  	if x == nil {
  1199  		x = p.embeddedTerm()
  1200  	}
  1201  	for p.tok == token.OR {
  1202  		t := new(ast.BinaryExpr)
  1203  		t.OpPos = p.pos
  1204  		t.Op = token.OR
  1205  		p.next()
  1206  		t.X = x
  1207  		t.Y = p.embeddedTerm()
  1208  		x = t
  1209  	}
  1210  	return x
  1211  }
  1212  
  1213  func (p *parser) embeddedTerm() ast.Expr {
  1214  	if p.trace {
  1215  		defer un(trace(p, "EmbeddedTerm"))
  1216  	}
  1217  	if p.tok == token.TILDE {
  1218  		t := new(ast.UnaryExpr)
  1219  		t.OpPos = p.pos
  1220  		t.Op = token.TILDE
  1221  		p.next()
  1222  		t.X = p.parseType()
  1223  		return t
  1224  	}
  1225  
  1226  	t := p.tryIdentOrType()
  1227  	if t == nil {
  1228  		pos := p.pos
  1229  		p.errorExpected(pos, "~ term or type")
  1230  		p.advance(exprEnd)
  1231  		return &ast.BadExpr{From: pos, To: p.pos}
  1232  	}
  1233  
  1234  	return t
  1235  }
  1236  
  1237  func (p *parser) parseInterfaceType() *ast.InterfaceType {
  1238  	if p.trace {
  1239  		defer un(trace(p, "InterfaceType"))
  1240  	}
  1241  
  1242  	pos := p.expect(token.INTERFACE)
  1243  	lbrace := p.expect(token.LBRACE)
  1244  
  1245  	var list []*ast.Field
  1246  
  1247  parseElements:
  1248  	for {
  1249  		switch {
  1250  		case p.tok == token.IDENT:
  1251  			f := p.parseMethodSpec()
  1252  			if f.Names == nil {
  1253  				f.Type = p.embeddedElem(f.Type)
  1254  			}
  1255  			f.Comment = p.expectSemi()
  1256  			list = append(list, f)
  1257  		case p.tok == token.TILDE:
  1258  			typ := p.embeddedElem(nil)
  1259  			comment := p.expectSemi()
  1260  			list = append(list, &ast.Field{Type: typ, Comment: comment})
  1261  		default:
  1262  			if t := p.tryIdentOrType(); t != nil {
  1263  				typ := p.embeddedElem(t)
  1264  				comment := p.expectSemi()
  1265  				list = append(list, &ast.Field{Type: typ, Comment: comment})
  1266  			} else {
  1267  				break parseElements
  1268  			}
  1269  		}
  1270  	}
  1271  
  1272  	// TODO(rfindley): the error produced here could be improved, since we could
  1273  	// accept an identifier, 'type', or a '}' at this point.
  1274  	rbrace := p.expect(token.RBRACE)
  1275  
  1276  	return &ast.InterfaceType{
  1277  		Interface: pos,
  1278  		Methods: &ast.FieldList{
  1279  			Opening: lbrace,
  1280  			List:    list,
  1281  			Closing: rbrace,
  1282  		},
  1283  	}
  1284  }
  1285  
  1286  func (p *parser) parseMapType() *ast.MapType {
  1287  	if p.trace {
  1288  		defer un(trace(p, "MapType"))
  1289  	}
  1290  
  1291  	pos := p.expect(token.MAP)
  1292  	p.expect(token.LBRACK)
  1293  	key := p.parseType()
  1294  	p.expect(token.RBRACK)
  1295  	value := p.parseType()
  1296  
  1297  	return &ast.MapType{Map: pos, Key: key, Value: value}
  1298  }
  1299  
  1300  func (p *parser) parseChanType() *ast.ChanType {
  1301  	if p.trace {
  1302  		defer un(trace(p, "ChanType"))
  1303  	}
  1304  
  1305  	pos := p.pos
  1306  	dir := ast.SEND | ast.RECV
  1307  	var arrow token.Pos
  1308  	if p.tok == token.CHAN {
  1309  		p.next()
  1310  		if p.tok == token.ARROW {
  1311  			arrow = p.pos
  1312  			p.next()
  1313  			dir = ast.SEND
  1314  		}
  1315  	} else {
  1316  		arrow = p.expect(token.ARROW)
  1317  		p.expect(token.CHAN)
  1318  		dir = ast.RECV
  1319  	}
  1320  	value := p.parseType()
  1321  
  1322  	return &ast.ChanType{Begin: pos, Arrow: arrow, Dir: dir, Value: value}
  1323  }
  1324  
  1325  func (p *parser) parseTypeInstance(typ ast.Expr) ast.Expr {
  1326  	if p.trace {
  1327  		defer un(trace(p, "TypeInstance"))
  1328  	}
  1329  
  1330  	opening := p.expect(token.LBRACK)
  1331  	p.exprLev++
  1332  	var list []ast.Expr
  1333  	for p.tok != token.RBRACK && p.tok != token.EOF {
  1334  		list = append(list, p.parseType())
  1335  		if !p.atComma("type argument list", token.RBRACK) {
  1336  			break
  1337  		}
  1338  		p.next()
  1339  	}
  1340  	p.exprLev--
  1341  
  1342  	closing := p.expectClosing(token.RBRACK, "type argument list")
  1343  
  1344  	if len(list) == 0 {
  1345  		p.errorExpected(closing, "type argument list")
  1346  		return &ast.IndexExpr{
  1347  			X:      typ,
  1348  			Lbrack: opening,
  1349  			Index:  &ast.BadExpr{From: opening + 1, To: closing},
  1350  			Rbrack: closing,
  1351  		}
  1352  	}
  1353  
  1354  	return packIndexExpr(typ, opening, list, closing)
  1355  }
  1356  
  1357  func (p *parser) tryIdentOrType() ast.Expr {
  1358  	defer decNestLev(incNestLev(p))
  1359  
  1360  	switch p.tok {
  1361  	case token.IDENT:
  1362  		typ := p.parseTypeName(nil)
  1363  		if p.tok == token.LBRACK {
  1364  			typ = p.parseTypeInstance(typ)
  1365  		}
  1366  		return typ
  1367  	case token.LBRACK:
  1368  		lbrack := p.expect(token.LBRACK)
  1369  		return p.parseArrayType(lbrack, nil)
  1370  	case token.STRUCT:
  1371  		return p.parseStructType()
  1372  	case token.MUL:
  1373  		return p.parsePointerType()
  1374  	case token.FUNC:
  1375  		return p.parseFuncType()
  1376  	case token.INTERFACE:
  1377  		return p.parseInterfaceType()
  1378  	case token.MAP:
  1379  		return p.parseMapType()
  1380  	case token.CHAN, token.ARROW:
  1381  		return p.parseChanType()
  1382  	case token.LPAREN:
  1383  		lparen := p.pos
  1384  		p.next()
  1385  		typ := p.parseType()
  1386  		rparen := p.expect(token.RPAREN)
  1387  		return &ast.ParenExpr{Lparen: lparen, X: typ, Rparen: rparen}
  1388  	}
  1389  
  1390  	// no type found
  1391  	return nil
  1392  }
  1393  
  1394  // ----------------------------------------------------------------------------
  1395  // Blocks
  1396  
  1397  func (p *parser) parseStmtList() (list []ast.Stmt) {
  1398  	if p.trace {
  1399  		defer un(trace(p, "StatementList"))
  1400  	}
  1401  
  1402  	for p.tok != token.CASE && p.tok != token.DEFAULT && p.tok != token.RBRACE && p.tok != token.EOF {
  1403  		list = append(list, p.parseStmt())
  1404  	}
  1405  
  1406  	return
  1407  }
  1408  
  1409  func (p *parser) parseBody() *ast.BlockStmt {
  1410  	if p.trace {
  1411  		defer un(trace(p, "Body"))
  1412  	}
  1413  
  1414  	lbrace := p.expect(token.LBRACE)
  1415  	list := p.parseStmtList()
  1416  	rbrace := p.expect2(token.RBRACE)
  1417  
  1418  	return &ast.BlockStmt{Lbrace: lbrace, List: list, Rbrace: rbrace}
  1419  }
  1420  
  1421  func (p *parser) parseBlockStmt() *ast.BlockStmt {
  1422  	if p.trace {
  1423  		defer un(trace(p, "BlockStmt"))
  1424  	}
  1425  
  1426  	lbrace := p.expect(token.LBRACE)
  1427  	list := p.parseStmtList()
  1428  	rbrace := p.expect2(token.RBRACE)
  1429  
  1430  	return &ast.BlockStmt{Lbrace: lbrace, List: list, Rbrace: rbrace}
  1431  }
  1432  
  1433  // ----------------------------------------------------------------------------
  1434  // Expressions
  1435  
  1436  func (p *parser) parseFuncTypeOrLit() ast.Expr {
  1437  	if p.trace {
  1438  		defer un(trace(p, "FuncTypeOrLit"))
  1439  	}
  1440  
  1441  	typ := p.parseFuncType()
  1442  	if p.tok != token.LBRACE {
  1443  		// function type only
  1444  		return typ
  1445  	}
  1446  
  1447  	p.exprLev++
  1448  	body := p.parseBody()
  1449  	p.exprLev--
  1450  
  1451  	return &ast.FuncLit{Type: typ, Body: body}
  1452  }
  1453  
  1454  // parseOperand may return an expression or a raw type (incl. array
  1455  // types of the form [...]T). Callers must verify the result.
  1456  func (p *parser) parseOperand() ast.Expr {
  1457  	if p.trace {
  1458  		defer un(trace(p, "Operand"))
  1459  	}
  1460  
  1461  	switch p.tok {
  1462  	case token.IDENT:
  1463  		x := p.parseIdent()
  1464  		return x
  1465  
  1466  	case token.INT, token.FLOAT, token.IMAG, token.CHAR, token.STRING:
  1467  		x := &ast.BasicLit{ValuePos: p.pos, Kind: p.tok, Value: p.lit}
  1468  		p.next()
  1469  		return x
  1470  
  1471  	case token.LPAREN:
  1472  		lparen := p.pos
  1473  		p.next()
  1474  		p.exprLev++
  1475  		x := p.parseRhs() // types may be parenthesized: (some type)
  1476  		p.exprLev--
  1477  		rparen := p.expect(token.RPAREN)
  1478  		return &ast.ParenExpr{Lparen: lparen, X: x, Rparen: rparen}
  1479  
  1480  	case token.FUNC:
  1481  		return p.parseFuncTypeOrLit()
  1482  	}
  1483  
  1484  	if typ := p.tryIdentOrType(); typ != nil { // do not consume trailing type parameters
  1485  		// could be type for composite literal or conversion
  1486  		_, isIdent := typ.(*ast.Ident)
  1487  		assert(!isIdent, "type cannot be identifier")
  1488  		return typ
  1489  	}
  1490  
  1491  	// we have an error
  1492  	pos := p.pos
  1493  	p.errorExpected(pos, "operand")
  1494  	p.advance(stmtStart)
  1495  	return &ast.BadExpr{From: pos, To: p.pos}
  1496  }
  1497  
  1498  func (p *parser) parseSelector(x ast.Expr) ast.Expr {
  1499  	if p.trace {
  1500  		defer un(trace(p, "Selector"))
  1501  	}
  1502  
  1503  	sel := p.parseIdent()
  1504  
  1505  	return &ast.SelectorExpr{X: x, Sel: sel}
  1506  }
  1507  
  1508  func (p *parser) parseTypeAssertion(x ast.Expr) ast.Expr {
  1509  	if p.trace {
  1510  		defer un(trace(p, "TypeAssertion"))
  1511  	}
  1512  
  1513  	lparen := p.expect(token.LPAREN)
  1514  	var typ ast.Expr
  1515  	if p.tok == token.TYPE {
  1516  		// type switch: typ == nil
  1517  		p.next()
  1518  	} else {
  1519  		typ = p.parseType()
  1520  	}
  1521  	rparen := p.expect(token.RPAREN)
  1522  
  1523  	return &ast.TypeAssertExpr{X: x, Type: typ, Lparen: lparen, Rparen: rparen}
  1524  }
  1525  
  1526  func (p *parser) parseIndexOrSliceOrInstance(x ast.Expr) ast.Expr {
  1527  	if p.trace {
  1528  		defer un(trace(p, "parseIndexOrSliceOrInstance"))
  1529  	}
  1530  
  1531  	lbrack := p.expect(token.LBRACK)
  1532  	if p.tok == token.RBRACK {
  1533  		// empty index, slice or index expressions are not permitted;
  1534  		// accept them for parsing tolerance, but complain
  1535  		p.errorExpected(p.pos, "operand")
  1536  		rbrack := p.pos
  1537  		p.next()
  1538  		return &ast.IndexExpr{
  1539  			X:      x,
  1540  			Lbrack: lbrack,
  1541  			Index:  &ast.BadExpr{From: rbrack, To: rbrack},
  1542  			Rbrack: rbrack,
  1543  		}
  1544  	}
  1545  	p.exprLev++
  1546  
  1547  	const N = 3 // change the 3 to 2 to disable 3-index slices
  1548  	var args []ast.Expr
  1549  	var index [N]ast.Expr
  1550  	var colons [N - 1]token.Pos
  1551  	if p.tok != token.COLON {
  1552  		// We can't know if we have an index expression or a type instantiation;
  1553  		// so even if we see a (named) type we are not going to be in type context.
  1554  		index[0] = p.parseRhs()
  1555  	}
  1556  	ncolons := 0
  1557  	switch p.tok {
  1558  	case token.COLON:
  1559  		// slice expression
  1560  		for p.tok == token.COLON && ncolons < len(colons) {
  1561  			colons[ncolons] = p.pos
  1562  			ncolons++
  1563  			p.next()
  1564  			if p.tok != token.COLON && p.tok != token.RBRACK && p.tok != token.EOF {
  1565  				index[ncolons] = p.parseRhs()
  1566  			}
  1567  		}
  1568  	case token.COMMA:
  1569  		// instance expression
  1570  		args = append(args, index[0])
  1571  		for p.tok == token.COMMA {
  1572  			p.next()
  1573  			if p.tok != token.RBRACK && p.tok != token.EOF {
  1574  				args = append(args, p.parseType())
  1575  			}
  1576  		}
  1577  	}
  1578  
  1579  	p.exprLev--
  1580  	rbrack := p.expect(token.RBRACK)
  1581  
  1582  	if ncolons > 0 {
  1583  		// slice expression
  1584  		slice3 := false
  1585  		if ncolons == 2 {
  1586  			slice3 = true
  1587  			// Check presence of middle and final index here rather than during type-checking
  1588  			// to prevent erroneous programs from passing through gofmt (was go.dev/issue/7305).
  1589  			if index[1] == nil {
  1590  				p.error(colons[0], "middle index required in 3-index slice")
  1591  				index[1] = &ast.BadExpr{From: colons[0] + 1, To: colons[1]}
  1592  			}
  1593  			if index[2] == nil {
  1594  				p.error(colons[1], "final index required in 3-index slice")
  1595  				index[2] = &ast.BadExpr{From: colons[1] + 1, To: rbrack}
  1596  			}
  1597  		}
  1598  		return &ast.SliceExpr{X: x, Lbrack: lbrack, Low: index[0], High: index[1], Max: index[2], Slice3: slice3, Rbrack: rbrack}
  1599  	}
  1600  
  1601  	if len(args) == 0 {
  1602  		// index expression
  1603  		return &ast.IndexExpr{X: x, Lbrack: lbrack, Index: index[0], Rbrack: rbrack}
  1604  	}
  1605  
  1606  	// instance expression
  1607  	return packIndexExpr(x, lbrack, args, rbrack)
  1608  }
  1609  
  1610  func (p *parser) parseCallOrConversion(fun ast.Expr) *ast.CallExpr {
  1611  	if p.trace {
  1612  		defer un(trace(p, "CallOrConversion"))
  1613  	}
  1614  
  1615  	lparen := p.expect(token.LPAREN)
  1616  	p.exprLev++
  1617  	var list []ast.Expr
  1618  	var ellipsis token.Pos
  1619  	for p.tok != token.RPAREN && p.tok != token.EOF && !ellipsis.IsValid() {
  1620  		list = append(list, p.parseRhs()) // builtins may expect a type: make(some type, ...)
  1621  		if p.tok == token.ELLIPSIS {
  1622  			ellipsis = p.pos
  1623  			p.next()
  1624  		}
  1625  		if !p.atComma("argument list", token.RPAREN) {
  1626  			break
  1627  		}
  1628  		p.next()
  1629  	}
  1630  	p.exprLev--
  1631  	rparen := p.expectClosing(token.RPAREN, "argument list")
  1632  
  1633  	return &ast.CallExpr{Fun: fun, Lparen: lparen, Args: list, Ellipsis: ellipsis, Rparen: rparen}
  1634  }
  1635  
  1636  func (p *parser) parseValue() ast.Expr {
  1637  	if p.trace {
  1638  		defer un(trace(p, "Element"))
  1639  	}
  1640  
  1641  	if p.tok == token.LBRACE {
  1642  		return p.parseLiteralValue(nil)
  1643  	}
  1644  
  1645  	x := p.parseExpr()
  1646  
  1647  	return x
  1648  }
  1649  
  1650  func (p *parser) parseElement() ast.Expr {
  1651  	if p.trace {
  1652  		defer un(trace(p, "Element"))
  1653  	}
  1654  
  1655  	x := p.parseValue()
  1656  	if p.tok == token.COLON {
  1657  		colon := p.pos
  1658  		p.next()
  1659  		x = &ast.KeyValueExpr{Key: x, Colon: colon, Value: p.parseValue()}
  1660  	}
  1661  
  1662  	return x
  1663  }
  1664  
  1665  func (p *parser) parseElementList() (list []ast.Expr) {
  1666  	if p.trace {
  1667  		defer un(trace(p, "ElementList"))
  1668  	}
  1669  
  1670  	for p.tok != token.RBRACE && p.tok != token.EOF {
  1671  		list = append(list, p.parseElement())
  1672  		if !p.atComma("composite literal", token.RBRACE) {
  1673  			break
  1674  		}
  1675  		p.next()
  1676  	}
  1677  
  1678  	return
  1679  }
  1680  
  1681  func (p *parser) parseLiteralValue(typ ast.Expr) ast.Expr {
  1682  	defer decNestLev(incNestLev(p))
  1683  
  1684  	if p.trace {
  1685  		defer un(trace(p, "LiteralValue"))
  1686  	}
  1687  
  1688  	lbrace := p.expect(token.LBRACE)
  1689  	var elts []ast.Expr
  1690  	p.exprLev++
  1691  	if p.tok != token.RBRACE {
  1692  		elts = p.parseElementList()
  1693  	}
  1694  	p.exprLev--
  1695  	rbrace := p.expectClosing(token.RBRACE, "composite literal")
  1696  	return &ast.CompositeLit{Type: typ, Lbrace: lbrace, Elts: elts, Rbrace: rbrace}
  1697  }
  1698  
  1699  func (p *parser) parsePrimaryExpr(x ast.Expr) ast.Expr {
  1700  	if p.trace {
  1701  		defer un(trace(p, "PrimaryExpr"))
  1702  	}
  1703  
  1704  	if x == nil {
  1705  		x = p.parseOperand()
  1706  	}
  1707  	// We track the nesting here rather than at the entry for the function,
  1708  	// since it can iteratively produce a nested output, and we want to
  1709  	// limit how deep a structure we generate.
  1710  	var n int
  1711  	defer func() { p.nestLev -= n }()
  1712  	for n = 1; ; n++ {
  1713  		incNestLev(p)
  1714  		switch p.tok {
  1715  		case token.PERIOD:
  1716  			p.next()
  1717  			switch p.tok {
  1718  			case token.IDENT:
  1719  				x = p.parseSelector(x)
  1720  			case token.LPAREN:
  1721  				x = p.parseTypeAssertion(x)
  1722  			default:
  1723  				pos := p.pos
  1724  				p.errorExpected(pos, "selector or type assertion")
  1725  				// TODO(rFindley) The check for token.RBRACE below is a targeted fix
  1726  				//                to error recovery sufficient to make the x/tools tests to
  1727  				//                pass with the new parsing logic introduced for type
  1728  				//                parameters. Remove this once error recovery has been
  1729  				//                more generally reconsidered.
  1730  				if p.tok != token.RBRACE {
  1731  					p.next() // make progress
  1732  				}
  1733  				sel := &ast.Ident{NamePos: pos, Name: "_"}
  1734  				x = &ast.SelectorExpr{X: x, Sel: sel}
  1735  			}
  1736  		case token.LBRACK:
  1737  			x = p.parseIndexOrSliceOrInstance(x)
  1738  		case token.LPAREN:
  1739  			x = p.parseCallOrConversion(x)
  1740  		case token.LBRACE:
  1741  			// operand may have returned a parenthesized complit
  1742  			// type; accept it but complain if we have a complit
  1743  			t := ast.Unparen(x)
  1744  			// determine if '{' belongs to a composite literal or a block statement
  1745  			switch t.(type) {
  1746  			case *ast.BadExpr, *ast.Ident, *ast.SelectorExpr:
  1747  				if p.exprLev < 0 {
  1748  					return x
  1749  				}
  1750  				// x is possibly a composite literal type
  1751  			case *ast.IndexExpr, *ast.IndexListExpr:
  1752  				if p.exprLev < 0 {
  1753  					return x
  1754  				}
  1755  				// x is possibly a composite literal type
  1756  			case *ast.ArrayType, *ast.StructType, *ast.MapType:
  1757  				// x is a composite literal type
  1758  			default:
  1759  				return x
  1760  			}
  1761  			if t != x {
  1762  				p.error(t.Pos(), "cannot parenthesize type in composite literal")
  1763  				// already progressed, no need to advance
  1764  			}
  1765  			x = p.parseLiteralValue(x)
  1766  		default:
  1767  			return x
  1768  		}
  1769  	}
  1770  }
  1771  
  1772  func (p *parser) parseUnaryExpr() ast.Expr {
  1773  	defer decNestLev(incNestLev(p))
  1774  
  1775  	if p.trace {
  1776  		defer un(trace(p, "UnaryExpr"))
  1777  	}
  1778  
  1779  	switch p.tok {
  1780  	case token.ADD, token.SUB, token.NOT, token.XOR, token.AND, token.TILDE:
  1781  		pos, op := p.pos, p.tok
  1782  		p.next()
  1783  		x := p.parseUnaryExpr()
  1784  		return &ast.UnaryExpr{OpPos: pos, Op: op, X: x}
  1785  
  1786  	case token.ARROW:
  1787  		// channel type or receive expression
  1788  		arrow := p.pos
  1789  		p.next()
  1790  
  1791  		// If the next token is token.CHAN we still don't know if it
  1792  		// is a channel type or a receive operation - we only know
  1793  		// once we have found the end of the unary expression. There
  1794  		// are two cases:
  1795  		//
  1796  		//   <- type  => (<-type) must be channel type
  1797  		//   <- expr  => <-(expr) is a receive from an expression
  1798  		//
  1799  		// In the first case, the arrow must be re-associated with
  1800  		// the channel type parsed already:
  1801  		//
  1802  		//   <- (chan type)    =>  (<-chan type)
  1803  		//   <- (chan<- type)  =>  (<-chan (<-type))
  1804  
  1805  		x := p.parseUnaryExpr()
  1806  
  1807  		// determine which case we have
  1808  		if typ, ok := x.(*ast.ChanType); ok {
  1809  			// (<-type)
  1810  
  1811  			// re-associate position info and <-
  1812  			dir := ast.SEND
  1813  			for ok && dir == ast.SEND {
  1814  				if typ.Dir == ast.RECV {
  1815  					// error: (<-type) is (<-(<-chan T))
  1816  					p.errorExpected(typ.Arrow, "'chan'")
  1817  				}
  1818  				arrow, typ.Begin, typ.Arrow = typ.Arrow, arrow, arrow
  1819  				dir, typ.Dir = typ.Dir, ast.RECV
  1820  				typ, ok = typ.Value.(*ast.ChanType)
  1821  			}
  1822  			if dir == ast.SEND {
  1823  				p.errorExpected(arrow, "channel type")
  1824  			}
  1825  
  1826  			return x
  1827  		}
  1828  
  1829  		// <-(expr)
  1830  		return &ast.UnaryExpr{OpPos: arrow, Op: token.ARROW, X: x}
  1831  
  1832  	case token.MUL:
  1833  		// pointer type or unary "*" expression
  1834  		pos := p.pos
  1835  		p.next()
  1836  		x := p.parseUnaryExpr()
  1837  		return &ast.StarExpr{Star: pos, X: x}
  1838  	}
  1839  
  1840  	return p.parsePrimaryExpr(nil)
  1841  }
  1842  
  1843  func (p *parser) tokPrec() (token.Token, int) {
  1844  	tok := p.tok
  1845  	if p.inRhs && tok == token.ASSIGN {
  1846  		tok = token.EQL
  1847  	}
  1848  	return tok, tok.Precedence()
  1849  }
  1850  
  1851  // parseBinaryExpr parses a (possibly) binary expression.
  1852  // If x is non-nil, it is used as the left operand.
  1853  //
  1854  // TODO(rfindley): parseBinaryExpr has become overloaded. Consider refactoring.
  1855  func (p *parser) parseBinaryExpr(x ast.Expr, prec1 int) ast.Expr {
  1856  	if p.trace {
  1857  		defer un(trace(p, "BinaryExpr"))
  1858  	}
  1859  
  1860  	if x == nil {
  1861  		x = p.parseUnaryExpr()
  1862  	}
  1863  	// We track the nesting here rather than at the entry for the function,
  1864  	// since it can iteratively produce a nested output, and we want to
  1865  	// limit how deep a structure we generate.
  1866  	var n int
  1867  	defer func() { p.nestLev -= n }()
  1868  	for n = 1; ; n++ {
  1869  		incNestLev(p)
  1870  		op, oprec := p.tokPrec()
  1871  		if oprec < prec1 {
  1872  			return x
  1873  		}
  1874  		pos := p.expect(op)
  1875  		y := p.parseBinaryExpr(nil, oprec+1)
  1876  		x = &ast.BinaryExpr{X: x, OpPos: pos, Op: op, Y: y}
  1877  	}
  1878  }
  1879  
  1880  // The result may be a type or even a raw type ([...]int).
  1881  func (p *parser) parseExpr() ast.Expr {
  1882  	if p.trace {
  1883  		defer un(trace(p, "Expression"))
  1884  	}
  1885  
  1886  	return p.parseBinaryExpr(nil, token.LowestPrec+1)
  1887  }
  1888  
  1889  func (p *parser) parseRhs() ast.Expr {
  1890  	old := p.inRhs
  1891  	p.inRhs = true
  1892  	x := p.parseExpr()
  1893  	p.inRhs = old
  1894  	return x
  1895  }
  1896  
  1897  // ----------------------------------------------------------------------------
  1898  // Statements
  1899  
  1900  // Parsing modes for parseSimpleStmt.
  1901  const (
  1902  	basic = iota
  1903  	labelOk
  1904  	rangeOk
  1905  )
  1906  
  1907  // parseSimpleStmt returns true as 2nd result if it parsed the assignment
  1908  // of a range clause (with mode == rangeOk). The returned statement is an
  1909  // assignment with a right-hand side that is a single unary expression of
  1910  // the form "range x". No guarantees are given for the left-hand side.
  1911  func (p *parser) parseSimpleStmt(mode int) (ast.Stmt, bool) {
  1912  	if p.trace {
  1913  		defer un(trace(p, "SimpleStmt"))
  1914  	}
  1915  
  1916  	x := p.parseList(false)
  1917  
  1918  	switch p.tok {
  1919  	case
  1920  		token.DEFINE, token.ASSIGN, token.ADD_ASSIGN,
  1921  		token.SUB_ASSIGN, token.MUL_ASSIGN, token.QUO_ASSIGN,
  1922  		token.REM_ASSIGN, token.AND_ASSIGN, token.OR_ASSIGN,
  1923  		token.XOR_ASSIGN, token.SHL_ASSIGN, token.SHR_ASSIGN, token.AND_NOT_ASSIGN:
  1924  		// assignment statement, possibly part of a range clause
  1925  		pos, tok := p.pos, p.tok
  1926  		p.next()
  1927  		var y []ast.Expr
  1928  		isRange := false
  1929  		if mode == rangeOk && p.tok == token.RANGE && (tok == token.DEFINE || tok == token.ASSIGN) {
  1930  			pos := p.pos
  1931  			p.next()
  1932  			y = []ast.Expr{&ast.UnaryExpr{OpPos: pos, Op: token.RANGE, X: p.parseRhs()}}
  1933  			isRange = true
  1934  		} else {
  1935  			y = p.parseList(true)
  1936  		}
  1937  		return &ast.AssignStmt{Lhs: x, TokPos: pos, Tok: tok, Rhs: y}, isRange
  1938  	}
  1939  
  1940  	if len(x) > 1 {
  1941  		p.errorExpected(x[0].Pos(), "1 expression")
  1942  		// continue with first expression
  1943  	}
  1944  
  1945  	switch p.tok {
  1946  	case token.COLON:
  1947  		// labeled statement
  1948  		colon := p.pos
  1949  		p.next()
  1950  		if label, isIdent := x[0].(*ast.Ident); mode == labelOk && isIdent {
  1951  			// Go spec: The scope of a label is the body of the function
  1952  			// in which it is declared and excludes the body of any nested
  1953  			// function.
  1954  			stmt := &ast.LabeledStmt{Label: label, Colon: colon, Stmt: p.parseStmt()}
  1955  			return stmt, false
  1956  		}
  1957  		// The label declaration typically starts at x[0].Pos(), but the label
  1958  		// declaration may be erroneous due to a token after that position (and
  1959  		// before the ':'). If SpuriousErrors is not set, the (only) error
  1960  		// reported for the line is the illegal label error instead of the token
  1961  		// before the ':' that caused the problem. Thus, use the (latest) colon
  1962  		// position for error reporting.
  1963  		p.error(colon, "illegal label declaration")
  1964  		return &ast.BadStmt{From: x[0].Pos(), To: colon + 1}, false
  1965  
  1966  	case token.ARROW:
  1967  		// send statement
  1968  		arrow := p.pos
  1969  		p.next()
  1970  		y := p.parseRhs()
  1971  		return &ast.SendStmt{Chan: x[0], Arrow: arrow, Value: y}, false
  1972  
  1973  	case token.INC, token.DEC:
  1974  		// increment or decrement
  1975  		s := &ast.IncDecStmt{X: x[0], TokPos: p.pos, Tok: p.tok}
  1976  		p.next()
  1977  		return s, false
  1978  	}
  1979  
  1980  	// expression
  1981  	return &ast.ExprStmt{X: x[0]}, false
  1982  }
  1983  
  1984  func (p *parser) parseCallExpr(callType string) *ast.CallExpr {
  1985  	x := p.parseRhs() // could be a conversion: (some type)(x)
  1986  	if t := ast.Unparen(x); t != x {
  1987  		p.error(x.Pos(), fmt.Sprintf("expression in %s must not be parenthesized", callType))
  1988  		x = t
  1989  	}
  1990  	if call, isCall := x.(*ast.CallExpr); isCall {
  1991  		return call
  1992  	}
  1993  	if _, isBad := x.(*ast.BadExpr); !isBad {
  1994  		// only report error if it's a new one
  1995  		p.error(p.safePos(x.End()), fmt.Sprintf("expression in %s must be function call", callType))
  1996  	}
  1997  	return nil
  1998  }
  1999  
  2000  func (p *parser) parseGoStmt() ast.Stmt {
  2001  	if p.trace {
  2002  		defer un(trace(p, "GoStmt"))
  2003  	}
  2004  
  2005  	pos := p.expect(token.GO)
  2006  	call := p.parseCallExpr("go")
  2007  	p.expectSemi()
  2008  	if call == nil {
  2009  		return &ast.BadStmt{From: pos, To: pos + 2} // len("go")
  2010  	}
  2011  
  2012  	return &ast.GoStmt{Go: pos, Call: call}
  2013  }
  2014  
  2015  func (p *parser) parseDeferStmt() ast.Stmt {
  2016  	if p.trace {
  2017  		defer un(trace(p, "DeferStmt"))
  2018  	}
  2019  
  2020  	pos := p.expect(token.DEFER)
  2021  	call := p.parseCallExpr("defer")
  2022  	p.expectSemi()
  2023  	if call == nil {
  2024  		return &ast.BadStmt{From: pos, To: pos + 5} // len("defer")
  2025  	}
  2026  
  2027  	return &ast.DeferStmt{Defer: pos, Call: call}
  2028  }
  2029  
  2030  func (p *parser) parseReturnStmt() *ast.ReturnStmt {
  2031  	if p.trace {
  2032  		defer un(trace(p, "ReturnStmt"))
  2033  	}
  2034  
  2035  	pos := p.pos
  2036  	p.expect(token.RETURN)
  2037  	var x []ast.Expr
  2038  	if p.tok != token.SEMICOLON && p.tok != token.RBRACE {
  2039  		x = p.parseList(true)
  2040  	}
  2041  	p.expectSemi()
  2042  
  2043  	return &ast.ReturnStmt{Return: pos, Results: x}
  2044  }
  2045  
  2046  func (p *parser) parseBranchStmt(tok token.Token) *ast.BranchStmt {
  2047  	if p.trace {
  2048  		defer un(trace(p, "BranchStmt"))
  2049  	}
  2050  
  2051  	pos := p.expect(tok)
  2052  	var label *ast.Ident
  2053  	if tok != token.FALLTHROUGH && p.tok == token.IDENT {
  2054  		label = p.parseIdent()
  2055  	}
  2056  	p.expectSemi()
  2057  
  2058  	return &ast.BranchStmt{TokPos: pos, Tok: tok, Label: label}
  2059  }
  2060  
  2061  func (p *parser) makeExpr(s ast.Stmt, want string) ast.Expr {
  2062  	if s == nil {
  2063  		return nil
  2064  	}
  2065  	if es, isExpr := s.(*ast.ExprStmt); isExpr {
  2066  		return es.X
  2067  	}
  2068  	found := "simple statement"
  2069  	if _, isAss := s.(*ast.AssignStmt); isAss {
  2070  		found = "assignment"
  2071  	}
  2072  	p.error(s.Pos(), fmt.Sprintf("expected %s, found %s (missing parentheses around composite literal?)", want, found))
  2073  	return &ast.BadExpr{From: s.Pos(), To: p.safePos(s.End())}
  2074  }
  2075  
  2076  // parseIfHeader is an adjusted version of parser.header
  2077  // in cmd/compile/internal/syntax/parser.go, which has
  2078  // been tuned for better error handling.
  2079  func (p *parser) parseIfHeader() (init ast.Stmt, cond ast.Expr) {
  2080  	if p.tok == token.LBRACE {
  2081  		p.error(p.pos, "missing condition in if statement")
  2082  		cond = &ast.BadExpr{From: p.pos, To: p.pos}
  2083  		return
  2084  	}
  2085  	// p.tok != token.LBRACE
  2086  
  2087  	prevLev := p.exprLev
  2088  	p.exprLev = -1
  2089  
  2090  	if p.tok != token.SEMICOLON {
  2091  		// accept potential variable declaration but complain
  2092  		if p.tok == token.VAR {
  2093  			p.next()
  2094  			p.error(p.pos, "var declaration not allowed in if initializer")
  2095  		}
  2096  		init, _ = p.parseSimpleStmt(basic)
  2097  	}
  2098  
  2099  	var condStmt ast.Stmt
  2100  	var semi struct {
  2101  		pos token.Pos
  2102  		lit string // ";" or "\n"; valid if pos.IsValid()
  2103  	}
  2104  	if p.tok != token.LBRACE {
  2105  		if p.tok == token.SEMICOLON {
  2106  			semi.pos = p.pos
  2107  			semi.lit = p.lit
  2108  			p.next()
  2109  		} else {
  2110  			p.expect(token.SEMICOLON)
  2111  		}
  2112  		if p.tok != token.LBRACE {
  2113  			condStmt, _ = p.parseSimpleStmt(basic)
  2114  		}
  2115  	} else {
  2116  		condStmt = init
  2117  		init = nil
  2118  	}
  2119  
  2120  	if condStmt != nil {
  2121  		cond = p.makeExpr(condStmt, "boolean expression")
  2122  	} else if semi.pos.IsValid() {
  2123  		if semi.lit == "\n" {
  2124  			p.error(semi.pos, "unexpected newline, expecting { after if clause")
  2125  		} else {
  2126  			p.error(semi.pos, "missing condition in if statement")
  2127  		}
  2128  	}
  2129  
  2130  	// make sure we have a valid AST
  2131  	if cond == nil {
  2132  		cond = &ast.BadExpr{From: p.pos, To: p.pos}
  2133  	}
  2134  
  2135  	p.exprLev = prevLev
  2136  	return
  2137  }
  2138  
  2139  func (p *parser) parseIfStmt() *ast.IfStmt {
  2140  	defer decNestLev(incNestLev(p))
  2141  
  2142  	if p.trace {
  2143  		defer un(trace(p, "IfStmt"))
  2144  	}
  2145  
  2146  	pos := p.expect(token.IF)
  2147  
  2148  	init, cond := p.parseIfHeader()
  2149  	body := p.parseBlockStmt()
  2150  
  2151  	var else_ ast.Stmt
  2152  	if p.tok == token.ELSE {
  2153  		p.next()
  2154  		switch p.tok {
  2155  		case token.IF:
  2156  			else_ = p.parseIfStmt()
  2157  		case token.LBRACE:
  2158  			else_ = p.parseBlockStmt()
  2159  			p.expectSemi()
  2160  		default:
  2161  			p.errorExpected(p.pos, "if statement or block")
  2162  			else_ = &ast.BadStmt{From: p.pos, To: p.pos}
  2163  		}
  2164  	} else {
  2165  		p.expectSemi()
  2166  	}
  2167  
  2168  	return &ast.IfStmt{If: pos, Init: init, Cond: cond, Body: body, Else: else_}
  2169  }
  2170  
  2171  func (p *parser) parseCaseClause() *ast.CaseClause {
  2172  	if p.trace {
  2173  		defer un(trace(p, "CaseClause"))
  2174  	}
  2175  
  2176  	pos := p.pos
  2177  	var list []ast.Expr
  2178  	if p.tok == token.CASE {
  2179  		p.next()
  2180  		list = p.parseList(true)
  2181  	} else {
  2182  		p.expect(token.DEFAULT)
  2183  	}
  2184  
  2185  	colon := p.expect(token.COLON)
  2186  	body := p.parseStmtList()
  2187  
  2188  	return &ast.CaseClause{Case: pos, List: list, Colon: colon, Body: body}
  2189  }
  2190  
  2191  func isTypeSwitchAssert(x ast.Expr) bool {
  2192  	a, ok := x.(*ast.TypeAssertExpr)
  2193  	return ok && a.Type == nil
  2194  }
  2195  
  2196  func (p *parser) isTypeSwitchGuard(s ast.Stmt) bool {
  2197  	switch t := s.(type) {
  2198  	case *ast.ExprStmt:
  2199  		// x.(type)
  2200  		return isTypeSwitchAssert(t.X)
  2201  	case *ast.AssignStmt:
  2202  		// v := x.(type)
  2203  		if len(t.Lhs) == 1 && len(t.Rhs) == 1 && isTypeSwitchAssert(t.Rhs[0]) {
  2204  			switch t.Tok {
  2205  			case token.ASSIGN:
  2206  				// permit v = x.(type) but complain
  2207  				p.error(t.TokPos, "expected ':=', found '='")
  2208  				fallthrough
  2209  			case token.DEFINE:
  2210  				return true
  2211  			}
  2212  		}
  2213  	}
  2214  	return false
  2215  }
  2216  
  2217  func (p *parser) parseSwitchStmt() ast.Stmt {
  2218  	if p.trace {
  2219  		defer un(trace(p, "SwitchStmt"))
  2220  	}
  2221  
  2222  	pos := p.expect(token.SWITCH)
  2223  
  2224  	var s1, s2 ast.Stmt
  2225  	if p.tok != token.LBRACE {
  2226  		prevLev := p.exprLev
  2227  		p.exprLev = -1
  2228  		if p.tok != token.SEMICOLON {
  2229  			s2, _ = p.parseSimpleStmt(basic)
  2230  		}
  2231  		if p.tok == token.SEMICOLON {
  2232  			p.next()
  2233  			s1 = s2
  2234  			s2 = nil
  2235  			if p.tok != token.LBRACE {
  2236  				// A TypeSwitchGuard may declare a variable in addition
  2237  				// to the variable declared in the initial SimpleStmt.
  2238  				// Introduce extra scope to avoid redeclaration errors:
  2239  				//
  2240  				//	switch t := 0; t := x.(T) { ... }
  2241  				//
  2242  				// (this code is not valid Go because the first t
  2243  				// cannot be accessed and thus is never used, the extra
  2244  				// scope is needed for the correct error message).
  2245  				//
  2246  				// If we don't have a type switch, s2 must be an expression.
  2247  				// Having the extra nested but empty scope won't affect it.
  2248  				s2, _ = p.parseSimpleStmt(basic)
  2249  			}
  2250  		}
  2251  		p.exprLev = prevLev
  2252  	}
  2253  
  2254  	typeSwitch := p.isTypeSwitchGuard(s2)
  2255  	lbrace := p.expect(token.LBRACE)
  2256  	var list []ast.Stmt
  2257  	for p.tok == token.CASE || p.tok == token.DEFAULT {
  2258  		list = append(list, p.parseCaseClause())
  2259  	}
  2260  	rbrace := p.expect(token.RBRACE)
  2261  	p.expectSemi()
  2262  	body := &ast.BlockStmt{Lbrace: lbrace, List: list, Rbrace: rbrace}
  2263  
  2264  	if typeSwitch {
  2265  		return &ast.TypeSwitchStmt{Switch: pos, Init: s1, Assign: s2, Body: body}
  2266  	}
  2267  
  2268  	return &ast.SwitchStmt{Switch: pos, Init: s1, Tag: p.makeExpr(s2, "switch expression"), Body: body}
  2269  }
  2270  
  2271  func (p *parser) parseCommClause() *ast.CommClause {
  2272  	if p.trace {
  2273  		defer un(trace(p, "CommClause"))
  2274  	}
  2275  
  2276  	pos := p.pos
  2277  	var comm ast.Stmt
  2278  	if p.tok == token.CASE {
  2279  		p.next()
  2280  		lhs := p.parseList(false)
  2281  		if p.tok == token.ARROW {
  2282  			// SendStmt
  2283  			if len(lhs) > 1 {
  2284  				p.errorExpected(lhs[0].Pos(), "1 expression")
  2285  				// continue with first expression
  2286  			}
  2287  			arrow := p.pos
  2288  			p.next()
  2289  			rhs := p.parseRhs()
  2290  			comm = &ast.SendStmt{Chan: lhs[0], Arrow: arrow, Value: rhs}
  2291  		} else {
  2292  			// RecvStmt
  2293  			if tok := p.tok; tok == token.ASSIGN || tok == token.DEFINE {
  2294  				// RecvStmt with assignment
  2295  				if len(lhs) > 2 {
  2296  					p.errorExpected(lhs[0].Pos(), "1 or 2 expressions")
  2297  					// continue with first two expressions
  2298  					lhs = lhs[0:2]
  2299  				}
  2300  				pos := p.pos
  2301  				p.next()
  2302  				rhs := p.parseRhs()
  2303  				comm = &ast.AssignStmt{Lhs: lhs, TokPos: pos, Tok: tok, Rhs: []ast.Expr{rhs}}
  2304  			} else {
  2305  				// lhs must be single receive operation
  2306  				if len(lhs) > 1 {
  2307  					p.errorExpected(lhs[0].Pos(), "1 expression")
  2308  					// continue with first expression
  2309  				}
  2310  				comm = &ast.ExprStmt{X: lhs[0]}
  2311  			}
  2312  		}
  2313  	} else {
  2314  		p.expect(token.DEFAULT)
  2315  	}
  2316  
  2317  	colon := p.expect(token.COLON)
  2318  	body := p.parseStmtList()
  2319  
  2320  	return &ast.CommClause{Case: pos, Comm: comm, Colon: colon, Body: body}
  2321  }
  2322  
  2323  func (p *parser) parseSelectStmt() *ast.SelectStmt {
  2324  	if p.trace {
  2325  		defer un(trace(p, "SelectStmt"))
  2326  	}
  2327  
  2328  	pos := p.expect(token.SELECT)
  2329  	lbrace := p.expect(token.LBRACE)
  2330  	var list []ast.Stmt
  2331  	for p.tok == token.CASE || p.tok == token.DEFAULT {
  2332  		list = append(list, p.parseCommClause())
  2333  	}
  2334  	rbrace := p.expect(token.RBRACE)
  2335  	p.expectSemi()
  2336  	body := &ast.BlockStmt{Lbrace: lbrace, List: list, Rbrace: rbrace}
  2337  
  2338  	return &ast.SelectStmt{Select: pos, Body: body}
  2339  }
  2340  
  2341  func (p *parser) parseForStmt() ast.Stmt {
  2342  	if p.trace {
  2343  		defer un(trace(p, "ForStmt"))
  2344  	}
  2345  
  2346  	pos := p.expect(token.FOR)
  2347  
  2348  	var s1, s2, s3 ast.Stmt
  2349  	var isRange bool
  2350  	if p.tok != token.LBRACE {
  2351  		prevLev := p.exprLev
  2352  		p.exprLev = -1
  2353  		if p.tok != token.SEMICOLON {
  2354  			if p.tok == token.RANGE {
  2355  				// "for range x" (nil lhs in assignment)
  2356  				pos := p.pos
  2357  				p.next()
  2358  				y := []ast.Expr{&ast.UnaryExpr{OpPos: pos, Op: token.RANGE, X: p.parseRhs()}}
  2359  				s2 = &ast.AssignStmt{Rhs: y}
  2360  				isRange = true
  2361  			} else {
  2362  				s2, isRange = p.parseSimpleStmt(rangeOk)
  2363  			}
  2364  		}
  2365  		if !isRange && p.tok == token.SEMICOLON {
  2366  			p.next()
  2367  			s1 = s2
  2368  			s2 = nil
  2369  			if p.tok != token.SEMICOLON {
  2370  				s2, _ = p.parseSimpleStmt(basic)
  2371  			}
  2372  			p.expectSemi()
  2373  			if p.tok != token.LBRACE {
  2374  				s3, _ = p.parseSimpleStmt(basic)
  2375  			}
  2376  		}
  2377  		p.exprLev = prevLev
  2378  	}
  2379  
  2380  	body := p.parseBlockStmt()
  2381  	p.expectSemi()
  2382  
  2383  	if isRange {
  2384  		as := s2.(*ast.AssignStmt)
  2385  		// check lhs
  2386  		var key, value ast.Expr
  2387  		switch len(as.Lhs) {
  2388  		case 0:
  2389  			// nothing to do
  2390  		case 1:
  2391  			key = as.Lhs[0]
  2392  		case 2:
  2393  			key, value = as.Lhs[0], as.Lhs[1]
  2394  		default:
  2395  			p.errorExpected(as.Lhs[len(as.Lhs)-1].Pos(), "at most 2 expressions")
  2396  			return &ast.BadStmt{From: pos, To: p.safePos(body.End())}
  2397  		}
  2398  		// parseSimpleStmt returned a right-hand side that
  2399  		// is a single unary expression of the form "range x"
  2400  		x := as.Rhs[0].(*ast.UnaryExpr).X
  2401  		return &ast.RangeStmt{
  2402  			For:    pos,
  2403  			Key:    key,
  2404  			Value:  value,
  2405  			TokPos: as.TokPos,
  2406  			Tok:    as.Tok,
  2407  			Range:  as.Rhs[0].Pos(),
  2408  			X:      x,
  2409  			Body:   body,
  2410  		}
  2411  	}
  2412  
  2413  	// regular for statement
  2414  	return &ast.ForStmt{
  2415  		For:  pos,
  2416  		Init: s1,
  2417  		Cond: p.makeExpr(s2, "boolean or range expression"),
  2418  		Post: s3,
  2419  		Body: body,
  2420  	}
  2421  }
  2422  
  2423  func (p *parser) parseStmt() (s ast.Stmt) {
  2424  	defer decNestLev(incNestLev(p))
  2425  
  2426  	if p.trace {
  2427  		defer un(trace(p, "Statement"))
  2428  	}
  2429  
  2430  	switch p.tok {
  2431  	case token.CONST, token.TYPE, token.VAR:
  2432  		s = &ast.DeclStmt{Decl: p.parseDecl(stmtStart)}
  2433  	case
  2434  		// tokens that may start an expression
  2435  		token.IDENT, token.INT, token.FLOAT, token.IMAG, token.CHAR, token.STRING, token.FUNC, token.LPAREN, // operands
  2436  		token.LBRACK, token.STRUCT, token.MAP, token.CHAN, token.INTERFACE, // composite types
  2437  		token.ADD, token.SUB, token.MUL, token.AND, token.XOR, token.ARROW, token.NOT: // unary operators
  2438  		s, _ = p.parseSimpleStmt(labelOk)
  2439  		// because of the required look-ahead, labeled statements are
  2440  		// parsed by parseSimpleStmt - don't expect a semicolon after
  2441  		// them
  2442  		if _, isLabeledStmt := s.(*ast.LabeledStmt); !isLabeledStmt {
  2443  			p.expectSemi()
  2444  		}
  2445  	case token.GO:
  2446  		s = p.parseGoStmt()
  2447  	case token.DEFER:
  2448  		s = p.parseDeferStmt()
  2449  	case token.RETURN:
  2450  		s = p.parseReturnStmt()
  2451  	case token.BREAK, token.CONTINUE, token.GOTO, token.FALLTHROUGH:
  2452  		s = p.parseBranchStmt(p.tok)
  2453  	case token.LBRACE:
  2454  		s = p.parseBlockStmt()
  2455  		p.expectSemi()
  2456  	case token.IF:
  2457  		s = p.parseIfStmt()
  2458  	case token.SWITCH:
  2459  		s = p.parseSwitchStmt()
  2460  	case token.SELECT:
  2461  		s = p.parseSelectStmt()
  2462  	case token.FOR:
  2463  		s = p.parseForStmt()
  2464  	case token.SEMICOLON:
  2465  		// Is it ever possible to have an implicit semicolon
  2466  		// producing an empty statement in a valid program?
  2467  		// (handle correctly anyway)
  2468  		s = &ast.EmptyStmt{Semicolon: p.pos, Implicit: p.lit == "\n"}
  2469  		p.next()
  2470  	case token.RBRACE:
  2471  		// a semicolon may be omitted before a closing "}"
  2472  		s = &ast.EmptyStmt{Semicolon: p.pos, Implicit: true}
  2473  	default:
  2474  		// no statement found
  2475  		pos := p.pos
  2476  		p.errorExpected(pos, "statement")
  2477  		p.advance(stmtStart)
  2478  		s = &ast.BadStmt{From: pos, To: p.pos}
  2479  	}
  2480  
  2481  	return
  2482  }
  2483  
  2484  // ----------------------------------------------------------------------------
  2485  // Declarations
  2486  
  2487  type parseSpecFunction func(doc *ast.CommentGroup, keyword token.Token, iota int) ast.Spec
  2488  
  2489  func (p *parser) parseImportSpec(doc *ast.CommentGroup, _ token.Token, _ int) ast.Spec {
  2490  	if p.trace {
  2491  		defer un(trace(p, "ImportSpec"))
  2492  	}
  2493  
  2494  	var ident *ast.Ident
  2495  	switch p.tok {
  2496  	case token.IDENT:
  2497  		ident = p.parseIdent()
  2498  	case token.PERIOD:
  2499  		ident = &ast.Ident{NamePos: p.pos, Name: "."}
  2500  		p.next()
  2501  	}
  2502  
  2503  	pos := p.pos
  2504  	var path string
  2505  	if p.tok == token.STRING {
  2506  		path = p.lit
  2507  		p.next()
  2508  	} else if p.tok.IsLiteral() {
  2509  		p.error(pos, "import path must be a string")
  2510  		p.next()
  2511  	} else {
  2512  		p.error(pos, "missing import path")
  2513  		p.advance(exprEnd)
  2514  	}
  2515  	comment := p.expectSemi()
  2516  
  2517  	// collect imports
  2518  	spec := &ast.ImportSpec{
  2519  		Doc:     doc,
  2520  		Name:    ident,
  2521  		Path:    &ast.BasicLit{ValuePos: pos, Kind: token.STRING, Value: path},
  2522  		Comment: comment,
  2523  	}
  2524  	p.imports = append(p.imports, spec)
  2525  
  2526  	return spec
  2527  }
  2528  
  2529  func (p *parser) parseValueSpec(doc *ast.CommentGroup, keyword token.Token, iota int) ast.Spec {
  2530  	if p.trace {
  2531  		defer un(trace(p, keyword.String()+"Spec"))
  2532  	}
  2533  
  2534  	idents := p.parseIdentList()
  2535  	var typ ast.Expr
  2536  	var values []ast.Expr
  2537  	switch keyword {
  2538  	case token.CONST:
  2539  		// always permit optional type and initialization for more tolerant parsing
  2540  		if p.tok != token.EOF && p.tok != token.SEMICOLON && p.tok != token.RPAREN {
  2541  			typ = p.tryIdentOrType()
  2542  			if p.tok == token.ASSIGN {
  2543  				p.next()
  2544  				values = p.parseList(true)
  2545  			}
  2546  		}
  2547  	case token.VAR:
  2548  		if p.tok != token.ASSIGN {
  2549  			typ = p.parseType()
  2550  		}
  2551  		if p.tok == token.ASSIGN {
  2552  			p.next()
  2553  			values = p.parseList(true)
  2554  		}
  2555  	default:
  2556  		panic("unreachable")
  2557  	}
  2558  	comment := p.expectSemi()
  2559  
  2560  	spec := &ast.ValueSpec{
  2561  		Doc:     doc,
  2562  		Names:   idents,
  2563  		Type:    typ,
  2564  		Values:  values,
  2565  		Comment: comment,
  2566  	}
  2567  	return spec
  2568  }
  2569  
  2570  func (p *parser) parseGenericType(spec *ast.TypeSpec, openPos token.Pos, name0 *ast.Ident, typ0 ast.Expr) {
  2571  	if p.trace {
  2572  		defer un(trace(p, "parseGenericType"))
  2573  	}
  2574  
  2575  	list := p.parseParameterList(name0, typ0, token.RBRACK)
  2576  	closePos := p.expect(token.RBRACK)
  2577  	spec.TypeParams = &ast.FieldList{Opening: openPos, List: list, Closing: closePos}
  2578  	// Let the type checker decide whether to accept type parameters on aliases:
  2579  	// see go.dev/issue/46477.
  2580  	if p.tok == token.ASSIGN {
  2581  		// type alias
  2582  		spec.Assign = p.pos
  2583  		p.next()
  2584  	}
  2585  	spec.Type = p.parseType()
  2586  }
  2587  
  2588  func (p *parser) parseTypeSpec(doc *ast.CommentGroup, _ token.Token, _ int) ast.Spec {
  2589  	if p.trace {
  2590  		defer un(trace(p, "TypeSpec"))
  2591  	}
  2592  
  2593  	name := p.parseIdent()
  2594  	spec := &ast.TypeSpec{Doc: doc, Name: name}
  2595  
  2596  	if p.tok == token.LBRACK {
  2597  		// spec.Name "[" ...
  2598  		// array/slice type or type parameter list
  2599  		lbrack := p.pos
  2600  		p.next()
  2601  		if p.tok == token.IDENT {
  2602  			// We may have an array type or a type parameter list.
  2603  			// In either case we expect an expression x (which may
  2604  			// just be a name, or a more complex expression) which
  2605  			// we can analyze further.
  2606  			//
  2607  			// A type parameter list may have a type bound starting
  2608  			// with a "[" as in: P []E. In that case, simply parsing
  2609  			// an expression would lead to an error: P[] is invalid.
  2610  			// But since index or slice expressions are never constant
  2611  			// and thus invalid array length expressions, if the name
  2612  			// is followed by "[" it must be the start of an array or
  2613  			// slice constraint. Only if we don't see a "[" do we
  2614  			// need to parse a full expression. Notably, name <- x
  2615  			// is not a concern because name <- x is a statement and
  2616  			// not an expression.
  2617  			var x ast.Expr = p.parseIdent()
  2618  			if p.tok != token.LBRACK {
  2619  				// To parse the expression starting with name, expand
  2620  				// the call sequence we would get by passing in name
  2621  				// to parser.expr, and pass in name to parsePrimaryExpr.
  2622  				p.exprLev++
  2623  				lhs := p.parsePrimaryExpr(x)
  2624  				x = p.parseBinaryExpr(lhs, token.LowestPrec+1)
  2625  				p.exprLev--
  2626  			}
  2627  			// Analyze expression x. If we can split x into a type parameter
  2628  			// name, possibly followed by a type parameter type, we consider
  2629  			// this the start of a type parameter list, with some caveats:
  2630  			// a single name followed by "]" tilts the decision towards an
  2631  			// array declaration; a type parameter type that could also be
  2632  			// an ordinary expression but which is followed by a comma tilts
  2633  			// the decision towards a type parameter list.
  2634  			if pname, ptype := extractName(x, p.tok == token.COMMA); pname != nil && (ptype != nil || p.tok != token.RBRACK) {
  2635  				// spec.Name "[" pname ...
  2636  				// spec.Name "[" pname ptype ...
  2637  				// spec.Name "[" pname ptype "," ...
  2638  				p.parseGenericType(spec, lbrack, pname, ptype) // ptype may be nil
  2639  			} else {
  2640  				// spec.Name "[" pname "]" ...
  2641  				// spec.Name "[" x ...
  2642  				spec.Type = p.parseArrayType(lbrack, x)
  2643  			}
  2644  		} else {
  2645  			// array type
  2646  			spec.Type = p.parseArrayType(lbrack, nil)
  2647  		}
  2648  	} else {
  2649  		// no type parameters
  2650  		if p.tok == token.ASSIGN {
  2651  			// type alias
  2652  			spec.Assign = p.pos
  2653  			p.next()
  2654  		}
  2655  		spec.Type = p.parseType()
  2656  	}
  2657  
  2658  	spec.Comment = p.expectSemi()
  2659  
  2660  	return spec
  2661  }
  2662  
  2663  // extractName splits the expression x into (name, expr) if syntactically
  2664  // x can be written as name expr. The split only happens if expr is a type
  2665  // element (per the isTypeElem predicate) or if force is set.
  2666  // If x is just a name, the result is (name, nil). If the split succeeds,
  2667  // the result is (name, expr). Otherwise the result is (nil, x).
  2668  // Examples:
  2669  //
  2670  //	x           force    name    expr
  2671  //	------------------------------------
  2672  //	P*[]int     T/F      P       *[]int
  2673  //	P*E         T        P       *E
  2674  //	P*E         F        nil     P*E
  2675  //	P([]int)    T/F      P       ([]int)
  2676  //	P(E)        T        P       (E)
  2677  //	P(E)        F        nil     P(E)
  2678  //	P*E|F|~G    T/F      P       *E|F|~G
  2679  //	P*E|F|G     T        P       *E|F|G
  2680  //	P*E|F|G     F        nil     P*E|F|G
  2681  func extractName(x ast.Expr, force bool) (*ast.Ident, ast.Expr) {
  2682  	switch x := x.(type) {
  2683  	case *ast.Ident:
  2684  		return x, nil
  2685  	case *ast.BinaryExpr:
  2686  		switch x.Op {
  2687  		case token.MUL:
  2688  			if name, _ := x.X.(*ast.Ident); name != nil && (force || isTypeElem(x.Y)) {
  2689  				// x = name *x.Y
  2690  				return name, &ast.StarExpr{Star: x.OpPos, X: x.Y}
  2691  			}
  2692  		case token.OR:
  2693  			if name, lhs := extractName(x.X, force || isTypeElem(x.Y)); name != nil && lhs != nil {
  2694  				// x = name lhs|x.Y
  2695  				op := *x
  2696  				op.X = lhs
  2697  				return name, &op
  2698  			}
  2699  		}
  2700  	case *ast.CallExpr:
  2701  		if name, _ := x.Fun.(*ast.Ident); name != nil {
  2702  			if len(x.Args) == 1 && x.Ellipsis == token.NoPos && (force || isTypeElem(x.Args[0])) {
  2703  				// x = name (x.Args[0])
  2704  				// (Note that the cmd/compile/internal/syntax parser does not care
  2705  				// about syntax tree fidelity and does not preserve parentheses here.)
  2706  				return name, &ast.ParenExpr{
  2707  					Lparen: x.Lparen,
  2708  					X:      x.Args[0],
  2709  					Rparen: x.Rparen,
  2710  				}
  2711  			}
  2712  		}
  2713  	}
  2714  	return nil, x
  2715  }
  2716  
  2717  // isTypeElem reports whether x is a (possibly parenthesized) type element expression.
  2718  // The result is false if x could be a type element OR an ordinary (value) expression.
  2719  func isTypeElem(x ast.Expr) bool {
  2720  	switch x := x.(type) {
  2721  	case *ast.ArrayType, *ast.StructType, *ast.FuncType, *ast.InterfaceType, *ast.MapType, *ast.ChanType:
  2722  		return true
  2723  	case *ast.BinaryExpr:
  2724  		return isTypeElem(x.X) || isTypeElem(x.Y)
  2725  	case *ast.UnaryExpr:
  2726  		return x.Op == token.TILDE
  2727  	case *ast.ParenExpr:
  2728  		return isTypeElem(x.X)
  2729  	}
  2730  	return false
  2731  }
  2732  
  2733  func (p *parser) parseGenDecl(keyword token.Token, f parseSpecFunction) *ast.GenDecl {
  2734  	if p.trace {
  2735  		defer un(trace(p, "GenDecl("+keyword.String()+")"))
  2736  	}
  2737  
  2738  	doc := p.leadComment
  2739  	pos := p.expect(keyword)
  2740  	var lparen, rparen token.Pos
  2741  	var list []ast.Spec
  2742  	if p.tok == token.LPAREN {
  2743  		lparen = p.pos
  2744  		p.next()
  2745  		for iota := 0; p.tok != token.RPAREN && p.tok != token.EOF; iota++ {
  2746  			list = append(list, f(p.leadComment, keyword, iota))
  2747  		}
  2748  		rparen = p.expect(token.RPAREN)
  2749  		p.expectSemi()
  2750  	} else {
  2751  		list = append(list, f(nil, keyword, 0))
  2752  	}
  2753  
  2754  	return &ast.GenDecl{
  2755  		Doc:    doc,
  2756  		TokPos: pos,
  2757  		Tok:    keyword,
  2758  		Lparen: lparen,
  2759  		Specs:  list,
  2760  		Rparen: rparen,
  2761  	}
  2762  }
  2763  
  2764  func (p *parser) parseFuncDecl() *ast.FuncDecl {
  2765  	if p.trace {
  2766  		defer un(trace(p, "FunctionDecl"))
  2767  	}
  2768  
  2769  	doc := p.leadComment
  2770  	pos := p.expect(token.FUNC)
  2771  
  2772  	var recv *ast.FieldList
  2773  	if p.tok == token.LPAREN {
  2774  		_, recv = p.parseParameters(false)
  2775  	}
  2776  
  2777  	ident := p.parseIdent()
  2778  
  2779  	tparams, params := p.parseParameters(true)
  2780  	if recv != nil && tparams != nil {
  2781  		// Method declarations do not have type parameters. We parse them for a
  2782  		// better error message and improved error recovery.
  2783  		p.error(tparams.Opening, "method must have no type parameters")
  2784  		tparams = nil
  2785  	}
  2786  	results := p.parseResult()
  2787  
  2788  	var body *ast.BlockStmt
  2789  	switch p.tok {
  2790  	case token.LBRACE:
  2791  		body = p.parseBody()
  2792  		p.expectSemi()
  2793  	case token.SEMICOLON:
  2794  		p.next()
  2795  		if p.tok == token.LBRACE {
  2796  			// opening { of function declaration on next line
  2797  			p.error(p.pos, "unexpected semicolon or newline before {")
  2798  			body = p.parseBody()
  2799  			p.expectSemi()
  2800  		}
  2801  	default:
  2802  		p.expectSemi()
  2803  	}
  2804  
  2805  	decl := &ast.FuncDecl{
  2806  		Doc:  doc,
  2807  		Recv: recv,
  2808  		Name: ident,
  2809  		Type: &ast.FuncType{
  2810  			Func:       pos,
  2811  			TypeParams: tparams,
  2812  			Params:     params,
  2813  			Results:    results,
  2814  		},
  2815  		Body: body,
  2816  	}
  2817  	return decl
  2818  }
  2819  
  2820  func (p *parser) parseDecl(sync map[token.Token]bool) ast.Decl {
  2821  	if p.trace {
  2822  		defer un(trace(p, "Declaration"))
  2823  	}
  2824  
  2825  	var f parseSpecFunction
  2826  	switch p.tok {
  2827  	case token.IMPORT:
  2828  		f = p.parseImportSpec
  2829  
  2830  	case token.CONST, token.VAR:
  2831  		f = p.parseValueSpec
  2832  
  2833  	case token.TYPE:
  2834  		f = p.parseTypeSpec
  2835  
  2836  	case token.FUNC:
  2837  		return p.parseFuncDecl()
  2838  
  2839  	default:
  2840  		pos := p.pos
  2841  		p.errorExpected(pos, "declaration")
  2842  		p.advance(sync)
  2843  		return &ast.BadDecl{From: pos, To: p.pos}
  2844  	}
  2845  
  2846  	return p.parseGenDecl(p.tok, f)
  2847  }
  2848  
  2849  // ----------------------------------------------------------------------------
  2850  // Source files
  2851  
  2852  func (p *parser) parseFile() *ast.File {
  2853  	if p.trace {
  2854  		defer un(trace(p, "File"))
  2855  	}
  2856  
  2857  	// Don't bother parsing the rest if we had errors scanning the first token.
  2858  	// Likely not a Go source file at all.
  2859  	if p.errors.Len() != 0 {
  2860  		return nil
  2861  	}
  2862  
  2863  	// package clause
  2864  	doc := p.leadComment
  2865  	pos := p.expect(token.PACKAGE)
  2866  	// Go spec: The package clause is not a declaration;
  2867  	// the package name does not appear in any scope.
  2868  	ident := p.parseIdent()
  2869  	if ident.Name == "_" && p.mode&DeclarationErrors != 0 {
  2870  		p.error(p.pos, "invalid package name _")
  2871  	}
  2872  	p.expectSemi()
  2873  
  2874  	// Don't bother parsing the rest if we had errors parsing the package clause.
  2875  	// Likely not a Go source file at all.
  2876  	if p.errors.Len() != 0 {
  2877  		return nil
  2878  	}
  2879  
  2880  	var decls []ast.Decl
  2881  	if p.mode&PackageClauseOnly == 0 {
  2882  		// import decls
  2883  		for p.tok == token.IMPORT {
  2884  			decls = append(decls, p.parseGenDecl(token.IMPORT, p.parseImportSpec))
  2885  		}
  2886  
  2887  		if p.mode&ImportsOnly == 0 {
  2888  			// rest of package body
  2889  			prev := token.IMPORT
  2890  			for p.tok != token.EOF {
  2891  				// Continue to accept import declarations for error tolerance, but complain.
  2892  				if p.tok == token.IMPORT && prev != token.IMPORT {
  2893  					p.error(p.pos, "imports must appear before other declarations")
  2894  				}
  2895  				prev = p.tok
  2896  
  2897  				decls = append(decls, p.parseDecl(declStart))
  2898  			}
  2899  		}
  2900  	}
  2901  
  2902  	f := &ast.File{
  2903  		Doc:     doc,
  2904  		Package: pos,
  2905  		Name:    ident,
  2906  		Decls:   decls,
  2907  		// File{Start,End} are set by the defer in the caller.
  2908  		Imports:   p.imports,
  2909  		Comments:  p.comments,
  2910  		GoVersion: p.goVersion,
  2911  	}
  2912  	var declErr func(token.Pos, string)
  2913  	if p.mode&DeclarationErrors != 0 {
  2914  		declErr = p.error
  2915  	}
  2916  	if p.mode&SkipObjectResolution == 0 {
  2917  		resolveFile(f, p.file, declErr)
  2918  	}
  2919  
  2920  	return f
  2921  }
  2922  
  2923  // packIndexExpr returns an IndexExpr x[expr0] or IndexListExpr x[expr0, ...].
  2924  func packIndexExpr(x ast.Expr, lbrack token.Pos, exprs []ast.Expr, rbrack token.Pos) ast.Expr {
  2925  	switch len(exprs) {
  2926  	case 0:
  2927  		panic("internal error: packIndexExpr with empty expr slice")
  2928  	case 1:
  2929  		return &ast.IndexExpr{
  2930  			X:      x,
  2931  			Lbrack: lbrack,
  2932  			Index:  exprs[0],
  2933  			Rbrack: rbrack,
  2934  		}
  2935  	default:
  2936  		return &ast.IndexListExpr{
  2937  			X:       x,
  2938  			Lbrack:  lbrack,
  2939  			Indices: exprs,
  2940  			Rbrack:  rbrack,
  2941  		}
  2942  	}
  2943  }
  2944  

View as plain text