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

View as plain text