Source file src/go/parser/parser.go

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

View as plain text