Debian Codegraph @

go/analysis/passes/modernize/unsafefuncs.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 import (
8 "fmt"
9 "go/ast"
10 "go/token"
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/ast/inspector"
17 "golang.org/x/tools/internal/analysis/analyzerutil"
18 "golang.org/x/tools/internal/astutil"
19 "golang.org/x/tools/internal/refactor"
20 "golang.org/x/tools/internal/typesinternal"
21 "golang.org/x/tools/internal/versions"
22 )
23
24 // TODO(adonovan): also support:
25 //
26 // func String(ptr *byte, len IntegerType) string
27 // func StringData(str string) *byte
28 // func Slice(ptr *ArbitraryType, len IntegerType) []ArbitraryType
29 // func SliceData(slice []ArbitraryType) *ArbitraryType
30
31 // TODO(adonovan): needs a proposal for a public symbol.
32 var unsafeFuncsAnalyzer = &analysis.Analyzer{
33 Name: "unsafefuncs",
34 Doc: analyzerutil.MustExtractDoc(doc, "unsafefuncs"),
35 Requires: []*analysis.Analyzer{inspect.Analyzer},
36 Run: unsafefuncs,
37 URL: "https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/modernize#unsafefuncs",
38 }
39
40 func unsafefuncs(pass *analysis.Pass) (any, error) {
41 // Short circuit if the package doesn't use unsafe.
42 // (In theory one could use some imported alias of unsafe.Pointer,
43 // but let's ignore that.)
44 if !typesinternal.Imports(pass.Pkg, "unsafe") {
45 return nil, nil
46 }
47
48 var (
49 inspect = pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
50 info = pass.TypesInfo
51 tUnsafePointer = types.Typ[types.UnsafePointer]
52 )
53
54 // isConversion reports whether e is a conversion T(x).
55 // If so, it returns T and x.
56 isConversion := func(curExpr inspector.Cursor) (t types.Type, x inspector.Cursor) {
57 e := curExpr.Node().(ast.Expr)
58 if conv, ok := ast.Unparen(e).(*ast.CallExpr); ok && len(conv.Args) == 1 {
59 if tv := pass.TypesInfo.Types[conv.Fun]; tv.IsType() {
60 return tv.Type, curExpr.ChildAt(edge.CallExpr_Args, 0)
61 }
62 }
63 return
64 }
65
66 // The general form is where ptr and the result are of type unsafe.Pointer:
67 //
68 // unsafe.Pointer(uintptr(ptr) + uintptr(n))
69 // =>
70 // unsafe.Add(ptr, n)
71
72 // Search for 'unsafe.Pointer(uintptr + uintptr)'
73 // where the left operand was converted from a pointer.
74 //
75 // (Start from sum, not conversion, as it is not
76 // uncommon to use a local type alias for unsafe.Pointer.)
77 for curSum := range inspect.Root().Preorder((*ast.BinaryExpr)(nil)) {
78 if sum, ok := curSum.Node().(*ast.BinaryExpr); ok &&
79 sum.Op == token.ADD &&
80 types.Identical(info.TypeOf(sum.X), types.Typ[types.Uintptr]) &&
81 curSum.ParentEdgeKind() == edge.CallExpr_Args {
82 // Have: sum ≡ T(x:...uintptr... + y:...uintptr...)
83 curX := curSum.ChildAt(edge.BinaryExpr_X, -1)
84 curY := curSum.ChildAt(edge.BinaryExpr_Y, -1)
85
86 // Is sum converted to unsafe.Pointer?
87 curResult := curSum.Parent()
88 if t, _ := isConversion(curResult); !(t != nil && types.Identical(t, tUnsafePointer)) {
89 continue
90 }
91 // Have: result ≡ unsafe.Pointer(x:...uintptr... + y:...uintptr...)
92
93 // Is sum.x converted from unsafe.Pointer?
94 _, curPtr := isConversion(curX)
95 if !curPtr.Valid() {
96 continue
97 }
98 ptr := curPtr.Node().(ast.Expr)
99 if !types.Identical(info.TypeOf(ptr), tUnsafePointer) {
100 continue
101 }
102 // Have: result ≡ unsafe.Pointer(x:uintptr(...unsafe.Pointer...) + y:...uintptr...)
103
104 file := astutil.EnclosingFile(curSum)
105 if !analyzerutil.FileUsesGoVersion(pass, file, versions.Go1_17) {
106 continue // unsafe.Add not available in this file
107 }
108
109 // import "unsafe"
110 unsafedot, edits := refactor.AddImport(info, file, "unsafe", "unsafe", "Add", sum.Pos())
111
112 // unsafe.Pointer(x + y)
113 // --------------- -
114 // x + y
115 edits = append(edits, deleteConv(curResult)...)
116
117 // uintptr (ptr) + offset
118 // ----------- ---- -
119 // unsafe.Add(ptr, offset)
120 edits = append(edits, []analysis.TextEdit{
121 {
122 Pos: sum.Pos(),
123 End: ptr.Pos(),
124 NewText: fmt.Appendf(nil, "%sAdd(", unsafedot),
125 },
126 {
127 Pos: ptr.End(),
128 End: sum.Y.Pos(),
129 NewText: []byte(", "),
130 },
131 {
132 Pos: sum.Y.End(),
133 End: sum.Y.End(),
134 NewText: []byte(")"),
135 },
136 }...)
137
138 // Variant: sum.y operand was converted from another integer type.
139 // Discard the conversion, as Add is generic over integers.
140 //
141 // e.g. unsafe.Pointer(uintptr(ptr) + uintptr(len(s)))
142 // -------- -
143 // unsafe.Add ( ptr, len(s))
144 if t, _ := isConversion(curY); t != nil && isInteger(t) {
145 edits = append(edits, deleteConv(curY)...)
146 }
147
148 pass.Report(analysis.Diagnostic{
149 Pos: sum.Pos(),
150 End: sum.End(),
151 Message: "pointer + integer can be simplified using unsafe.Add",
152 SuggestedFixes: []analysis.SuggestedFix{{
153 Message: "Simplify pointer addition using unsafe.Add",
154 TextEdits: edits,
155 }},
156 })
157 }
158 }
159
160 return nil, nil
161 }
162
163 // deleteConv returns edits for changing T(x) to x, respecting precedence.
164 func deleteConv(cur inspector.Cursor) []analysis.TextEdit {
165 conv := cur.Node().(*ast.CallExpr)
166
167 usesPrec := func(n ast.Node) bool {
168 switch n.(type) {
169 case *ast.BinaryExpr, *ast.UnaryExpr:
170 return true
171 }
172 return false
173 }
174
175 // Be careful not to change precedence of e.g. T(1+2) * 3.
176 // TODO(adonovan): refine this.
177 if usesPrec(cur.Parent().Node()) && usesPrec(conv.Args[0]) {
178 // T(x+y) * z
179 // -
180 // (x+y) * z
181 return []analysis.TextEdit{{
182 Pos: conv.Fun.Pos(),
183 End: conv.Fun.End(),
184 }}
185 }
186
187 // T(x)
188 // -- -
189 // x
190 return []analysis.TextEdit{
191 {
192 Pos: conv.Pos(),
193 End: conv.Args[0].Pos(),
194 },
195 {
196 Pos: conv.Args[0].End(),
197 End: conv.End(),
198 },
199 }
200 }