Debian Codegraph @

go/analysis/passes/modernize/reflect.go

raw symbols SCIP
1 // Copyright 2025 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 // This file defines modernizers that use the "reflect" package.
8
9 import (
10 "go/ast"
11 "go/types"
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/types/typeutil"
17 "golang.org/x/tools/internal/analysis/analyzerutil"
18 typeindexanalyzer "golang.org/x/tools/internal/analysis/typeindex"
19 "golang.org/x/tools/internal/astutil"
20 "golang.org/x/tools/internal/refactor"
21 "golang.org/x/tools/internal/typesinternal"
22 "golang.org/x/tools/internal/typesinternal/typeindex"
23 "golang.org/x/tools/internal/versions"
24 )
25
26 var ReflectTypeForAnalyzer = &analysis.Analyzer{
27 Name: "reflecttypefor",
28 Doc: analyzerutil.MustExtractDoc(doc, "reflecttypefor"),
29 Requires: []*analysis.Analyzer{
30 inspect.Analyzer,
31 typeindexanalyzer.Analyzer,
32 },
33 Run: reflecttypefor,
34 URL: "https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/modernize#reflecttypefor",
35 }
36
37 func reflecttypefor(pass *analysis.Pass) (any, error) {
38 var (
39 index = pass.ResultOf[typeindexanalyzer.Analyzer].(*typeindex.Index)
40 info = pass.TypesInfo
41
42 reflectTypeOf = index.Object("reflect", "TypeOf")
43 )
44
45 for curCall := range index.Calls(reflectTypeOf) {
46 call := curCall.Node().(*ast.CallExpr)
47 // Have: reflect.TypeOf(expr)
48
49 expr := call.Args[0]
50
51 // reflect.TypeFor cannot be instantiated with an untyped nil.
52 // We use type information rather than checking the identifier name
53 // to correctly handle edge cases where "nil" is shadowed (e.g. nil := "nil").
54 if info.Types[expr].IsNil() {
55 continue
56 }
57
58 if !typesinternal.NoEffects(info, expr) {
59 continue // don't eliminate operand: may have effects
60 }
61
62 t := info.TypeOf(expr)
63 var edits []analysis.TextEdit
64
65 // Special cases for TypeOf((*T)(nil)).Elem(), and
66 // TypeOf([]T(nil)).Elem(), needed when T is an interface type.
67 if curCall.ParentEdgeKind() == edge.SelectorExpr_X {
68 curSel := astutil.UnparenEnclosingCursor(curCall).Parent()
69 if curSel.ParentEdgeKind() == edge.CallExpr_Fun {
70 call2 := astutil.UnparenEnclosingCursor(curSel).Parent().Node().(*ast.CallExpr) // potentially .Elem()
71 obj := typeutil.Callee(info, call2)
72 if typesinternal.IsMethodNamed(obj, "reflect", "Type", "Elem") {
73 // reflect.TypeOf(expr).Elem()
74 // -------
75 // reflect.TypeOf(expr)
76 if typ, hasElem := t.(interface{ Elem() types.Type }); hasElem {
77 // Have: TypeOf(expr).Elem() where expr is *T, []T, [k]T, chan T, map[K]T, etc.
78 t = typ.Elem()
79 edits = []analysis.TextEdit{{
80 Pos: call.End(),
81 End: call2.End(),
82 }}
83 }
84 }
85 }
86 }
87
88 // TypeOf(x) where x has an interface type is a
89 // dynamic operation; don't transform it to TypeFor.
90 // (edits == nil means "not the Elem() special case".)
91 if types.IsInterface(t) && edits == nil {
92 continue
93 }
94
95 file := astutil.EnclosingFile(curCall)
96 if !analyzerutil.FileUsesGoVersion(pass, file, versions.Go1_22) {
97 continue // TypeFor requires go1.22
98 }
99 tokFile := pass.Fset.File(file.Pos())
100
101 // Format the type as valid Go syntax.
102 // TODO(adonovan): FileQualifier needs to respect
103 // visibility at the current point, and either fail
104 // or edit the imports as needed.
105 qual := typesinternal.FileQualifier(file, pass.Pkg)
106 tstr := types.TypeString(t, qual)
107
108 sel, ok := call.Fun.(*ast.SelectorExpr)
109 if !ok {
110 continue // e.g. reflect was dot-imported
111 }
112
113 // Don't offer a fix if the type contains an unnamed struct or unnamed
114 // interface because the replacement would be significantly more verbose.
115 // (See golang/go#76698)
116 if isComplicatedType(t) {
117 continue
118 }
119
120 // Don't offer the fix if the type string is too long. We define "too
121 // long" as more than three times the length of the original expression
122 // and at least 16 characters (a 3x length increase of a very
123 // short expression should not be cause for skipping the fix).
124 oldLen := int(expr.End() - expr.Pos())
125 newLen := len(tstr)
126 if newLen >= 16 && newLen > 3*oldLen {
127 continue
128 }
129
130 // If the call argument contains the last use
131 // of a variable, as in:
132 // var zero T
133 // reflect.TypeOf(zero)
134 // remove the declaration of that variable.
135 curArg0 := curCall.ChildAt(edge.CallExpr_Args, 0)
136 edits = append(edits, refactor.DeleteUnusedVars(index, info, tokFile, curArg0)...)
137
138 pass.Report(analysis.Diagnostic{
139 Pos: call.Fun.Pos(),
140 End: call.Fun.End(),
141 Message: "reflect.TypeOf call can be simplified using TypeFor",
142 SuggestedFixes: []analysis.SuggestedFix{{
143 // reflect.TypeOf (...T value...)
144 // ------ -------------
145 // reflect.TypeFor[T]( )
146 Message: "Replace TypeOf by TypeFor",
147 TextEdits: append([]analysis.TextEdit{
148 {
149 Pos: sel.Sel.Pos(),
150 End: sel.Sel.End(),
151 NewText: []byte("TypeFor[" + tstr + "]"),
152 },
153 // delete (pure) argument
154 {
155 Pos: call.Lparen + 1,
156 End: call.Rparen,
157 },
158 }, edits...),
159 }},
160 })
161 }
162
163 return nil, nil
164 }
165
166 // isComplicatedType reports whether type t is complicated, e.g. it is or contains an
167 // unnamed struct, interface, or function signature.
168 func isComplicatedType(t types.Type) bool {
169 var check func(typ types.Type) bool
170 check = func(typ types.Type) bool {
171 switch t := typ.(type) {
172 case typesinternal.NamedOrAlias:
173 for ta := range t.TypeArgs().Types() {
174 if check(ta) {
175 return true
176 }
177 }
178 return false
179 case *types.Struct, *types.Interface, *types.Signature:
180 // These are complex types with potentially many elements
181 // so we should avoid duplicating their definition.
182 return true
183 case *types.Pointer:
184 return check(t.Elem())
185 case *types.Slice:
186 return check(t.Elem())
187 case *types.Array:
188 return check(t.Elem())
189 case *types.Chan:
190 return check(t.Elem())
191 case *types.Map:
192 return check(t.Key()) || check(t.Elem())
193 case *types.Basic:
194 return false
195 case *types.TypeParam:
196 return false
197 default:
198 // Includes types.Union
199 return true
200 }
201 }
202
203 return check(t)
204 }