src/go/parser/parser.go GO 2,945 lines View on github.com → Search inside
File is large — showing lines 1–2,000 of 2,945.
1// Copyright 2009 The Go Authors. All rights reserved.2// Use of this source code is governed by a BSD-style3// license that can be found in the LICENSE file.45// Package parser implements a parser for Go source files.6//7// The [ParseFile] function reads file input from a string, []byte, or8// io.Reader, and produces an [ast.File] representing the complete9// abstract syntax tree of the file.10//11// The [ParseExprFrom] function reads a single source-level expression and12// produces an [ast.Expr], the syntax tree of the expression.13//14// The parser accepts a larger language than is syntactically permitted by15// the Go spec, for simplicity, and for improved robustness in the presence16// of syntax errors. For instance, in method declarations, the receiver is17// treated like an ordinary parameter list and thus may contain multiple18// entries where the spec permits exactly one. Consequently, the corresponding19// field in the AST (ast.FuncDecl.Recv) field is not restricted to one entry.20//21// Applications that need to parse one or more complete packages of Go22// source code may find it more convenient not to interact directly23// with the parser but instead to use the Load function in package24// [golang.org/x/tools/go/packages].25package parser2627import (28	"fmt"29	"go/ast"30	"go/build/constraint"31	"go/scanner"32	"go/token"33	"strings"34)3536// The parser structure holds the parser's internal state.37type parser struct {38	file    *token.File39	errors  scanner.ErrorList40	scanner scanner.Scanner4142	// Tracing/debugging43	mode   Mode // parsing mode44	trace  bool // == (mode&Trace != 0)45	indent int  // indentation used for tracing output4647	// Comments48	comments    []*ast.CommentGroup49	leadComment *ast.CommentGroup // last lead comment50	lineComment *ast.CommentGroup // last line comment51	top         bool              // in top of file (before package clause)52	goVersion   string            // minimum Go version found in //go:build comment5354	// Next token55	pos token.Pos   // token position56	tok token.Token // one token look-ahead57	lit string      // token literal5859	// Error recovery60	// (used to limit the number of calls to parser.advance61	// w/o making scanning progress - avoids potential endless62	// loops across multiple parser functions during error recovery)63	syncPos token.Pos // last synchronization position64	syncCnt int       // number of parser.advance calls without progress6566	// Non-syntactic parser control67	exprLev int  // < 0: in control clause, >= 0: in expression68	inRhs   bool // if set, the parser is parsing a rhs expression6970	imports []*ast.ImportSpec // list of imports7172	// nestLev is used to track and limit the recursion depth73	// during parsing.74	nestLev int75}7677func (p *parser) init(file *token.File, src []byte, mode Mode) {78	p.file = file79	eh := func(pos token.Position, msg string) { p.errors.Add(pos, msg) }80	p.scanner.Init(p.file, src, eh, scanner.ScanComments)8182	p.top = true83	p.mode = mode84	p.trace = mode&Trace != 0 // for convenience (p.trace is used frequently)85	p.next()86}8788// end returns the end position of the current token89func (p *parser) end() token.Pos {90	return p.scanner.End()91}9293// ----------------------------------------------------------------------------94// Parsing support9596func (p *parser) printTrace(a ...any) {97	const dots = ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "98	const n = len(dots)99	pos := p.file.Position(p.pos)100	fmt.Printf("%5d:%3d: ", pos.Line, pos.Column)101	i := 2 * p.indent102	for i > n {103		fmt.Print(dots)104		i -= n105	}106	// i <= n107	fmt.Print(dots[0:i])108	fmt.Println(a...)109}110111func trace(p *parser, msg string) *parser {112	p.printTrace(msg, "(")113	p.indent++114	return p115}116117// Usage pattern: defer un(trace(p, "..."))118func un(p *parser) {119	p.indent--120	p.printTrace(")")121}122123// maxNestLev is the deepest we're willing to recurse during parsing124const maxNestLev int = 1e5125126func incNestLev(p *parser) *parser {127	p.nestLev++128	if p.nestLev > maxNestLev {129		p.error(p.pos, "exceeded max nesting depth")130		panic(bailout{})131	}132	return p133}134135// decNestLev is used to track nesting depth during parsing to prevent stack exhaustion.136// It is used along with incNestLev in a similar fashion to how un and trace are used.137func decNestLev(p *parser) {138	p.nestLev--139}140141// Advance to the next token.142func (p *parser) next0() {143	// Because of one-token look-ahead, print the previous token144	// when tracing as it provides a more readable output. The145	// very first token (!p.pos.IsValid()) is not initialized146	// (it is token.ILLEGAL), so don't print it.147	if p.trace && p.pos.IsValid() {148		s := p.tok.String()149		switch {150		case p.tok.IsLiteral():151			p.printTrace(s, p.lit)152		case p.tok.IsOperator(), p.tok.IsKeyword():153			p.printTrace("\"" + s + "\"")154		default:155			p.printTrace(s)156		}157	}158159	for {160		p.pos, p.tok, p.lit = p.scanner.Scan()161		if p.tok == token.COMMENT {162			if p.top && strings.HasPrefix(p.lit, "//go:build") {163				if x, err := constraint.Parse(p.lit); err == nil {164					p.goVersion = constraint.GoVersion(x)165				}166			}167			if p.mode&ParseComments == 0 {168				continue169			}170		} else {171			// Found a non-comment; top of file is over.172			p.top = false173		}174		break175	}176}177178// lineFor returns the line of pos, ignoring line directive adjustments.179func (p *parser) lineFor(pos token.Pos) int {180	return p.file.PositionFor(pos, false).Line181}182183// Consume a comment and return it and the line on which it ends.184func (p *parser) consumeComment() (comment *ast.Comment, endline int) {185	// /*-style comments may end on a different line than where they start.186	// Scan the comment for '\n' chars and adjust endline accordingly.187	endline = p.lineFor(p.pos)188	if p.lit[1] == '*' {189		// don't use range here - no need to decode Unicode code points190		for i := 0; i < len(p.lit); i++ {191			if p.lit[i] == '\n' {192				endline++193			}194		}195	}196197	comment = &ast.Comment{Slash: p.pos, Text: p.lit}198	p.next0()199200	return201}202203// Consume a group of adjacent comments, add it to the parser's204// comments list, and return it together with the line at which205// the last comment in the group ends. A non-comment token or n206// empty lines terminate a comment group.207func (p *parser) consumeCommentGroup(n int) (comments *ast.CommentGroup, endline int) {208	var list []*ast.Comment209	endline = p.lineFor(p.pos)210	for p.tok == token.COMMENT && p.lineFor(p.pos) <= endline+n {211		var comment *ast.Comment212		comment, endline = p.consumeComment()213		list = append(list, comment)214	}215216	// add comment group to the comments list217	comments = &ast.CommentGroup{List: list}218	p.comments = append(p.comments, comments)219220	return221}222223// Advance to the next non-comment token. In the process, collect224// any comment groups encountered, and remember the last lead and225// line comments.226//227// A lead comment is a comment group that starts and ends in a228// line without any other tokens and that is followed by a non-comment229// token on the line immediately after the comment group.230//231// A line comment is a comment group that follows a non-comment232// token on the same line, and that has no tokens after it on the line233// where it ends.234//235// Lead and line comments may be considered documentation that is236// stored in the AST.237func (p *parser) next() {238	p.leadComment = nil239	p.lineComment = nil240	prev := p.pos241	p.next0()242243	if p.tok == token.COMMENT {244		var comment *ast.CommentGroup245		var endline int246247		if p.lineFor(p.pos) == p.lineFor(prev) {248			// The comment is on same line as the previous token; it249			// cannot be a lead comment but may be a line comment.250			comment, endline = p.consumeCommentGroup(0)251			if p.lineFor(p.pos) != endline || p.tok == token.SEMICOLON || p.tok == token.EOF {252				// The next token is on a different line, thus253				// the last comment group is a line comment.254				p.lineComment = comment255			}256		}257258		// consume successor comments, if any259		endline = -1260		for p.tok == token.COMMENT {261			comment, endline = p.consumeCommentGroup(1)262		}263264		if endline+1 == p.lineFor(p.pos) {265			// The next token is following on the line immediately after the266			// comment group, thus the last comment group is a lead comment.267			p.leadComment = comment268		}269	}270}271272// A bailout panic is raised to indicate early termination. pos and msg are273// only populated when bailing out of object resolution.274type bailout struct {275	pos token.Pos276	msg string277}278279func (p *parser) error(pos token.Pos, msg string) {280	if p.trace {281		defer un(trace(p, "error: "+msg))282	}283284	epos := p.file.Position(pos)285286	// If AllErrors is not set, discard errors reported on the same line287	// as the last recorded error and stop parsing if there are more than288	// 10 errors.289	if p.mode&AllErrors == 0 {290		n := len(p.errors)291		if n > 0 && p.errors[n-1].Pos.Line == epos.Line {292			return // discard - likely a spurious error293		}294		if n > 10 {295			panic(bailout{})296		}297	}298299	p.errors.Add(epos, msg)300}301302func (p *parser) errorExpected(pos token.Pos, msg string) {303	msg = "expected " + msg304	if pos == p.pos {305		// the error happened at the current position;306		// make the error message more specific307		switch {308		case p.tok == token.SEMICOLON && p.lit == "\n":309			msg += ", found newline"310		case p.tok.IsLiteral():311			// print 123 rather than 'INT', etc.312			msg += ", found " + p.lit313		default:314			msg += ", found '" + p.tok.String() + "'"315		}316	}317	p.error(pos, msg)318}319320func (p *parser) expect(tok token.Token) token.Pos {321	pos := p.pos322	if p.tok != tok {323		p.errorExpected(pos, "'"+tok.String()+"'")324	}325	p.next() // make progress326	return pos327}328329// expect2 is like expect, but it returns an invalid position330// if the expected token is not found.331func (p *parser) expect2(tok token.Token) (pos token.Pos) {332	if p.tok == tok {333		pos = p.pos334	} else {335		p.errorExpected(p.pos, "'"+tok.String()+"'")336	}337	p.next() // make progress338	return339}340341// expectClosing is like expect but provides a better error message342// for the common case of a missing comma before a newline.343func (p *parser) expectClosing(tok token.Token, context string) token.Pos {344	if p.tok != tok && p.tok == token.SEMICOLON && p.lit == "\n" {345		p.error(p.pos, "missing ',' before newline in "+context)346		p.next()347	}348	return p.expect(tok)349}350351// expectSemi consumes a semicolon and returns the applicable line comment.352func (p *parser) expectSemi() (comment *ast.CommentGroup) {353	switch p.tok {354	case token.RPAREN, token.RBRACE:355		return nil // semicolon is optional before a closing ')' or '}'356	case token.COMMA:357		// permit a ',' instead of a ';' but complain358		p.errorExpected(p.pos, "';'")359		fallthrough360	case token.SEMICOLON:361		if p.lit == ";" {362			// explicit semicolon363			p.next()364			comment = p.lineComment // use following comments365		} else {366			// artificial semicolon367			comment = p.lineComment // use preceding comments368			p.next()369		}370		return comment371	default:372		p.errorExpected(p.pos, "';'")373		p.advance(stmtStart)374		return nil375	}376}377378func (p *parser) atComma(context string, follow token.Token) bool {379	if p.tok == token.COMMA {380		return true381	}382	if p.tok != follow {383		msg := "missing ','"384		if p.tok == token.SEMICOLON && p.lit == "\n" {385			msg += " before newline"386		}387		p.error(p.pos, msg+" in "+context)388		return true // "insert" comma and continue389	}390	return false391}392393func assert(cond bool, msg string) {394	if !cond {395		panic("go/parser internal error: " + msg)396	}397}398399// advance consumes tokens until the current token p.tok400// is in the 'to' set, or token.EOF. For error recovery.401func (p *parser) advance(to map[token.Token]bool) {402	for ; p.tok != token.EOF; p.next() {403		if to[p.tok] {404			// Return only if parser made some progress since last405			// sync or if it has not reached 10 advance calls without406			// progress. Otherwise consume at least one token to407			// avoid an endless parser loop (it is possible that408			// both parseOperand and parseStmt call advance and409			// correctly do not advance, thus the need for the410			// invocation limit p.syncCnt).411			if p.pos == p.syncPos && p.syncCnt < 10 {412				p.syncCnt++413				return414			}415			if p.pos > p.syncPos {416				p.syncPos = p.pos417				p.syncCnt = 0418				return419			}420			// Reaching here indicates a parser bug, likely an421			// incorrect token list in this function, but it only422			// leads to skipping of possibly correct code if a423			// previous error is present, and thus is preferred424			// over a non-terminating parse.425		}426	}427}428429var stmtStart = map[token.Token]bool{430	token.BREAK:       true,431	token.CONST:       true,432	token.CONTINUE:    true,433	token.DEFER:       true,434	token.FALLTHROUGH: true,435	token.FOR:         true,436	token.GO:          true,437	token.GOTO:        true,438	token.IF:          true,439	token.RETURN:      true,440	token.SELECT:      true,441	token.SWITCH:      true,442	token.TYPE:        true,443	token.VAR:         true,444}445446var declStart = map[token.Token]bool{447	token.IMPORT: true,448	token.CONST:  true,449	token.TYPE:   true,450	token.VAR:    true,451}452453var exprEnd = map[token.Token]bool{454	token.COMMA:     true,455	token.COLON:     true,456	token.SEMICOLON: true,457	token.RPAREN:    true,458	token.RBRACK:    true,459	token.RBRACE:    true,460}461462// ----------------------------------------------------------------------------463// Identifiers464465func (p *parser) parseIdent() *ast.Ident {466	pos := p.pos467	name := "_"468	if p.tok == token.IDENT {469		name = p.lit470		p.next()471	} else {472		p.expect(token.IDENT) // use expect() error handling473	}474	return &ast.Ident{NamePos: pos, Name: name}475}476477func (p *parser) parseIdentList() (list []*ast.Ident) {478	if p.trace {479		defer un(trace(p, "IdentList"))480	}481482	list = append(list, p.parseIdent())483	for p.tok == token.COMMA {484		p.next()485		list = append(list, p.parseIdent())486	}487488	return489}490491// ----------------------------------------------------------------------------492// Common productions493494// If lhs is set, result list elements which are identifiers are not resolved.495func (p *parser) parseExprList() (list []ast.Expr) {496	if p.trace {497		defer un(trace(p, "ExpressionList"))498	}499500	list = append(list, p.parseExpr())501	for p.tok == token.COMMA {502		p.next()503		list = append(list, p.parseExpr())504	}505506	return507}508509func (p *parser) parseList(inRhs bool) []ast.Expr {510	old := p.inRhs511	p.inRhs = inRhs512	list := p.parseExprList()513	p.inRhs = old514	return list515}516517// ----------------------------------------------------------------------------518// Types519520func (p *parser) parseType() ast.Expr {521	if p.trace {522		defer un(trace(p, "Type"))523	}524525	typ := p.tryIdentOrType()526527	if typ == nil {528		pos := p.pos529		p.errorExpected(pos, "type")530		p.advance(exprEnd)531		return &ast.BadExpr{From: pos, To: p.pos}532	}533534	return typ535}536537func (p *parser) parseQualifiedIdent(ident *ast.Ident) ast.Expr {538	if p.trace {539		defer un(trace(p, "QualifiedIdent"))540	}541542	typ := p.parseTypeName(ident)543	if p.tok == token.LBRACK {544		typ = p.parseTypeInstance(typ)545	}546547	return typ548}549550// If the result is an identifier, it is not resolved.551func (p *parser) parseTypeName(ident *ast.Ident) ast.Expr {552	if p.trace {553		defer un(trace(p, "TypeName"))554	}555556	if ident == nil {557		ident = p.parseIdent()558	}559560	if p.tok == token.PERIOD {561		// ident is a package name562		p.next()563		sel := p.parseIdent()564		return &ast.SelectorExpr{X: ident, Sel: sel}565	}566567	return ident568}569570// "[" has already been consumed, and lbrack is its position.571// If len != nil it is the already consumed array length.572func (p *parser) parseArrayType(lbrack token.Pos, len ast.Expr) *ast.ArrayType {573	if p.trace {574		defer un(trace(p, "ArrayType"))575	}576577	if len == nil {578		p.exprLev++579		// always permit ellipsis for more fault-tolerant parsing580		if p.tok == token.ELLIPSIS {581			len = &ast.Ellipsis{Ellipsis: p.pos}582			p.next()583		} else if p.tok != token.RBRACK {584			len = p.parseRhs()585		}586		p.exprLev--587	}588	if p.tok == token.COMMA {589		// Trailing commas are accepted in type parameter590		// lists but not in array type declarations.591		// Accept for better error handling but complain.592		p.error(p.pos, "unexpected comma; expecting ]")593		p.next()594	}595	p.expect(token.RBRACK)596	elt := p.parseType()597	return &ast.ArrayType{Lbrack: lbrack, Len: len, Elt: elt}598}599600func (p *parser) parseArrayFieldOrTypeInstance(x *ast.Ident) (*ast.Ident, ast.Expr) {601	if p.trace {602		defer un(trace(p, "ArrayFieldOrTypeInstance"))603	}604605	lbrack := p.expect(token.LBRACK)606	trailingComma := token.NoPos // if valid, the position of a trailing comma preceding the ']'607	var args []ast.Expr608	if p.tok != token.RBRACK {609		p.exprLev++610		args = append(args, p.parseRhs())611		for p.tok == token.COMMA {612			comma := p.pos613			p.next()614			if p.tok == token.RBRACK {615				trailingComma = comma616				break617			}618			args = append(args, p.parseRhs())619		}620		p.exprLev--621	}622	rbrack := p.expect(token.RBRACK)623624	if len(args) == 0 {625		// x []E626		elt := p.parseType()627		return x, &ast.ArrayType{Lbrack: lbrack, Elt: elt}628	}629630	// x [P]E or x[P]631	if len(args) == 1 {632		elt := p.tryIdentOrType()633		if elt != nil {634			// x [P]E635			if trailingComma.IsValid() {636				// Trailing commas are invalid in array type fields.637				p.error(trailingComma, "unexpected comma; expecting ]")638			}639			return x, &ast.ArrayType{Lbrack: lbrack, Len: args[0], Elt: elt}640		}641	}642643	// x[P], x[P1, P2], ...644	return nil, packIndexExpr(x, lbrack, args, rbrack)645}646647func (p *parser) parseFieldDecl() *ast.Field {648	if p.trace {649		defer un(trace(p, "FieldDecl"))650	}651652	doc := p.leadComment653654	var names []*ast.Ident655	var typ ast.Expr656	switch p.tok {657	case token.IDENT:658		name := p.parseIdent()659		if p.tok == token.PERIOD || p.tok == token.STRING || p.tok == token.SEMICOLON || p.tok == token.RBRACE {660			// embedded type661			typ = name662			if p.tok == token.PERIOD {663				typ = p.parseQualifiedIdent(name)664			}665		} else {666			// name1, name2, ... T667			names = []*ast.Ident{name}668			for p.tok == token.COMMA {669				p.next()670				names = append(names, p.parseIdent())671			}672			// Careful dance: We don't know if we have an embedded instantiated673			// type T[P1, P2, ...] or a field T of array type []E or [P]E.674			if len(names) == 1 && p.tok == token.LBRACK {675				name, typ = p.parseArrayFieldOrTypeInstance(name)676				if name == nil {677					names = nil678				}679			} else {680				// T P681				typ = p.parseType()682			}683		}684	case token.MUL:685		star := p.pos686		p.next()687		if p.tok == token.LPAREN {688			// *(T)689			p.error(p.pos, "cannot parenthesize embedded type")690			p.next()691			typ = p.parseQualifiedIdent(nil)692			// expect closing ')' but no need to complain if missing693			if p.tok == token.RPAREN {694				p.next()695			}696		} else {697			// *T698			typ = p.parseQualifiedIdent(nil)699		}700		typ = &ast.StarExpr{Star: star, X: typ}701702	case token.LPAREN:703		p.error(p.pos, "cannot parenthesize embedded type")704		p.next()705		if p.tok == token.MUL {706			// (*T)707			star := p.pos708			p.next()709			typ = &ast.StarExpr{Star: star, X: p.parseQualifiedIdent(nil)}710		} else {711			// (T)712			typ = p.parseQualifiedIdent(nil)713		}714		// expect closing ')' but no need to complain if missing715		if p.tok == token.RPAREN {716			p.next()717		}718719	default:720		pos := p.pos721		p.errorExpected(pos, "field name or embedded type")722		p.advance(exprEnd)723		typ = &ast.BadExpr{From: pos, To: p.pos}724	}725726	var tag *ast.BasicLit727	if p.tok == token.STRING {728		tag = &ast.BasicLit{ValuePos: p.pos, ValueEnd: p.end(), Kind: p.tok, Value: p.lit}729		p.next()730	}731732	comment := p.expectSemi()733734	field := &ast.Field{Doc: doc, Names: names, Type: typ, Tag: tag, Comment: comment}735	return field736}737738func (p *parser) parseStructType() *ast.StructType {739	if p.trace {740		defer un(trace(p, "StructType"))741	}742743	pos := p.expect(token.STRUCT)744	lbrace := p.expect(token.LBRACE)745	var list []*ast.Field746	for p.tok == token.IDENT || p.tok == token.MUL || p.tok == token.LPAREN {747		// a field declaration cannot start with a '(' but we accept748		// it here for more robust parsing and better error messages749		// (parseFieldDecl will check and complain if necessary)750		list = append(list, p.parseFieldDecl())751	}752	rbrace := p.expect(token.RBRACE)753754	return &ast.StructType{755		Struct: pos,756		Fields: &ast.FieldList{757			Opening: lbrace,758			List:    list,759			Closing: rbrace,760		},761	}762}763764func (p *parser) parsePointerType() *ast.StarExpr {765	if p.trace {766		defer un(trace(p, "PointerType"))767	}768769	star := p.expect(token.MUL)770	base := p.parseType()771772	return &ast.StarExpr{Star: star, X: base}773}774775func (p *parser) parseDotsType() *ast.Ellipsis {776	if p.trace {777		defer un(trace(p, "DotsType"))778	}779780	pos := p.expect(token.ELLIPSIS)781	elt := p.parseType()782783	return &ast.Ellipsis{Ellipsis: pos, Elt: elt}784}785786type field struct {787	name *ast.Ident788	typ  ast.Expr789}790791func (p *parser) parseParamDecl(name *ast.Ident, typeSetsOK bool) (f field) {792	// TODO(rFindley) refactor to be more similar to paramDeclOrNil in the syntax793	// package794	if p.trace {795		defer un(trace(p, "ParamDecl"))796	}797798	ptok := p.tok799	if name != nil {800		p.tok = token.IDENT // force token.IDENT case in switch below801	} else if typeSetsOK && p.tok == token.TILDE {802		// "~" ...803		return field{nil, p.embeddedElem(nil)}804	}805806	switch p.tok {807	case token.IDENT:808		// name809		if name != nil {810			f.name = name811			p.tok = ptok812		} else {813			f.name = p.parseIdent()814		}815		switch p.tok {816		case token.IDENT, token.MUL, token.ARROW, token.FUNC, token.CHAN, token.MAP, token.STRUCT, token.INTERFACE, token.LPAREN:817			// name type818			f.typ = p.parseType()819820		case token.LBRACK:821			// name "[" type1, ..., typeN "]" or name "[" n "]" type822			f.name, f.typ = p.parseArrayFieldOrTypeInstance(f.name)823824		case token.ELLIPSIS:825			// name "..." type826			f.typ = p.parseDotsType()827			return // don't allow ...type "|" ...828829		case token.PERIOD:830			// name "." ...831			f.typ = p.parseQualifiedIdent(f.name)832			f.name = nil833834		case token.TILDE:835			if typeSetsOK {836				f.typ = p.embeddedElem(nil)837				return838			}839840		case token.OR:841			if typeSetsOK {842				// name "|" typeset843				f.typ = p.embeddedElem(f.name)844				f.name = nil845				return846			}847		}848849	case token.MUL, token.ARROW, token.FUNC, token.LBRACK, token.CHAN, token.MAP, token.STRUCT, token.INTERFACE, token.LPAREN:850		// type851		f.typ = p.parseType()852853	case token.ELLIPSIS:854		// "..." type855		// (always accepted)856		f.typ = p.parseDotsType()857		return // don't allow ...type "|" ...858859	default:860		// TODO(rfindley): this is incorrect in the case of type parameter lists861		//                 (should be "']'" in that case)862		p.errorExpected(p.pos, "')'")863		p.advance(exprEnd)864	}865866	// [name] type "|"867	if typeSetsOK && p.tok == token.OR && f.typ != nil {868		f.typ = p.embeddedElem(f.typ)869	}870871	return872}873874func (p *parser) parseParameterList(name0 *ast.Ident, typ0 ast.Expr, closing token.Token, dddok bool) (params []*ast.Field) {875	if p.trace {876		defer un(trace(p, "ParameterList"))877	}878879	// Type parameters are the only parameter list closed by ']'.880	tparams := closing == token.RBRACK881882	pos0 := p.pos883	if name0 != nil {884		pos0 = name0.Pos()885	} else if typ0 != nil {886		pos0 = typ0.Pos()887	}888889	// Note: The code below matches the corresponding code in the syntax890	//       parser closely. Changes must be reflected in either parser.891	//       For the code to match, we use the local []field list that892	//       corresponds to []syntax.Field. At the end, the list must be893	//       converted into an []*ast.Field.894895	var list []field896	var named int // number of parameters that have an explicit name and type897	var typed int // number of parameters that have an explicit type898899	for name0 != nil || p.tok != closing && p.tok != token.EOF {900		var par field901		if typ0 != nil {902			if tparams {903				typ0 = p.embeddedElem(typ0)904			}905			par = field{name0, typ0}906		} else {907			par = p.parseParamDecl(name0, tparams)908		}909		name0 = nil // 1st name was consumed if present910		typ0 = nil  // 1st typ was consumed if present911		if par.name != nil || par.typ != nil {912			list = append(list, par)913			if par.name != nil && par.typ != nil {914				named++915			}916			if par.typ != nil {917				typed++918			}919		}920		if !p.atComma("parameter list", closing) {921			break922		}923		p.next()924	}925926	if len(list) == 0 {927		return // not uncommon928	}929930	// distribute parameter types (len(list) > 0)931	if named == 0 {932		// all unnamed => found names are type names933		for i := range list {934			par := &list[i]935			if typ := par.name; typ != nil {936				par.typ = typ937				par.name = nil938			}939		}940		if tparams {941			// This is the same error handling as below, adjusted for type parameters only.942			// See comment below for details. (go.dev/issue/64534)943			var errPos token.Pos944			var msg string945			if named == typed /* same as typed == 0 */ {946				errPos = p.pos // position error at closing ]947				msg = "missing type constraint"948			} else {949				errPos = pos0 // position at opening [ or first name950				msg = "missing type parameter name"951				if len(list) == 1 {952					msg += " or invalid array length"953				}954			}955			p.error(errPos, msg)956		}957	} else if named != len(list) {958		// some named or we're in a type parameter list => all must be named959		var errPos token.Pos // left-most error position (or invalid)960		var typ ast.Expr     // current type (from right to left)961		for i := range list {962			if par := &list[len(list)-i-1]; par.typ != nil {963				typ = par.typ964				if par.name == nil {965					errPos = typ.Pos()966					n := ast.NewIdent("_")967					n.NamePos = errPos // correct position968					par.name = n969				}970			} else if typ != nil {971				par.typ = typ972			} else {973				// par.typ == nil && typ == nil => we only have a par.name974				errPos = par.name.Pos()975				par.typ = &ast.BadExpr{From: errPos, To: p.pos}976			}977		}978		if errPos.IsValid() {979			// Not all parameters are named because named != len(list).980			// If named == typed, there must be parameters that have no types.981			// They must be at the end of the parameter list, otherwise types982			// would have been filled in by the right-to-left sweep above and983			// there would be no error.984			// If tparams is set, the parameter list is a type parameter list.985			var msg string986			if named == typed {987				errPos = p.pos // position error at closing token ) or ]988				if tparams {989					msg = "missing type constraint"990				} else {991					msg = "missing parameter type"992				}993			} else {994				if tparams {995					msg = "missing type parameter name"996					// go.dev/issue/60812997					if len(list) == 1 {998						msg += " or invalid array length"999					}1000				} else {1001					msg = "missing parameter name"1002				}1003			}1004			p.error(errPos, msg)1005		}1006	}10071008	// check use of ...1009	first := true // only report first occurrence1010	for i, _ := range list {1011		f := &list[i]1012		if t, _ := f.typ.(*ast.Ellipsis); t != nil && (!dddok || i+1 < len(list)) {1013			if first {1014				first = false1015				if dddok {1016					p.error(t.Ellipsis, "can only use ... with final parameter")1017				} else {1018					p.error(t.Ellipsis, "invalid use of ...")1019				}1020			}1021			// use T instead of invalid ...T1022			// TODO(gri) would like to use `f.typ = t.Elt` but that causes problems1023			//           with the resolver in cases of reuse of the same identifier1024			f.typ = &ast.BadExpr{From: t.Pos(), To: t.End()}1025		}1026	}10271028	// Convert list to []*ast.Field.1029	// If list contains types only, each type gets its own ast.Field.1030	if named == 0 {1031		// parameter list consists of types only1032		for _, par := range list {1033			assert(par.typ != nil, "nil type in unnamed parameter list")1034			params = append(params, &ast.Field{Type: par.typ})1035		}1036		return1037	}10381039	// If the parameter list consists of named parameters with types,1040	// collect all names with the same types into a single ast.Field.1041	var names []*ast.Ident1042	var typ ast.Expr1043	addParams := func() {1044		assert(typ != nil, "nil type in named parameter list")1045		field := &ast.Field{Names: names, Type: typ}1046		params = append(params, field)1047		names = nil1048	}1049	for _, par := range list {1050		if par.typ != typ {1051			if len(names) > 0 {1052				addParams()1053			}1054			typ = par.typ1055		}1056		names = append(names, par.name)1057	}1058	if len(names) > 0 {1059		addParams()1060	}1061	return1062}10631064func (p *parser) parseTypeParameters() *ast.FieldList {1065	if p.trace {1066		defer un(trace(p, "TypeParameters"))1067	}10681069	lbrack := p.expect(token.LBRACK)1070	var list []*ast.Field1071	if p.tok != token.RBRACK {1072		list = p.parseParameterList(nil, nil, token.RBRACK, false)1073	}1074	rbrack := p.expect(token.RBRACK)10751076	if len(list) == 0 {1077		p.error(rbrack, "empty type parameter list")1078		return nil // avoid follow-on errors1079	}10801081	return &ast.FieldList{Opening: lbrack, List: list, Closing: rbrack}1082}10831084func (p *parser) parseParameters(result bool) *ast.FieldList {1085	if p.trace {1086		defer un(trace(p, "Parameters"))1087	}10881089	if !result || p.tok == token.LPAREN {1090		lparen := p.expect(token.LPAREN)1091		var list []*ast.Field1092		if p.tok != token.RPAREN {1093			list = p.parseParameterList(nil, nil, token.RPAREN, !result)1094		}1095		rparen := p.expect(token.RPAREN)1096		return &ast.FieldList{Opening: lparen, List: list, Closing: rparen}1097	}10981099	if typ := p.tryIdentOrType(); typ != nil {1100		list := make([]*ast.Field, 1)1101		list[0] = &ast.Field{Type: typ}1102		return &ast.FieldList{List: list}1103	}11041105	return nil1106}11071108func (p *parser) parseFuncType() *ast.FuncType {1109	if p.trace {1110		defer un(trace(p, "FuncType"))1111	}11121113	pos := p.expect(token.FUNC)1114	// accept type parameters for more tolerant parsing but complain1115	if p.tok == token.LBRACK {1116		tparams := p.parseTypeParameters()1117		if tparams != nil {1118			p.error(tparams.Opening, "function type must have no type parameters")1119		}1120	}1121	params := p.parseParameters(false)1122	results := p.parseParameters(true)11231124	return &ast.FuncType{Func: pos, Params: params, Results: results}1125}11261127func (p *parser) parseMethodSpec() *ast.Field {1128	if p.trace {1129		defer un(trace(p, "MethodSpec"))1130	}11311132	doc := p.leadComment1133	var idents []*ast.Ident1134	var typ ast.Expr1135	x := p.parseTypeName(nil)1136	if ident, _ := x.(*ast.Ident); ident != nil {1137		switch {1138		case p.tok == token.LBRACK:1139			// generic method or embedded instantiated type1140			lbrack := p.pos1141			p.next()1142			p.exprLev++1143			x := p.parseExpr()1144			p.exprLev--1145			if name0, _ := x.(*ast.Ident); name0 != nil && p.tok != token.COMMA && p.tok != token.RBRACK {1146				// generic method m[T any]1147				//1148				// Interface methods do not have type parameters. We parse them for a1149				// better error message and improved error recovery.1150				_ = p.parseParameterList(name0, nil, token.RBRACK, false)1151				_ = p.expect(token.RBRACK)1152				p.error(lbrack, "interface method must have no type parameters")11531154				// TODO(rfindley) refactor to share code with parseFuncType.1155				params := p.parseParameters(false)1156				results := p.parseParameters(true)1157				idents = []*ast.Ident{ident}1158				typ = &ast.FuncType{1159					Func:    token.NoPos,1160					Params:  params,1161					Results: results,1162				}1163			} else {1164				// embedded instantiated type1165				// TODO(rfindley) should resolve all identifiers in x.1166				list := []ast.Expr{x}1167				if p.atComma("type argument list", token.RBRACK) {1168					p.exprLev++1169					p.next()1170					for p.tok != token.RBRACK && p.tok != token.EOF {1171						list = append(list, p.parseType())1172						if !p.atComma("type argument list", token.RBRACK) {1173							break1174						}1175						p.next()1176					}1177					p.exprLev--1178				}1179				rbrack := p.expectClosing(token.RBRACK, "type argument list")1180				typ = packIndexExpr(ident, lbrack, list, rbrack)1181			}1182		case p.tok == token.LPAREN:1183			// ordinary method1184			// TODO(rfindley) refactor to share code with parseFuncType.1185			params := p.parseParameters(false)1186			results := p.parseParameters(true)1187			idents = []*ast.Ident{ident}1188			typ = &ast.FuncType{Func: token.NoPos, Params: params, Results: results}1189		default:1190			// embedded type1191			typ = x1192		}1193	} else {1194		// embedded, possibly instantiated type1195		typ = x1196		if p.tok == token.LBRACK {1197			// embedded instantiated interface1198			typ = p.parseTypeInstance(typ)1199		}1200	}12011202	// Comment is added at the callsite: the field below may joined with1203	// additional type specs using '|'.1204	// TODO(rfindley) this should be refactored.1205	// TODO(rfindley) add more tests for comment handling.1206	return &ast.Field{Doc: doc, Names: idents, Type: typ}1207}12081209func (p *parser) embeddedElem(x ast.Expr) ast.Expr {1210	if p.trace {1211		defer un(trace(p, "EmbeddedElem"))1212	}1213	if x == nil {1214		x = p.embeddedTerm()1215	}1216	for p.tok == token.OR {1217		t := new(ast.BinaryExpr)1218		t.OpPos = p.pos1219		t.Op = token.OR1220		p.next()1221		t.X = x1222		t.Y = p.embeddedTerm()1223		x = t1224	}1225	return x1226}12271228func (p *parser) embeddedTerm() ast.Expr {1229	if p.trace {1230		defer un(trace(p, "EmbeddedTerm"))1231	}1232	if p.tok == token.TILDE {1233		t := new(ast.UnaryExpr)1234		t.OpPos = p.pos1235		t.Op = token.TILDE1236		p.next()1237		t.X = p.parseType()1238		return t1239	}12401241	t := p.tryIdentOrType()1242	if t == nil {1243		pos := p.pos1244		p.errorExpected(pos, "~ term or type")1245		p.advance(exprEnd)1246		return &ast.BadExpr{From: pos, To: p.pos}1247	}12481249	return t1250}12511252func (p *parser) parseInterfaceType() *ast.InterfaceType {1253	if p.trace {1254		defer un(trace(p, "InterfaceType"))1255	}12561257	pos := p.expect(token.INTERFACE)1258	lbrace := p.expect(token.LBRACE)12591260	var list []*ast.Field12611262parseElements:1263	for {1264		switch {1265		case p.tok == token.IDENT:1266			f := p.parseMethodSpec()1267			if f.Names == nil {1268				f.Type = p.embeddedElem(f.Type)1269			}1270			f.Comment = p.expectSemi()1271			list = append(list, f)1272		case p.tok == token.TILDE:1273			typ := p.embeddedElem(nil)1274			comment := p.expectSemi()1275			list = append(list, &ast.Field{Type: typ, Comment: comment})1276		default:1277			if t := p.tryIdentOrType(); t != nil {1278				typ := p.embeddedElem(t)1279				comment := p.expectSemi()1280				list = append(list, &ast.Field{Type: typ, Comment: comment})1281			} else {1282				break parseElements1283			}1284		}1285	}12861287	// TODO(rfindley): the error produced here could be improved, since we could1288	// accept an identifier, 'type', or a '}' at this point.1289	rbrace := p.expect(token.RBRACE)12901291	return &ast.InterfaceType{1292		Interface: pos,1293		Methods: &ast.FieldList{1294			Opening: lbrace,1295			List:    list,1296			Closing: rbrace,1297		},1298	}1299}13001301func (p *parser) parseMapType() *ast.MapType {1302	if p.trace {1303		defer un(trace(p, "MapType"))1304	}13051306	pos := p.expect(token.MAP)1307	p.expect(token.LBRACK)1308	key := p.parseType()1309	p.expect(token.RBRACK)1310	value := p.parseType()13111312	return &ast.MapType{Map: pos, Key: key, Value: value}1313}13141315func (p *parser) parseChanType() *ast.ChanType {1316	if p.trace {1317		defer un(trace(p, "ChanType"))1318	}13191320	pos := p.pos1321	dir := ast.SEND | ast.RECV1322	var arrow token.Pos1323	if p.tok == token.CHAN {1324		p.next()1325		if p.tok == token.ARROW {1326			arrow = p.pos1327			p.next()1328			dir = ast.SEND1329		}1330	} else {1331		arrow = p.expect(token.ARROW)1332		p.expect(token.CHAN)1333		dir = ast.RECV1334	}1335	value := p.parseType()13361337	return &ast.ChanType{Begin: pos, Arrow: arrow, Dir: dir, Value: value}1338}13391340func (p *parser) parseTypeInstance(typ ast.Expr) ast.Expr {1341	if p.trace {1342		defer un(trace(p, "TypeInstance"))1343	}13441345	opening := p.expect(token.LBRACK)1346	p.exprLev++1347	var list []ast.Expr1348	for p.tok != token.RBRACK && p.tok != token.EOF {1349		list = append(list, p.parseType())1350		if !p.atComma("type argument list", token.RBRACK) {1351			break1352		}1353		p.next()1354	}1355	p.exprLev--13561357	closing := p.expectClosing(token.RBRACK, "type argument list")13581359	if len(list) == 0 {1360		p.errorExpected(closing, "type argument list")1361		return &ast.IndexExpr{1362			X:      typ,1363			Lbrack: opening,1364			Index:  &ast.BadExpr{From: opening + 1, To: closing},1365			Rbrack: closing,1366		}1367	}13681369	return packIndexExpr(typ, opening, list, closing)1370}13711372func (p *parser) tryIdentOrType() ast.Expr {1373	defer decNestLev(incNestLev(p))13741375	switch p.tok {1376	case token.IDENT:1377		typ := p.parseTypeName(nil)1378		if p.tok == token.LBRACK {1379			typ = p.parseTypeInstance(typ)1380		}1381		return typ1382	case token.LBRACK:1383		lbrack := p.expect(token.LBRACK)1384		return p.parseArrayType(lbrack, nil)1385	case token.STRUCT:1386		return p.parseStructType()1387	case token.MUL:1388		return p.parsePointerType()1389	case token.FUNC:1390		return p.parseFuncType()1391	case token.INTERFACE:1392		return p.parseInterfaceType()1393	case token.MAP:1394		return p.parseMapType()1395	case token.CHAN, token.ARROW:1396		return p.parseChanType()1397	case token.LPAREN:1398		lparen := p.pos1399		p.next()1400		typ := p.parseType()1401		rparen := p.expect(token.RPAREN)1402		return &ast.ParenExpr{Lparen: lparen, X: typ, Rparen: rparen}1403	}14041405	// no type found1406	return nil1407}14081409// ----------------------------------------------------------------------------1410// Blocks14111412func (p *parser) parseStmtList() (list []ast.Stmt) {1413	if p.trace {1414		defer un(trace(p, "StatementList"))1415	}14161417	for p.tok != token.CASE && p.tok != token.DEFAULT && p.tok != token.RBRACE && p.tok != token.EOF {1418		list = append(list, p.parseStmt())1419	}14201421	return1422}14231424func (p *parser) parseBody() *ast.BlockStmt {1425	if p.trace {1426		defer un(trace(p, "Body"))1427	}14281429	lbrace := p.expect(token.LBRACE)1430	list := p.parseStmtList()1431	rbrace := p.expect2(token.RBRACE)14321433	return &ast.BlockStmt{Lbrace: lbrace, List: list, Rbrace: rbrace}1434}14351436func (p *parser) parseBlockStmt() *ast.BlockStmt {1437	if p.trace {1438		defer un(trace(p, "BlockStmt"))1439	}14401441	lbrace := p.expect(token.LBRACE)1442	list := p.parseStmtList()1443	rbrace := p.expect2(token.RBRACE)14441445	return &ast.BlockStmt{Lbrace: lbrace, List: list, Rbrace: rbrace}1446}14471448// ----------------------------------------------------------------------------1449// Expressions14501451func (p *parser) parseFuncTypeOrLit() ast.Expr {1452	if p.trace {1453		defer un(trace(p, "FuncTypeOrLit"))1454	}14551456	typ := p.parseFuncType()1457	if p.tok != token.LBRACE {1458		// function type only1459		return typ1460	}14611462	p.exprLev++1463	body := p.parseBody()1464	p.exprLev--14651466	return &ast.FuncLit{Type: typ, Body: body}1467}14681469// parseOperand may return an expression or a raw type (incl. array1470// types of the form [...]T). Callers must verify the result.1471func (p *parser) parseOperand() ast.Expr {1472	if p.trace {1473		defer un(trace(p, "Operand"))1474	}14751476	switch p.tok {1477	case token.IDENT:1478		return p.parseIdent()14791480	case token.INT, token.FLOAT, token.IMAG, token.CHAR, token.STRING:1481		x := &ast.BasicLit{ValuePos: p.pos, ValueEnd: p.end(), Kind: p.tok, Value: p.lit}1482		p.next()1483		return x14841485	case token.LBRACE:1486		return p.parseLiteralValue(nil)14871488	case token.LPAREN:1489		lparen := p.pos1490		p.next()1491		p.exprLev++1492		x := p.parseRhs() // types may be parenthesized: (some type)1493		p.exprLev--1494		rparen := p.expect(token.RPAREN)1495		return &ast.ParenExpr{Lparen: lparen, X: x, Rparen: rparen}14961497	case token.FUNC:1498		return p.parseFuncTypeOrLit()1499	}15001501	if typ := p.tryIdentOrType(); typ != nil { // do not consume trailing type parameters1502		// could be type for composite literal or conversion1503		_, isIdent := typ.(*ast.Ident)1504		assert(!isIdent, "type cannot be identifier")1505		return typ1506	}15071508	// we have an error1509	pos := p.pos1510	p.errorExpected(pos, "operand")1511	p.advance(stmtStart)1512	return &ast.BadExpr{From: pos, To: p.pos}1513}15141515func (p *parser) parseSelector(x ast.Expr) ast.Expr {1516	if p.trace {1517		defer un(trace(p, "Selector"))1518	}15191520	sel := p.parseIdent()15211522	return &ast.SelectorExpr{X: x, Sel: sel}1523}15241525func (p *parser) parseTypeAssertion(x ast.Expr) ast.Expr {1526	if p.trace {1527		defer un(trace(p, "TypeAssertion"))1528	}15291530	lparen := p.expect(token.LPAREN)1531	var typ ast.Expr1532	if p.tok == token.TYPE {1533		// type switch: typ == nil1534		p.next()1535	} else {1536		typ = p.parseType()1537	}1538	rparen := p.expect(token.RPAREN)15391540	return &ast.TypeAssertExpr{X: x, Type: typ, Lparen: lparen, Rparen: rparen}1541}15421543func (p *parser) parseIndexOrSliceOrInstance(x ast.Expr) ast.Expr {1544	if p.trace {1545		defer un(trace(p, "parseIndexOrSliceOrInstance"))1546	}15471548	lbrack := p.expect(token.LBRACK)1549	if p.tok == token.RBRACK {1550		// empty index, slice or index expressions are not permitted;1551		// accept them for parsing tolerance, but complain1552		p.errorExpected(p.pos, "operand")1553		rbrack := p.pos1554		p.next()1555		return &ast.IndexExpr{1556			X:      x,1557			Lbrack: lbrack,1558			Index:  &ast.BadExpr{From: rbrack, To: rbrack},1559			Rbrack: rbrack,1560		}1561	}1562	p.exprLev++15631564	const N = 3 // change the 3 to 2 to disable 3-index slices1565	var args []ast.Expr1566	var index [N]ast.Expr1567	var colons [N - 1]token.Pos1568	if p.tok != token.COLON {1569		// We can't know if we have an index expression or a type instantiation;1570		// so even if we see a (named) type we are not going to be in type context.1571		index[0] = p.parseRhs()1572	}1573	ncolons := 01574	switch p.tok {1575	case token.COLON:1576		// slice expression1577		for p.tok == token.COLON && ncolons < len(colons) {1578			colons[ncolons] = p.pos1579			ncolons++1580			p.next()1581			if p.tok != token.COLON && p.tok != token.RBRACK && p.tok != token.EOF {1582				index[ncolons] = p.parseRhs()1583			}1584		}1585	case token.COMMA:1586		// instance expression1587		args = append(args, index[0])1588		for p.tok == token.COMMA {1589			p.next()1590			if p.tok != token.RBRACK && p.tok != token.EOF {1591				args = append(args, p.parseType())1592			}1593		}1594	}15951596	p.exprLev--1597	rbrack := p.expect(token.RBRACK)15981599	if ncolons > 0 {1600		// slice expression1601		slice3 := false1602		if ncolons == 2 {1603			slice3 = true1604			// Check presence of middle and final index here rather than during type-checking1605			// to prevent erroneous programs from passing through gofmt (was go.dev/issue/7305).1606			if index[1] == nil {1607				p.error(colons[0], "middle index required in 3-index slice")1608				index[1] = &ast.BadExpr{From: colons[0] + 1, To: colons[1]}1609			}1610			if index[2] == nil {1611				p.error(colons[1], "final index required in 3-index slice")1612				index[2] = &ast.BadExpr{From: colons[1] + 1, To: rbrack}1613			}1614		}1615		return &ast.SliceExpr{X: x, Lbrack: lbrack, Low: index[0], High: index[1], Max: index[2], Slice3: slice3, Rbrack: rbrack}1616	}16171618	if len(args) == 0 {1619		// index expression1620		return &ast.IndexExpr{X: x, Lbrack: lbrack, Index: index[0], Rbrack: rbrack}1621	}16221623	// instance expression1624	return packIndexExpr(x, lbrack, args, rbrack)1625}16261627func (p *parser) parseCallOrConversion(fun ast.Expr) *ast.CallExpr {1628	if p.trace {1629		defer un(trace(p, "CallOrConversion"))1630	}16311632	lparen := p.expect(token.LPAREN)1633	p.exprLev++1634	var list []ast.Expr1635	var ellipsis token.Pos1636	for p.tok != token.RPAREN && p.tok != token.EOF && !ellipsis.IsValid() {1637		list = append(list, p.parseRhs()) // builtins may expect a type: make(some type, ...)1638		if p.tok == token.ELLIPSIS {1639			ellipsis = p.pos1640			p.next()1641		}1642		if !p.atComma("argument list", token.RPAREN) {1643			break1644		}1645		p.next()1646	}1647	p.exprLev--1648	rparen := p.expectClosing(token.RPAREN, "argument list")16491650	return &ast.CallExpr{Fun: fun, Lparen: lparen, Args: list, Ellipsis: ellipsis, Rparen: rparen}1651}16521653func (p *parser) parseElement() ast.Expr {1654	if p.trace {1655		defer un(trace(p, "Element"))1656	}16571658	x := p.parseExpr()1659	if p.tok == token.COLON {1660		colon := p.pos1661		p.next()1662		x = &ast.KeyValueExpr{Key: x, Colon: colon, Value: p.parseExpr()}1663	}16641665	return x1666}16671668func (p *parser) parseElementList() (list []ast.Expr) {1669	if p.trace {1670		defer un(trace(p, "ElementList"))1671	}16721673	for p.tok != token.RBRACE && p.tok != token.EOF {1674		list = append(list, p.parseElement())1675		if !p.atComma("composite literal", token.RBRACE) {1676			break1677		}1678		p.next()1679	}16801681	return1682}16831684func (p *parser) parseLiteralValue(typ ast.Expr) ast.Expr {1685	defer decNestLev(incNestLev(p))16861687	if p.trace {1688		defer un(trace(p, "LiteralValue"))1689	}16901691	lbrace := p.expect(token.LBRACE)1692	var elts []ast.Expr1693	p.exprLev++1694	if p.tok != token.RBRACE {1695		elts = p.parseElementList()1696	}1697	p.exprLev--1698	rbrace := p.expectClosing(token.RBRACE, "composite literal")1699	return &ast.CompositeLit{Type: typ, Lbrace: lbrace, Elts: elts, Rbrace: rbrace}1700}17011702func (p *parser) parsePrimaryExpr(x ast.Expr) ast.Expr {1703	if p.trace {1704		defer un(trace(p, "PrimaryExpr"))1705	}17061707	if x == nil {1708		x = p.parseOperand()1709	}1710	// We track the nesting here rather than at the entry for the function,1711	// since it can iteratively produce a nested output, and we want to1712	// limit how deep a structure we generate.1713	var n int1714	defer func() { p.nestLev -= n }()1715	for n = 1; ; n++ {1716		incNestLev(p)1717		switch p.tok {1718		case token.PERIOD:1719			p.next()1720			switch p.tok {1721			case token.IDENT:1722				x = p.parseSelector(x)1723			case token.LPAREN:1724				x = p.parseTypeAssertion(x)1725			default:1726				pos := p.pos1727				p.errorExpected(pos, "selector or type assertion")1728				// TODO(rFindley) The check for token.RBRACE below is a targeted fix1729				//                to error recovery sufficient to make the x/tools tests to1730				//                pass with the new parsing logic introduced for type1731				//                parameters. Remove this once error recovery has been1732				//                more generally reconsidered.1733				if p.tok != token.RBRACE {1734					p.next() // make progress1735				}1736				sel := &ast.Ident{NamePos: pos, Name: "_"}1737				x = &ast.SelectorExpr{X: x, Sel: sel}1738			}1739		case token.LBRACK:1740			x = p.parseIndexOrSliceOrInstance(x)1741		case token.LPAREN:1742			x = p.parseCallOrConversion(x)1743		case token.LBRACE:1744			// operand may have returned a parenthesized complit1745			// type; accept it but complain if we have a complit1746			t := ast.Unparen(x)1747			// determine if '{' belongs to a composite literal or a block statement1748			switch t.(type) {1749			case *ast.BadExpr, *ast.Ident, *ast.SelectorExpr:1750				if p.exprLev < 0 {1751					return x1752				}1753				// x is possibly a composite literal type1754			case *ast.IndexExpr, *ast.IndexListExpr:1755				if p.exprLev < 0 {1756					return x1757				}1758				// x is possibly a composite literal type1759			case *ast.ArrayType, *ast.StructType, *ast.MapType:1760				// x is a composite literal type1761			default:1762				return x1763			}1764			if t != x {1765				p.error(t.Pos(), "cannot parenthesize type in composite literal")1766				// already progressed, no need to advance1767			}1768			x = p.parseLiteralValue(t)1769		default:1770			return x1771		}1772	}1773}17741775func (p *parser) parseUnaryExpr() ast.Expr {1776	defer decNestLev(incNestLev(p))17771778	if p.trace {1779		defer un(trace(p, "UnaryExpr"))1780	}17811782	switch p.tok {1783	case token.ADD, token.SUB, token.NOT, token.XOR, token.AND, token.TILDE:1784		pos, op := p.pos, p.tok1785		p.next()1786		x := p.parseUnaryExpr()1787		return &ast.UnaryExpr{OpPos: pos, Op: op, X: x}17881789	case token.ARROW:1790		// channel type or receive expression1791		arrow := p.pos1792		p.next()17931794		// If the next token is token.CHAN we still don't know if it1795		// is a channel type or a receive operation - we only know1796		// once we have found the end of the unary expression. There1797		// are two cases:1798		//1799		//   <- type  => (<-type) must be channel type1800		//   <- expr  => <-(expr) is a receive from an expression1801		//1802		// In the first case, the arrow must be re-associated with1803		// the channel type parsed already:1804		//1805		//   <- (chan type)    =>  (<-chan type)1806		//   <- (chan<- type)  =>  (<-chan (<-type))18071808		x := p.parseUnaryExpr()18091810		// determine which case we have1811		if typ, ok := x.(*ast.ChanType); ok {1812			// (<-type)18131814			// re-associate position info and <-1815			dir := ast.SEND1816			for ok && dir == ast.SEND {1817				if typ.Dir == ast.RECV {1818					// error: (<-type) is (<-(<-chan T))1819					p.errorExpected(typ.Arrow, "'chan'")1820				}1821				arrow, typ.Begin, typ.Arrow = typ.Arrow, arrow, arrow1822				dir, typ.Dir = typ.Dir, ast.RECV1823				typ, ok = typ.Value.(*ast.ChanType)1824			}1825			if dir == ast.SEND {1826				p.errorExpected(arrow, "channel type")1827			}18281829			return x1830		}18311832		// <-(expr)1833		return &ast.UnaryExpr{OpPos: arrow, Op: token.ARROW, X: x}18341835	case token.MUL:1836		// pointer type or unary "*" expression1837		pos := p.pos1838		p.next()1839		x := p.parseUnaryExpr()1840		return &ast.StarExpr{Star: pos, X: x}1841	}18421843	return p.parsePrimaryExpr(nil)1844}18451846func (p *parser) tokPrec() (token.Token, int) {1847	tok := p.tok1848	if p.inRhs && tok == token.ASSIGN {1849		tok = token.EQL1850	}1851	return tok, tok.Precedence()1852}18531854// parseBinaryExpr parses a (possibly) binary expression.1855// If x is non-nil, it is used as the left operand.1856//1857// TODO(rfindley): parseBinaryExpr has become overloaded. Consider refactoring.1858func (p *parser) parseBinaryExpr(x ast.Expr, prec1 int) ast.Expr {1859	if p.trace {1860		defer un(trace(p, "BinaryExpr"))1861	}18621863	if x == nil {1864		x = p.parseUnaryExpr()1865	}1866	// We track the nesting here rather than at the entry for the function,1867	// since it can iteratively produce a nested output, and we want to1868	// limit how deep a structure we generate.1869	var n int1870	defer func() { p.nestLev -= n }()1871	for n = 1; ; n++ {1872		incNestLev(p)1873		op, oprec := p.tokPrec()1874		if oprec < prec1 {1875			return x1876		}1877		pos := p.expect(op)1878		y := p.parseBinaryExpr(nil, oprec+1)1879		x = &ast.BinaryExpr{X: x, OpPos: pos, Op: op, Y: y}1880	}1881}18821883// The result may be a type or even a raw type ([...]int).1884func (p *parser) parseExpr() ast.Expr {1885	if p.trace {1886		defer un(trace(p, "Expression"))1887	}18881889	return p.parseBinaryExpr(nil, token.LowestPrec+1)1890}18911892func (p *parser) parseRhs() ast.Expr {1893	old := p.inRhs1894	p.inRhs = true1895	x := p.parseExpr()1896	p.inRhs = old1897	return x1898}18991900// ----------------------------------------------------------------------------1901// Statements19021903// Parsing modes for parseSimpleStmt.1904const (1905	basic = iota1906	labelOk1907	rangeOk1908)19091910// parseSimpleStmt returns true as 2nd result if it parsed the assignment1911// of a range clause (with mode == rangeOk). The returned statement is an1912// assignment with a right-hand side that is a single unary expression of1913// the form "range x". No guarantees are given for the left-hand side.1914func (p *parser) parseSimpleStmt(mode int) (ast.Stmt, bool) {1915	if p.trace {1916		defer un(trace(p, "SimpleStmt"))1917	}19181919	x := p.parseList(false)19201921	switch p.tok {1922	case1923		token.DEFINE, token.ASSIGN, token.ADD_ASSIGN,1924		token.SUB_ASSIGN, token.MUL_ASSIGN, token.QUO_ASSIGN,1925		token.REM_ASSIGN, token.AND_ASSIGN, token.OR_ASSIGN,1926		token.XOR_ASSIGN, token.SHL_ASSIGN, token.SHR_ASSIGN, token.AND_NOT_ASSIGN:1927		// assignment statement, possibly part of a range clause1928		pos, tok := p.pos, p.tok1929		p.next()1930		var y []ast.Expr1931		isRange := false1932		if mode == rangeOk && p.tok == token.RANGE && (tok == token.DEFINE || tok == token.ASSIGN) {1933			pos := p.pos1934			p.next()1935			y = []ast.Expr{&ast.UnaryExpr{OpPos: pos, Op: token.RANGE, X: p.parseRhs()}}1936			isRange = true1937		} else {1938			y = p.parseList(true)1939		}1940		return &ast.AssignStmt{Lhs: x, TokPos: pos, Tok: tok, Rhs: y}, isRange1941	}19421943	if len(x) > 1 {1944		p.errorExpected(x[0].Pos(), "1 expression")1945		// continue with first expression1946	}19471948	switch p.tok {1949	case token.COLON:1950		// labeled statement1951		colon := p.pos1952		p.next()1953		if label, isIdent := x[0].(*ast.Ident); mode == labelOk && isIdent {1954			// Go spec: The scope of a label is the body of the function1955			// in which it is declared and excludes the body of any nested1956			// function.1957			stmt := &ast.LabeledStmt{Label: label, Colon: colon, Stmt: p.parseStmt()}1958			return stmt, false1959		}1960		// The label declaration typically starts at x[0].Pos(), but the label1961		// declaration may be erroneous due to a token after that position (and1962		// before the ':'). If SpuriousErrors is not set, the (only) error1963		// reported for the line is the illegal label error instead of the token1964		// before the ':' that caused the problem. Thus, use the (latest) colon1965		// position for error reporting.1966		p.error(colon, "illegal label declaration")1967		return &ast.BadStmt{From: x[0].Pos(), To: colon + 1}, false19681969	case token.ARROW:1970		// send statement1971		arrow := p.pos1972		p.next()1973		y := p.parseRhs()1974		return &ast.SendStmt{Chan: x[0], Arrow: arrow, Value: y}, false19751976	case token.INC, token.DEC:1977		// increment or decrement1978		s := &ast.IncDecStmt{X: x[0], TokPos: p.pos, Tok: p.tok}1979		p.next()1980		return s, false1981	}19821983	// expression1984	return &ast.ExprStmt{X: x[0]}, false1985}19861987func (p *parser) parseCallExpr(callType string) *ast.CallExpr {1988	x := p.parseRhs() // could be a conversion: (some type)(x)1989	if t := ast.Unparen(x); t != x {1990		p.error(x.Pos(), fmt.Sprintf("expression in %s must not be parenthesized", callType))1991		x = t1992	}1993	if call, isCall := x.(*ast.CallExpr); isCall {1994		return call1995	}1996	if _, isBad := x.(*ast.BadExpr); !isBad {1997		// only report error if it's a new one1998		p.error(x.End(), fmt.Sprintf("expression in %s must be function call", callType))1999	}2000	return nil

