Debian Codegraph @

go/analysis/passes/modernize/embedlit.go

raw symbols SCIP
1 // Copyright 2026 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 modernize
6
7 import (
8 "bytes"
9 "fmt"
10 "go/ast"
11 "go/token"
12 "go/types"
13 "slices"
14 "strings"
15
16 "golang.org/x/tools/go/analysis"
17 "golang.org/x/tools/go/analysis/passes/inspect"
18 "golang.org/x/tools/go/ast/edge"
19 "golang.org/x/tools/go/ast/inspector"
20 "golang.org/x/tools/internal/analysis/analyzerutil"
21 typeindexanalyzer "golang.org/x/tools/internal/analysis/typeindex"
22 "golang.org/x/tools/internal/astutil"
23 "golang.org/x/tools/internal/moreiters"
24 "golang.org/x/tools/internal/typesinternal/typeindex"
25 "golang.org/x/tools/internal/versions"
26 )
27
28 var EmbedLitAnalyzer = &analysis.Analyzer{
29 Name: "embedlit",
30 Doc: analyzerutil.MustExtractDoc(doc, "embedlit"),
31 Requires: []*analysis.Analyzer{
32 inspect.Analyzer,
33 typeindexanalyzer.Analyzer,
34 },
35 Run: runEmbedLit,
36 URL: "https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/modernize#embedlit",
37 }
38
39 // Go1.27 introduced the ability to directly access embedded struct fields.
40 // The embedlit modernizer suggests two types of fixes that use this feature:
41 // 1. Removing redundant field type specifiers in embedded struct fields.
42 // 2. Moving embedded struct field assignments inside of the struct literal
43 // initialization.
44 func runEmbedLit(pass *analysis.Pass) (any, error) {
45 var (
46 inspect = pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
47 index = pass.ResultOf[typeindexanalyzer.Analyzer].(*typeindex.Index)
48 info = pass.TypesInfo
49 )
50 for curLit := range inspect.Root().Preorder((*ast.CompositeLit)(nil)) {
51 if curLit.ParentEdgeKind() != edge.KeyValueExpr_Value { // non-nested comp lit
52 // TODO(mkalil): Figure out how to handle addition/removal of commas in
53 // the comp lit when we observe code where both patterns apply. (This will
54 // likely require a significant amount of work). For now, only apply edits
55 // from one pattern at a time.
56 if !embedlitUnnest(pass, info, curLit) {
57 err := embedlitCombine(pass, index, info, curLit) // calls pass.ReadFile
58 if err != nil {
59 return nil, err
60 }
61 }
62 }
63 }
64 return nil, nil
65 }
66
67 // Pattern A: removing unneeded embedded field type specifier from the struct
68 // literal.
69 // T{U: U{f: v, ...}} => T{f: v, ...}
70 // It returns true if it reported a diagnostic with edits.
71 func embedlitUnnest(pass *analysis.Pass, info *types.Info, curLit inspector.Cursor) bool {
72 var (
73 edits []analysis.TextEdit
74 names []string // names of the embedded field types that can be removed
75 lit = curLit.Node().(*ast.CompositeLit)
76 compLitType = info.TypeOf(lit)
77 )
78
79 // checkLit determines whether any of the fields in the given struct literal can
80 // be promoted, and calculates the corresponding edits.
81 var checkLit func(lit *ast.CompositeLit)
82 checkLit = func(lit *ast.CompositeLit) {
83 for i, elt := range lit.Elts {
84 // Can't promote an unkeyed field; would result in a syntax error.
85 if kv, ok := elt.(*ast.KeyValueExpr); ok {
86 if innerLit := isEmbeddedFieldLit(info, compLitType, kv); innerLit != nil {
87 // Emit edits to delete the unnecessary embedded field type specifier
88 // and its closing brace.
89 closingPos := innerLit.Rbrace
90 if len(innerLit.Elts) > 0 {
91 // Delete any inner trailing commas or white space. Extra trailing commas
92 // would result in invalid code.
93 closingPos = innerLit.Elts[len(innerLit.Elts)-1].End()
94 }
95 file := astutil.EnclosingFile(curLit)
96 // Enable modernizer only for Go1.27.
97 if !analyzerutil.FileUsesGoVersion(pass, file, versions.Go1_27) {
98 return
99 }
100 // If any comments overlap with the range to delete, don't suggest a fix.
101 if !moreiters.Empty(astutil.Comments(file, kv.Pos(), innerLit.Lbrace+1)) ||
102 !moreiters.Empty(astutil.Comments(file, closingPos, innerLit.Rbrace+1)) {
103 continue
104 }
105 // Delete starting from the key to the character right after the
106 // opening brace of the inner literal:
107 // T{U: U{f: v, ...}}
108 // -----
109 startPos := kv.Pos()
110 endPos := innerLit.Lbrace + 1
111
112 // Delete the entire line if the key and its opening brace are
113 // together on their own line. This prevents leaving behind unneeded
114 // blank lines inside struct literals that `gofmt` will not remove.
115 // T{
116 // U: U{ <- delete entire line
117 // f: v,
118 // }
119 // }
120 //
121 tokFile := pass.Fset.File(kv.Pos())
122 lineOf := func(pos token.Pos) int {
123 return tokFile.PositionFor(pos, false).Line
124 }
125 curLine := lineOf(kv.Pos())
126 var prevLine int
127 if i == 0 {
128 // First element, so the previous line is the parent lbrace.
129 prevLine = lineOf(lit.Lbrace)
130 } else {
131 prevLine = lineOf(lit.Elts[i-1].End())
132 }
133
134 // We can safely delete the entire line if the key value expression is
135 // on a different line than the previous element, and the closing
136 // brace of the inner literal is on a different line than its opening
137 // brace.
138 if prevLine < curLine && curLine < tokFile.LineCount() && // (1-based)
139 lineOf(innerLit.Lbrace) < lineOf(innerLit.Rbrace) {
140 lineStart := tokFile.LineStart(curLine)
141 nextLineStart := tokFile.LineStart(curLine + 1)
142 // Check that there are no comments on the line we are going to delete.
143 if moreiters.Empty(astutil.Comments(file, lineStart, nextLineStart)) {
144 startPos = tokFile.LineStart(curLine)
145 endPos = nextLineStart
146 }
147 }
148
149 edits = append(edits, []analysis.TextEdit{
150 // T{U: U{f: v, ...}}
151 // ----- -
152 {
153 // Delete the key and the opening brace of the inner struct literal.
154 Pos: startPos,
155 End: endPos,
156 },
157 {
158 // Delete the corresponding closing brace, including preceding
159 // white space or commas. Failing to delete trailing commas may
160 // result in invalid code.
161 Pos: closingPos,
162 End: innerLit.Rbrace + 1,
163 },
164 }...)
165 names = append(names, kv.Key.(*ast.Ident).Name)
166 checkLit(innerLit)
167 }
168 }
169 }
170 }
171 checkLit(lit)
172 if len(edits) > 0 {
173 pass.Report(analysis.Diagnostic{
174 Pos: curLit.Node().Pos(),
175 End: curLit.Node().End(),
176 Message: "embedded field type can be removed from struct literal",
177 SuggestedFixes: []analysis.SuggestedFix{
178 {
179 Message: fmt.Sprintf("Remove embedded field type%s %s", cond(len(names) == 1, "", "s"), strings.Join(names, ", ")),
180 TextEdits: edits,
181 },
182 },
183 })
184 return true
185 }
186 return false
187 }
188
189 // Pattern B: moving embedded field assignments inside the struct literal
190 // initialization.
191 // t := T{...}; t.x = x => t := T{..., x: x}
192 // (or var t = ...)
193 func embedlitCombine(pass *analysis.Pass, index *typeindex.Index, info *types.Info, curLit inspector.Cursor) error {
194 compLit := curLit.Node().(*ast.CompositeLit)
195 if !moreiters.Every(slices.Values(compLit.Elts), func(e ast.Expr) bool {
196 return is[*ast.KeyValueExpr](e)
197 }) {
198 // Promoting additional embedded fields would result in mixing keyed and
199 // unkeyed fields, which isn't allowed.
200 return nil
201 }
202 var (
203 // Ident for "t" in the assignment.
204 lhs *ast.Ident
205 // The cursor representing the statement that initializes the comp lit "t".
206 // We use its siblings to search for field assignments and verify that there
207 // are no intervening statements, in case those statements observe "t".
208 curStmt inspector.Cursor
209 )
210 switch curLit.ParentEdgeKind() {
211 case edge.AssignStmt_Rhs:
212 assign := curLit.Parent().Node().(*ast.AssignStmt)
213 // TODO(mkalil): Handle lhs forms that aren't idents, i.e. x.y[i] = T{...}.
214 if id, ok := assign.Lhs[curLit.ParentEdgeIndex()].(*ast.Ident); ok {
215 lhs = id
216 curStmt = curLit.Parent()
217 }
218 case edge.ValueSpec_Values:
219 spec := curLit.Parent().Node().(*ast.ValueSpec)
220 lhs = spec.Names[curLit.ParentEdgeIndex()]
221 if decl, ok := moreiters.First(curLit.Enclosing((*ast.DeclStmt)(nil))); ok {
222 curStmt = decl
223 }
224 default:
225 return nil
226 }
227
228 if lhs == nil || !curStmt.Valid() {
229 return nil
230 }
231
232 var (
233 tObj = info.ObjectOf(lhs)
234 // Marks the contiguous block of embedded field assign statements that will
235 // be moved into the struct initialization.
236 firstStmt, lastStmt inspector.Cursor
237 )
238 stmtloop:
239 for {
240 var ok bool
241 curStmt, ok = curStmt.NextSibling()
242 if !ok {
243 break // end of (e.g.) block
244 }
245 // All embedded field value assignments must immediately follow the struct
246 // initialization.
247 assign, ok := curStmt.Node().(*ast.AssignStmt)
248 if !ok || len(assign.Lhs) != 1 || !(assign.Tok == token.ASSIGN || assign.Tok == token.DEFINE) {
249 // TODO(mkalil): handle multi-assignments like t.x, t.y = 1, 2
250 break
251 }
252 expr := assign.Lhs[0]
253 sel, ok := expr.(*ast.SelectorExpr)
254 if !ok {
255 break
256 }
257 // Verify that sel.X refers to the same object as "t"
258 selXId, ok := sel.X.(*ast.Ident)
259 if !ok {
260 // TODO(mkalil): handle deeply nested expressions like t.B.x
261 break
262 }
263 obj := info.ObjectOf(selXId)
264 if obj != tObj {
265 break
266 }
267 rhsCur := curStmt.ChildAt(edge.AssignStmt_Rhs, 0)
268 if uses(index, rhsCur, tObj) {
269 break
270 }
271 for c := range rhsCur.Preorder((*ast.Ident)(nil)) {
272 id := c.Node().(*ast.Ident)
273 // If the rhs uses a value of t (e.g. t.x = t.y), don't suggest a fix because
274 // we can't evaluate t.y when constructing the new literal.
275 if info.ObjectOf(id) == tObj {
276 break stmtloop
277 }
278 // Note: we don't need to worry about expressions with side effects
279 // changing the behavior when moved inside the comp lit. The order of
280 // effects will be preserved because we preserve the order of the key
281 // value pairs inside the comp lit.
282 }
283 if !firstStmt.Valid() {
284 firstStmt = curStmt
285 }
286 lastStmt = curStmt
287 }
288
289 if !firstStmt.Valid() {
290 return nil
291 }
292
293 file := astutil.EnclosingFile(curLit)
294 // Enable modernizer only for Go1.27.
295 if !analyzerutil.FileUsesGoVersion(pass, file, versions.Go1_27) {
296 return nil
297 }
298
299 // Read file content to determine if the struct lit has a trailing comma
300 // after its last element.
301 tokFile := pass.Fset.File(compLit.Rbrace)
302 filename := tokFile.Name()
303 src, err := pass.ReadFile(filename)
304 if err != nil {
305 return err
306 }
307
308 hasTrailingComma := false
309 if len(compLit.Elts) > 0 {
310 lastElt := compLit.Elts[len(compLit.Elts)-1]
311 lastEltOffset := tokFile.Offset(lastElt.End())
312 rbraceOffset := tokFile.Offset(compLit.Rbrace)
313 hasTrailingComma = bytes.Contains(src[lastEltOffset:rbraceOffset], []byte(","))
314 }
315 var edits []analysis.TextEdit
316 // Emit edits to move the field assignment into the struct lit while
317 // removing it from its current place.
318 // t := T{...}; t.x = v
319 // ----- --- -
320 // t := T{..., x: v}
321
322 // Add a trailing comma before the closing brace of compLit if one doesn't
323 // exist, and delete the closing brace itself.
324 // t := T{...}; t.x = v
325 // -
326 // t := T{..., t.x = v
327 if len(compLit.Elts) > 0 && !hasTrailingComma {
328 edits = append(edits, analysis.TextEdit{
329 Pos: compLit.Rbrace,
330 End: compLit.Rbrace + 1,
331 NewText: []byte(","),
332 })
333 } else {
334 edits = append(edits, analysis.TextEdit{
335 Pos: compLit.Rbrace,
336 End: compLit.Rbrace + 1,
337 })
338 }
339
340 // For each assignment:
341 // t.x = v
342 // -- ---
343 // x : v
344 curStmt = firstStmt
345 var prevStmt inspector.Cursor
346 for {
347 assign := curStmt.Node().(*ast.AssignStmt)
348 expr := assign.Lhs[0]
349 sel := expr.(*ast.SelectorExpr)
350 // Delete "t."
351 edits = append(edits, analysis.TextEdit{
352 Pos: assign.Pos(),
353 End: sel.Sel.Pos(),
354 })
355 // Replace "=" with ":"
356 edits = append(edits, analysis.TextEdit{
357 Pos: expr.End(),
358 End: assign.TokPos + 1,
359 NewText: []byte(":"),
360 })
361
362 // Add a comma after the previous assignment if this is not the first one.
363 if prevStmt.Valid() {
364 edits = append(edits, analysis.TextEdit{
365 Pos: prevStmt.Node().End(),
366 NewText: []byte(","),
367 })
368 }
369
370 // For the last assignment, add the closing brace of the struct lit.
371 if curStmt == lastStmt {
372 edits = append(edits, analysis.TextEdit{
373 Pos: assign.End(),
374 NewText: []byte("}"),
375 })
376 break
377 }
378 prevStmt = curStmt
379 curStmt, _ = curStmt.NextSibling() // can't fail because we break out of the loop when we hit lastStmt
380 }
381
382 pass.Report(analysis.Diagnostic{
383 Pos: curLit.Node().Pos(),
384 End: curLit.Node().End(),
385 Message: "embedded field assignment can be moved to struct literal",
386 SuggestedFixes: []analysis.SuggestedFix{
387 {
388 Message: "Move embedded field assignment to struct literal",
389 TextEdits: edits,
390 },
391 },
392 })
393 return nil
394 }
395
396 // isEmbeddedFieldLit determines whether elt is a KeyValueExpr "T: T{...}" for
397 // an embedded field for which we can safely remove its type.
398 // If so, it returns the corresponding CompositeLit.
399 // If elt contains an unkeyed field or ambiguous type, it returns nil.
400 func isEmbeddedFieldLit(info *types.Info, topLevelType types.Type, kv *ast.KeyValueExpr) *ast.CompositeLit {
401 obj := keyedField(info, kv)
402 if obj == nil || !obj.Embedded() {
403 return nil
404 }
405 lit, ok := kv.Value.(*ast.CompositeLit)
406 if !ok || len(lit.Elts) == 0 {
407 // Skip if the struct literal is empty.
408 return nil
409 }
410 // We cannot remove this type if any of its nested composite elements have
411 // unkeyed fields or are ambiguous, so we check for those conditions before
412 // returning.
413 for _, elt := range lit.Elts {
414 kv, ok := elt.(*ast.KeyValueExpr)
415 if !ok {
416 return nil
417 }
418 obj := keyedField(info, kv)
419 if obj == nil {
420 return nil
421 }
422 k := kv.Key.(*ast.Ident) // can't fail
423 // Cannot promote an ambiguous type, for example:
424 // type T struct { A; B }
425 // type A struct { x int }
426 // type B struct { x int }
427 // _ = T{A: A{x: 1}}
428 // cannot be simplified to T{x: 1} because T has two different embedded fields called "x".
429 // We also reject composite literals with slice elements, as parentObj will be nil.
430 parentObj, _, _ := types.LookupFieldOrMethod(topLevelType, true, obj.Pkg(), k.Name)
431 if parentObj != obj {
432 return nil
433 }
434 }
435 return lit
436 }
437
438 // keyedField reports whether the key of kv is an embedded field type. If so, it
439 // returns the type of the embedded field, otherwise it returns nil.
440 func keyedField(info *types.Info, kv *ast.KeyValueExpr) *types.Var {
441 k, ok := kv.Key.(*ast.Ident)
442 if !ok {
443 return nil
444 }
445 obj, ok := info.ObjectOf(k).(*types.Var)
446 if !ok || !obj.IsField() {
447 return nil
448 }
449 return obj
450 }