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

View as plain text