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

View as plain text