| 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 | "fmt" |
| 9 | "go/ast" |
| 10 | "go/types" |
| 11 | "strings" |
| 12 | |
| 13 | "golang.org/x/tools/go/analysis" |
| 14 | "golang.org/x/tools/go/analysis/passes/inspect" |
| 15 | "golang.org/x/tools/go/ast/edge" |
| 16 | "golang.org/x/tools/go/ast/inspector" |
| 17 | "golang.org/x/tools/internal/analysis/analyzerutil" |
| 18 | "golang.org/x/tools/internal/astutil" |
| 19 | "golang.org/x/tools/internal/moreiters" |
| 20 | "golang.org/x/tools/internal/versions" |
| 21 | ) |
| 22 | |
| 23 | var EmbedLitAnalyzer = &analysis.Analyzer{ |
| 24 | Name: "embedlit", |
| 25 | Doc: analyzerutil.MustExtractDoc(doc, "embedlit"), |
| 26 | Requires: []*analysis.Analyzer{ |
| 27 | inspect.Analyzer, |
| 28 | }, |
| 29 | Run: runEmbedLit, |
| 30 | URL: "https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/modernize#embedlit", |
| 31 | } |
| 32 | |
| 33 | // TODO(mkalil): Handle other patterns such as: |
| 34 | // t := T{...} |
| 35 | // t.x = x |
| 36 | // ... |
| 37 | // => |
| 38 | // t := T{..., x: x, ...} |
| 39 | func runEmbedLit(pass *analysis.Pass) (any, error) { |
| 40 | var ( |
| 41 | inspect = pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) |
| 42 | info = pass.TypesInfo |
| 43 | ) |
| 44 | for curLit := range inspect.Root().Preorder((*ast.CompositeLit)(nil)) { |
| 45 | var ( |
| 46 | edits []analysis.TextEdit |
| 47 | names []string // names of the embedded field types that can be removed |
| 48 | compLit = curLit.Node().(*ast.CompositeLit) |
| 49 | compLitType = info.TypeOf(compLit) |
| 50 | check func(*ast.CompositeLit) |
| 51 | ) |
| 52 | check = func(lit *ast.CompositeLit) { |
| 53 | for _, elt := range lit.Elts { |
| 54 | // Can't promote an unkeyed field; would result in a syntax error. |
| 55 | if kv, ok := elt.(*ast.KeyValueExpr); ok { |
| 56 | if innerLit := isEmbeddedFieldLit(info, compLitType, kv); innerLit != nil { |
| 57 | // Emit edits to delete the unnecessary embedded field type specifier |
| 58 | // and its closing brace. |
| 59 | closingPos := innerLit.Rbrace |
| 60 | if len(innerLit.Elts) > 0 { |
| 61 | // Delete any inner trailing commas or white space. Extra trailing commas |
| 62 | // would result in invalid code. |
| 63 | closingPos = innerLit.Elts[len(innerLit.Elts)-1].End() |
| 64 | } |
| 65 | file := astutil.EnclosingFile(curLit) |
| 66 | // Enable modernizer only for Go1.27. |
| 67 | if !analyzerutil.FileUsesGoVersion(pass, file, versions.Go1_27) { |
| 68 | return |
| 69 | } |
| 70 | // If any comments overlap with the range to delete, don't suggest a fix. |
| 71 | if !moreiters.Empty(astutil.Comments(file, closingPos, innerLit.Rbrace+1)) { |
| 72 | continue |
| 73 | } |
| 74 | edits = append(edits, []analysis.TextEdit{ |
| 75 | // T{U: U{f: v, ...}} |
| 76 | // ----- - |
| 77 | { |
| 78 | // Delete the key and the opening brace of the inner struct literal. |
| 79 | Pos: kv.Pos(), |
| 80 | End: innerLit.Lbrace + 1, |
| 81 | }, |
| 82 | { |
| 83 | // Delete the corresponding closing brace, including preceding |
| 84 | // white space or commas. Failing to delete trailing commas may |
| 85 | // result in invalid code. |
| 86 | Pos: closingPos, |
| 87 | End: innerLit.Rbrace + 1, |
| 88 | }, |
| 89 | }...) |
| 90 | names = append(names, kv.Key.(*ast.Ident).Name) |
| 91 | check(innerLit) |
| 92 | } |
| 93 | } |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | if curLit.ParentEdgeKind() != edge.KeyValueExpr_Value { |
| 98 | compLit := curLit.Node().(*ast.CompositeLit) |
| 99 | check(compLit) // non-nested comp lit |
| 100 | } |
| 101 | if len(edits) > 0 { |
| 102 | pass.Report(analysis.Diagnostic{ |
| 103 | Pos: curLit.Node().Pos(), |
| 104 | End: curLit.Node().End(), |
| 105 | Message: "embedded field type can be removed from struct literal", |
| 106 | SuggestedFixes: []analysis.SuggestedFix{ |
| 107 | { |
| 108 | Message: fmt.Sprintf("Remove embedded field type%s %s", cond(len(names) == 1, "", "s"), strings.Join(names, ", ")), |
| 109 | TextEdits: edits, |
| 110 | }, |
| 111 | }, |
| 112 | }) |
| 113 | } |
| 114 | } |
| 115 | return nil, nil |
| 116 | } |
| 117 | |
| 118 | // isEmbeddedFieldLit determines whether elt is a KeyValueExpr "T: T{...}" for |
| 119 | // an embedded field for which we can safely remove its type. |
| 120 | // If so, it returns the corresponding CompositeLit. |
| 121 | // If elt contains an unkeyed field or ambiguous type, it returns nil. |
| 122 | func isEmbeddedFieldLit(info *types.Info, topLevelType types.Type, kv *ast.KeyValueExpr) *ast.CompositeLit { |
| 123 | obj := keyedField(info, kv) |
| 124 | if obj == nil || !obj.Embedded() { |
| 125 | return nil |
| 126 | } |
| 127 | lit, ok := kv.Value.(*ast.CompositeLit) |
| 128 | if !ok { |
| 129 | return nil |
| 130 | } |
| 131 | // We cannot remove this type if any of its nested composite elements have |
| 132 | // unkeyed fields or are ambiguous, so we check for those conditions before |
| 133 | // returning. |
| 134 | for _, elt := range lit.Elts { |
| 135 | kv, ok := elt.(*ast.KeyValueExpr) |
| 136 | if !ok { |
| 137 | return nil |
| 138 | } |
| 139 | obj := keyedField(info, kv) |
| 140 | if obj == nil { |
| 141 | return nil |
| 142 | } |
| 143 | k := kv.Key.(*ast.Ident) // can't fail |
| 144 | // Cannot promote an ambiguous type, for example: |
| 145 | // type T struct { A; B } |
| 146 | // type A struct { x int } |
| 147 | // type B struct { x int } |
| 148 | // _ = T{A: A{x: 1}} |
| 149 | // cannot be simplified to T{x: 1} because T has two different embedded fields called "x". |
| 150 | parentObj, _, _ := types.LookupFieldOrMethod(topLevelType, true, obj.Pkg(), k.Name) |
| 151 | if parentObj != obj { |
| 152 | return nil |
| 153 | } |
| 154 | } |
| 155 | return lit |
| 156 | } |
| 157 | |
| 158 | // keyedField reports whether the key of kv is an embedded field type. If so, it |
| 159 | // returns the type of the embedded field, otherwise it returns nil. |
| 160 | func keyedField(info *types.Info, kv *ast.KeyValueExpr) *types.Var { |
| 161 | k, ok := kv.Key.(*ast.Ident) |
| 162 | if !ok { |
| 163 | return nil |
| 164 | } |
| 165 | obj, ok := info.ObjectOf(k).(*types.Var) |
| 166 | if !ok || !obj.IsField() { |
| 167 | return nil |
| 168 | } |
| 169 | return obj |
| 170 | } |