Code quality findings 70

Declared map variable without initialization; writing to a nil map causes a panic. Use make() to initialize
warning correctness nil-map-write
var stmtStart = map[token.Token]bool{
Declared map variable without initialization; writing to a nil map causes a panic. Use make() to initialize
warning correctness nil-map-write
var declStart = map[token.Token]bool{
Declared map variable without initialization; writing to a nil map causes a panic. Use make() to initialize
warning correctness nil-map-write
var exprEnd = map[token.Token]bool{
Defer inside loop; deferred calls accumulate until the function returns, not until the loop iteration ends. This can cause resource leaks
warning correctness defer-in-loop
defer un(trace(p, "IdentList"))
Defer inside loop; deferred calls accumulate until the function returns, not until the loop iteration ends. This can cause resource leaks
warning correctness defer-in-loop
defer un(trace(p, "ExpressionList"))
Defer inside loop; deferred calls accumulate until the function returns, not until the loop iteration ends. This can cause resource leaks
warning correctness defer-in-loop
defer un(trace(p, "ArrayFieldOrTypeInstance"))
Defer inside loop; deferred calls accumulate until the function returns, not until the loop iteration ends. This can cause resource leaks
warning correctness defer-in-loop
defer un(trace(p, "StructType"))
Blank identifier discarding results; verify intentional ignoring of return values
warning correctness blank-identifier-discard
_ = p.parseParameterList(name0, nil, token.RBRACK, false)
Blank identifier discarding results; verify intentional ignoring of return values
warning correctness blank-identifier-discard
_ = p.expect(token.RBRACK)
Defer inside loop; deferred calls accumulate until the function returns, not until the loop iteration ends. This can cause resource leaks
warning correctness defer-in-loop
defer un(trace(p, "EmbeddedElem"))
Defer inside loop; deferred calls accumulate until the function returns, not until the loop iteration ends. This can cause resource leaks
warning correctness defer-in-loop
defer un(trace(p, "InterfaceType"))
Defer inside loop; deferred calls accumulate until the function returns, not until the loop iteration ends. This can cause resource leaks
warning correctness defer-in-loop
defer un(trace(p, "TypeInstance"))
Defer inside loop; deferred calls accumulate until the function returns, not until the loop iteration ends. This can cause resource leaks
warning correctness defer-in-loop
defer un(trace(p, "StatementList"))
Defer inside loop; deferred calls accumulate until the function returns, not until the loop iteration ends. This can cause resource leaks
warning correctness defer-in-loop
defer un(trace(p, "Body"))
Defer inside loop; deferred calls accumulate until the function returns, not until the loop iteration ends. This can cause resource leaks
warning correctness defer-in-loop
defer un(trace(p, "CallOrConversion"))
Defer inside loop; deferred calls accumulate until the function returns, not until the loop iteration ends. This can cause resource leaks
warning correctness defer-in-loop
defer un(trace(p, "ElementList"))
Defer inside loop; deferred calls accumulate until the function returns, not until the loop iteration ends. This can cause resource leaks
warning correctness defer-in-loop
defer func() { p.nestLev -= n }()
Defer inside loop; deferred calls accumulate until the function returns, not until the loop iteration ends. This can cause resource leaks
warning correctness defer-in-loop
defer func() { p.nestLev -= n }()
Blank identifier discarding results; verify intentional ignoring of return values
warning correctness blank-identifier-discard
init, _ = p.parseSimpleStmt(basic)
Blank identifier discarding results; verify intentional ignoring of return values
warning correctness blank-identifier-discard
condStmt, _ = p.parseSimpleStmt(basic)
Blank identifier discarding results; verify intentional ignoring of return values
warning correctness blank-identifier-discard
else_ = p.parseIfStmt()
Blank identifier discarding results; verify intentional ignoring of return values
warning correctness blank-identifier-discard
else_ = p.parseBlockStmt()
Blank identifier discarding results; verify intentional ignoring of return values
warning correctness blank-identifier-discard
else_ = &ast.BadStmt{From: p.pos, To: p.pos}
Blank identifier discarding results; verify intentional ignoring of return values
warning correctness blank-identifier-discard
s2, _ = p.parseSimpleStmt(basic)
Blank identifier discarding results; verify intentional ignoring of return values
warning correctness blank-identifier-discard
s2, _ = p.parseSimpleStmt(basic)
Defer inside loop; deferred calls accumulate until the function returns, not until the loop iteration ends. This can cause resource leaks
warning correctness defer-in-loop
defer un(trace(p, "SelectStmt"))
Blank identifier discarding results; verify intentional ignoring of return values
warning correctness blank-identifier-discard
s2, _ = p.parseSimpleStmt(basic)
Blank identifier discarding results; verify intentional ignoring of return values
warning correctness blank-identifier-discard
s3, _ = p.parseSimpleStmt(basic)
Blank identifier discarding results; verify intentional ignoring of return values
warning correctness blank-identifier-discard
s, _ = p.parseSimpleStmt(labelOk)
Defer inside loop; deferred calls accumulate until the function returns, not until the loop iteration ends. This can cause resource leaks
warning correctness defer-in-loop
defer un(trace(p, "GenDecl("+keyword.String()+")"))
Formatted output to console; prefer structured logging for consistency
info correctness fmt-printf
fmt.Printf("%5d:%3d: ", pos.Line, pos.Column)
Unstructured output; use a structured logging library (e.g., slog, zap, zerolog, logrus)
info correctness fmt-println
fmt.Println(a...)
Infinite loop detected; ensure it has a proper exit condition (e.g., break, return) to avoid unintentional resource consumption or hangs
info correctness infinite-loop
for {
Multiple appends without pre-allocation; use make() with capacity when size is known
info performance append-without-prealloc
list = append(list, comment)
Multiple appends without pre-allocation; use make() with capacity when size is known
info performance append-without-prealloc
p.comments = append(p.comments, comments)
Multiple appends without pre-allocation; use make() with capacity when size is known
info performance append-without-prealloc
list = append(list, p.parseIdent())
Multiple appends without pre-allocation; use make() with capacity when size is known
info performance append-without-prealloc
list = append(list, p.parseIdent())
Multiple appends without pre-allocation; use make() with capacity when size is known
info performance append-without-prealloc
list = append(list, p.parseExpr())
Multiple appends without pre-allocation; use make() with capacity when size is known
info performance append-without-prealloc
list = append(list, p.parseExpr())
Multiple appends without pre-allocation; use make() with capacity when size is known
info performance append-without-prealloc
args = append(args, p.parseRhs())
Multiple appends without pre-allocation; use make() with capacity when size is known
info performance append-without-prealloc
args = append(args, p.parseRhs())
Multiple appends without pre-allocation; use make() with capacity when size is known
info performance append-without-prealloc
names = append(names, p.parseIdent())
Multiple appends without pre-allocation; use make() with capacity when size is known
info performance append-without-prealloc
list = append(list, p.parseFieldDecl())
Multiple appends without pre-allocation; use make() with capacity when size is known
info performance append-without-prealloc
params = append(params, &ast.Field{Type: par.typ})
Multiple appends without pre-allocation; use make() with capacity when size is known
info performance append-without-prealloc
params = append(params, field)
Multiple appends without pre-allocation; use make() with capacity when size is known
info performance append-without-prealloc
names = append(names, par.name)
Multiple appends without pre-allocation; use make() with capacity when size is known
info performance append-without-prealloc
list = append(list, p.parseType())
Infinite loop detected; ensure it has a proper exit condition (e.g., break, return) to avoid unintentional resource consumption or hangs
info correctness infinite-loop
for {
Multiple appends without pre-allocation; use make() with capacity when size is known
info performance append-without-prealloc
list = append(list, f)
Multiple appends without pre-allocation; use make() with capacity when size is known
info performance append-without-prealloc
list = append(list, p.parseType())
Multiple appends without pre-allocation; use make() with capacity when size is known
info performance append-without-prealloc
list = append(list, p.parseStmt())
Multiple appends without pre-allocation; use make() with capacity when size is known
info performance append-without-prealloc
args = append(args, index[0])
Multiple appends without pre-allocation; use make() with capacity when size is known
info performance append-without-prealloc
args = append(args, p.parseType())
Multiple appends without pre-allocation; use make() with capacity when size is known
info performance append-without-prealloc
list = append(list, p.parseRhs()) // builtins may expect a type: make(some type, ...)
Multiple appends without pre-allocation; use make() with capacity when size is known
info performance append-without-prealloc
list = append(list, p.parseElement())
Type switch without default case; unhandled types will silently do nothing. Add a default case for safety
info correctness unchecked-type-switch
switch t.(type) {
Type switch without default case; unhandled types will silently do nothing. Add a default case for safety
info correctness unchecked-type-switch
switch t := s.(type) {
Multiple appends without pre-allocation; use make() with capacity when size is known
info performance append-without-prealloc
list = append(list, p.parseCaseClause())
Multiple appends without pre-allocation; use make() with capacity when size is known
info performance append-without-prealloc
list = append(list, p.parseCommClause())
Deeply nested control structures reduce readability; consider extracting to functions or using early returns
info maintainability deep-nesting
if p.tok != token.LBRACE {
Deeply nested control structures reduce readability; consider extracting to functions or using early returns
info maintainability deep-nesting
// "for range x" (nil lhs in assignment)
Type switch without default case; unhandled types will silently do nothing. Add a default case for safety
info correctness unchecked-type-switch
switch x := x.(type) {
Deeply nested control structures reduce readability; consider extracting to functions or using early returns
info maintainability deep-nesting
switch x := x.(type) {
Deeply nested control structures reduce readability; consider extracting to functions or using early returns
info maintainability deep-nesting
switch x.Op {
Deeply nested control structures reduce readability; consider extracting to functions or using early returns
info maintainability deep-nesting
if name, _ := x.X.(*ast.Ident); name != nil && (force || isTypeElem(x.Y)) {
Type switch without default case; unhandled types will silently do nothing. Add a default case for safety
info correctness unchecked-type-switch
switch x := x.(type) {
Multiple appends without pre-allocation; use make() with capacity when size is known
info performance append-without-prealloc
list = append(list, f(p.leadComment, keyword, iota))
Multiple appends without pre-allocation; use make() with capacity when size is known
info performance append-without-prealloc
list = append(list, f(nil, keyword, 0))
Multiple appends without pre-allocation; use make() with capacity when size is known
info performance append-without-prealloc
decls = append(decls, p.parseGenDecl(token.IMPORT, p.parseImportSpec))
Multiple appends without pre-allocation; use make() with capacity when size is known
info performance append-without-prealloc
decls = append(decls, p.parseDecl(declStart))

Get this view in your editor

Same data, no extra tab — call code_get_file + code_get_findings over MCP from Claude/Cursor/Copilot.