Debian Codegraph @

go/analysis/passes/modernize/atomictypes.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 "fmt"
9 "go/ast"
10 "go/token"
11 "go/types"
12 "strings"
13
14 "golang.org/x/tools/go/analysis"
15 "golang.org/x/tools/go/analysis/passes/inspect"
16 "golang.org/x/tools/go/ast/edge"
17 "golang.org/x/tools/go/ast/inspector"
18 "golang.org/x/tools/go/types/typeutil"
19 "golang.org/x/tools/internal/analysis/analyzerutil"
20 typeindexanalyzer "golang.org/x/tools/internal/analysis/typeindex"
21 "golang.org/x/tools/internal/astutil"
22 "golang.org/x/tools/internal/refactor"
23 "golang.org/x/tools/internal/typesinternal"
24 "golang.org/x/tools/internal/typesinternal/typeindex"
25 "golang.org/x/tools/internal/versions"
26 )
27
28 var AtomicTypesAnalyzer = &analysis.Analyzer{
29 Name: "atomictypes",
30 Doc: analyzerutil.MustExtractDoc(doc, "atomictypes"),
31 Requires: []*analysis.Analyzer{
32 inspect.Analyzer,
33 typeindexanalyzer.Analyzer,
34 },
35 Run: runAtomic,
36 URL: "https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/modernize#atomictypes",
37 }
38
39 // TODO(mkalil): support the Pointer variants.
40 // Consider the following function signatures for pointer loading:
41 // func LoadPointer(addr *unsafe.Pointer) (val unsafe.Pointer)
42 // func (x *Pointer[T]) Load() *T
43 // Since the former uses *unsafe.Pointer while the latter uses *Pointer[T],
44 // we would need to determine the type T to apply the transformation, and there
45 // will be additional edits required to remove any *unsafe.Pointer casts.
46 // "LoadPointer", "StorePointer", "SwapPointer", "CompareAndSwapPointer"
47
48 // sync/atomic functions of interest. Some added in go1.19, some added in go1.23.
49 var syncAtomicFuncs = []string{
50 // Added in go1.19.
51 "AddInt32", "AddInt64", "AddUint32", "AddUint64", "AddUintptr",
52 "CompareAndSwapInt32", "CompareAndSwapInt64", "CompareAndSwapUint32", "CompareAndSwapUint64", "CompareAndSwapUintptr",
53 "LoadInt32", "LoadInt64", "LoadUint32", "LoadUint64", "LoadUintptr",
54 "StoreInt32", "StoreInt64", "StoreUint32", "StoreUint64", "StoreUintptr",
55 "SwapInt32", "SwapInt64", "SwapUint32", "SwapUint64", "SwapUintptr",
56 // Added in go1.23.
57 "AndInt32", "AndInt64", "AndUint32", "AndUint64", "AndUintptr",
58 "OrInt32", "OrInt64", "OrUint32", "OrUint64", "OrUintptr",
59 }
60
61 func runAtomic(pass *analysis.Pass) (any, error) {
62 if !typesinternal.Imports(pass.Pkg, "sync/atomic") {
63 return nil, nil // doesn't directly import sync/atomic
64 }
65
66 var (
67 index = pass.ResultOf[typeindexanalyzer.Analyzer].(*typeindex.Index)
68 info = pass.TypesInfo
69 )
70
71 // Gather all candidate variables v appearing
72 // in calls to atomic.AddInt32(&v, ...) et al.
73 var (
74 atomicPkg *types.Package
75 vars = make(map[*types.Var]string) // maps candidate vars v to the name of the call they appear in
76 )
77 for _, funcName := range syncAtomicFuncs {
78 obj := index.Object("sync/atomic", funcName)
79 if obj == nil {
80 continue
81 }
82 atomicPkg = obj.Pkg()
83 for curCall := range index.Calls(obj) {
84 call := curCall.Node().(*ast.CallExpr)
85 if unary, ok := call.Args[0].(*ast.UnaryExpr); ok && unary.Op == token.AND {
86 var v *types.Var
87 switch x := unary.X.(type) {
88 case *ast.Ident:
89 v, _ = info.Uses[x].(*types.Var)
90 case *ast.SelectorExpr:
91 if seln, ok := info.Selections[x]; ok {
92 v, _ = seln.Obj().(*types.Var)
93 }
94 }
95 if v != nil && !v.Exported() {
96 // v must be a non-exported package or local var, or a struct field.
97 switch v.Kind() {
98 case types.RecvVar, types.ParamVar, types.ResultVar:
99 continue // fix would change func signature
100 }
101 vars[v] = funcName
102 }
103 }
104 }
105 }
106
107 // Check that all uses of each candidate variable
108 // appear in calls of the form atomic.AddInt32(&v, ...).
109 nextvar:
110 for v, funcName := range vars {
111 fixFiles := make(map[*ast.File]bool) // unique files involved in the current fix
112
113 // Check the form of the declaration: var v int or struct { v int }
114 def, ok := index.Def(v)
115 if !ok {
116 continue
117 }
118 var (
119 typ ast.Expr
120 names []*ast.Ident
121 )
122 switch parent := def.Parent().Node().(type) {
123 case *ast.Field: // struct { v int }
124 names = parent.Names
125 typ = parent.Type
126 case *ast.ValueSpec: // var v int
127 if len(parent.Values) > 0 {
128 // e.g. var v int = 5
129 // skip because rewriting as `var v atomic.Int32 = 5` is invalid
130 continue
131 }
132 names = parent.Names
133 typ = parent.Type
134 }
135 if len(names) != 1 || typ == nil {
136 continue // v is not the sole var declared here (e.g. var x, y int32); or no explicit type
137 }
138 oldType := info.TypeOf(typ) // e.g. "int32"
139 newType := strings.Title(oldType.Underlying().String()) // e.g. "Int32"
140
141 file := astutil.EnclosingFile(def)
142 // Get package prefix to avoid shadowing, and import edits, which may be
143 // necessary if the fix spans files.
144 // For example: file "a" declares an int32, which doesn't require the
145 // sync/atomic import, while file "b" calls atomic.LoadInt32(v). After
146 // the fix, the need for the import will shift from the use in file "b"
147 // (which becomes a method call v.Load) to the declaration in file "a"
148 // (which becomes atomic.Int32).
149 pkgPrefix, edits := refactor.AddImport(pass.TypesInfo, file, "atomic", "sync/atomic", "", def.Node().Pos())
150 // Edit the type.
151 //
152 // var v int32
153 // ------------
154 // var v atomic.Int32
155 edits = append(edits, analysis.TextEdit{
156 Pos: typ.Pos(),
157 End: typ.End(),
158 NewText: fmt.Appendf(nil, "%s%s", pkgPrefix, newType),
159 })
160 fixFiles[file] = true
161
162 // Each valid use is an Ident v or Selector expr.v within an atomic.F(&...) call.
163 var validUses []inspector.Cursor
164 for cur := range index.Uses(v) {
165 if v.IsField() && cur.ParentEdgeKind() == edge.KeyValueExpr_Key {
166 continue nextvar // we cannot fix initial an value assignment T{v: 1}
167 }
168 if cur.ParentEdgeKind() == edge.SelectorExpr_Sel {
169 cur = cur.Parent() // ascend from v to expr.v
170 }
171 // Inv: cur is the l-value expression denoting v.
172 // v must appear beneath atomic.AddInt32(&v, ...) call.
173 valid := false
174 if cur.ParentEdgeKind() == edge.UnaryExpr_X &&
175 cur.Parent().Node().(*ast.UnaryExpr).Op == token.AND {
176 if ek, idx := cur.Parent().ParentEdge(); ek == edge.CallExpr_Args && idx == 0 {
177 curCall := cur.Parent().Parent()
178 call := curCall.Node().(*ast.CallExpr)
179 if fn, ok := typeutil.Callee(info, call).(*types.Func); ok && fn.Pkg() == atomicPkg {
180 valid = true
181 }
182 }
183 }
184
185 if !valid {
186 // More complex case: reject candidate.
187 //
188 // For example, cur may be an unsynchronized load (e.g. v == 0). To
189 // avoid a type conversion error, we'd have to rewrite this as
190 // v.Load(). However, this is an invalid rewrite: if the program is
191 // mixing atomic operations with unsynchronized reads, the author
192 // might have accidentally introduced a data race and the suggested
193 // fix could obscure the mistake. Or, if the usage is intentional,
194 // rewriting may result in a behavior change.
195 continue nextvar
196 }
197 validUses = append(validUses, cur)
198 }
199
200 for _, cur := range validUses {
201 vexpr := cur.Node()
202 call := cur.Parent().Parent().Node().(*ast.CallExpr)
203 fn := typeutil.Callee(info, call).(*types.Func)
204 // atomic.AddInt32(&v, ...)
205 // ----------------- -----
206 // v.Add(...)
207 after := vexpr.End() // LoadInt32(&v⁁)
208 if len(call.Args) > 1 {
209 after = call.Args[1].Pos() // AddInt32(&v, ⁁...)
210 }
211 verb := strings.TrimSuffix(fn.Name(), newType) // "AddInt32" => "Add"
212 edits = append(edits, []analysis.TextEdit{
213 {
214 Pos: call.Pos(),
215 End: vexpr.Pos(),
216 },
217 {
218 Pos: vexpr.End(),
219 End: after,
220 NewText: fmt.Appendf(nil, ".%s(", verb),
221 },
222 }...)
223 fixFiles[astutil.EnclosingFile(cur)] = true
224 }
225
226 // Check minimum Go version: go1.19, or 1.23 for the And/Or functions.
227 if !(analyzerutil.FileUsesGoVersion(pass, file, versions.Go1_19) ||
228 analyzerutil.FileUsesGoVersion(pass, file, versions.Go1_23) &&
229 (strings.HasPrefix(funcName, "And") || strings.HasPrefix(funcName, "Or"))) {
230 continue
231 }
232
233 // Skip if v is not local and the package has ignored files as it may be
234 // an incomplete transformation.
235 if !isLocal(v) && len(pass.IgnoredFiles) > 0 {
236 continue
237 }
238
239 pass.Report(analysis.Diagnostic{
240 Pos: names[0].Pos(),
241 End: typ.End(),
242 Message: fmt.Sprintf("var %s %s may be simplified using atomic.%s", v.Name(), oldType, newType),
243 SuggestedFixes: []analysis.SuggestedFix{{
244 Message: fmt.Sprintf("Replace %s by atomic.%s", oldType, newType),
245 TextEdits: edits,
246 }},
247 })
248 }
249
250 return nil, nil
251 }