Debian Codegraph @

go/analysis/passes/modernize/slicesbackward.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 "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/types/typeutil"
18 "golang.org/x/tools/internal/analysis/analyzerutil"
19 typeindexanalyzer "golang.org/x/tools/internal/analysis/typeindex"
20 "golang.org/x/tools/internal/astutil"
21 "golang.org/x/tools/internal/refactor"
22 "golang.org/x/tools/internal/typesinternal/typeindex"
23 "golang.org/x/tools/internal/versions"
24 )
25
26 // TODO(adonovan): needs a proposal for a public symbol.
27 var slicesBackwardAnalyzer = &analysis.Analyzer{
28 Name: "slicesbackward",
29 Doc: analyzerutil.MustExtractDoc(doc, "slicesbackward"),
30 Requires: []*analysis.Analyzer{
31 inspect.Analyzer,
32 typeindexanalyzer.Analyzer,
33 },
34 Run: slicesbackward,
35 URL: "https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/modernize#slicesbackward",
36 }
37
38 // slicesbackward offers a fix to replace a manually-written backward loop:
39 //
40 // for i := len(s) - 1; i >= 0; i-- {
41 // use(s[i])
42 // }
43 //
44 // with a range loop using slices.Backward (added in Go 1.23):
45 //
46 // for _, v := range slices.Backward(s) {
47 // use(v)
48 // }
49 //
50 // If the loop index is needed beyond just indexing into the slice, both
51 // the index and value variables are kept:
52 //
53 // for i, v := range slices.Backward(s) { ... }
54 func slicesbackward(pass *analysis.Pass) (any, error) {
55 // Skip packages that are in the slices stdlib dependency tree to
56 // avoid import cycles.
57 if within(pass, "slices") {
58 return nil, nil
59 }
60
61 var (
62 info = pass.TypesInfo
63 index = pass.ResultOf[typeindexanalyzer.Analyzer].(*typeindex.Index)
64 )
65
66 for curFile := range filesUsingGoVersion(pass, versions.Go1_23) {
67 file := curFile.Node().(*ast.File)
68
69 nextLoop:
70 for curLoop := range curFile.Preorder((*ast.ForStmt)(nil)) {
71 loop := curLoop.Node().(*ast.ForStmt)
72
73 // Match init: i := len(s) - 1 or i = len(s) - 1
74 init, ok := loop.Init.(*ast.AssignStmt)
75 if !ok || !isSimpleAssign(init) {
76 continue
77 }
78 indexIdent, ok := init.Lhs[0].(*ast.Ident)
79 if !ok {
80 continue
81 }
82 indexObj := info.ObjectOf(indexIdent).(*types.Var)
83
84 // RHS must be len(s) - 1.
85 binRhs, ok := init.Rhs[0].(*ast.BinaryExpr)
86 if !ok || binRhs.Op != token.SUB {
87 continue
88 }
89 if !isIntLiteral(info, binRhs.Y, 1) {
90 continue
91 }
92 lenCall, ok := binRhs.X.(*ast.CallExpr)
93 if !ok || typeutil.Callee(info, lenCall) != builtinLen {
94 continue
95 }
96 if len(lenCall.Args) != 1 {
97 continue
98 }
99 sliceExpr := lenCall.Args[0]
100 if _, ok := info.TypeOf(sliceExpr).Underlying().(*types.Slice); !ok {
101 continue
102 }
103
104 // Match cond: i >= 0
105 cond, ok := loop.Cond.(*ast.BinaryExpr)
106 if !ok || cond.Op != token.GEQ {
107 continue
108 }
109 if !astutil.EqualSyntax(cond.X, indexIdent) {
110 continue
111 }
112 if !isZeroIntConst(info, cond.Y) {
113 continue
114 }
115
116 // Match post: i--
117 dec, ok := loop.Post.(*ast.IncDecStmt)
118 if !ok || dec.Tok != token.DEC {
119 continue
120 }
121 if !astutil.EqualSyntax(dec.X, indexIdent) {
122 continue
123 }
124
125 // Check that i is not used as an lvalue in the loop body.
126 // If init is = (not :=), i is a pre-existing variable; also
127 // check that it is not used as an lvalue outside the loop
128 // (e.g. &i before the loop).
129 bodyCur := curLoop.Child(loop.Body)
130 for curUse := range index.Uses(indexObj) {
131 if !isScalarLvalue(info, curUse) {
132 continue
133 }
134 if bodyCur.Contains(curUse) {
135 continue nextLoop // i is mutated in loop body
136 }
137 if init.Tok == token.ASSIGN && !curLoop.Contains(curUse) {
138 continue nextLoop // pre-existing i is an lvalue outside the loop
139 }
140 }
141
142 // Find all uses of i in the loop body. Classify as:
143 // s[i] — pure element accesses that can be replaced by the value var
144 // other — index used for non-indexing purposes
145 var (
146 // First assignment in the loop body of the form "name := s[i]"; or nil.
147 firstSliceIdxAssign *ast.AssignStmt
148 // List of s[i] expressions to replace by the value var (excludes firstSliceIdxAssign, which will be entirely removed).
149 sliceIdxsReplace []*ast.IndexExpr
150 // Total count of s[i] usages.
151 sliceIdxs int
152 // Non-indexing uses of i.
153 otherUses int
154 )
155 for curUse := range index.Uses(indexObj) {
156 if !bodyCur.Contains(curUse) {
157 continue
158 }
159 // Is i in the Index position of an s[i] expression?
160 // If so, we also need to check whether s[i] is an lvalue. If we're
161 // mutating the slice or taking an element's address, a fix will not
162 // be offered.
163 if curUse.ParentEdgeKind() == edge.IndexExpr_Index {
164 if isScalarLvalue(pass.TypesInfo, curUse.Parent()) {
165 continue nextLoop
166 }
167 idxCur := curUse.Parent()
168 idxExpr := idxCur.Node().(*ast.IndexExpr)
169 if astutil.EqualSyntax(idxExpr.X, sliceExpr) {
170 sliceIdxs++
171 // If the current statement is the first in the body of the form
172 // "name := s[i]", save it so we can use "name" as the value
173 // variable in slices.Backward. We can also remove the entire assign
174 // statement.
175 if firstSliceIdxAssign == nil && idxCur.ParentEdgeKind() == edge.AssignStmt_Rhs {
176 assignStmt := idxCur.Parent().Node().(*ast.AssignStmt)
177 if len(assignStmt.Lhs) == 1 && assignStmt.Tok == token.DEFINE {
178 // The condition above implies that assignStmt.Lhs[0] is a valid
179 // identifier.
180 firstSliceIdxAssign = assignStmt
181 // We don't need to replace the index expr with the value variable
182 // name if we are going to remove the entire assignment.
183 continue
184 }
185 }
186 sliceIdxsReplace = append(sliceIdxsReplace, idxExpr)
187 continue
188 }
189 }
190 otherUses++
191 }
192
193 // Build the suggested fix.
194 //
195 // for i := len(s) - 1; i >= 0; i-- { ... s[i] ... }
196 // -------------------------------- ----
197 // for _, v := range slices.Backward(s) { ... v ... }
198 sliceStr := astutil.Format(pass.Fset, sliceExpr)
199 prefix, edits := refactor.AddImport(info, file, "slices", "slices", "Backward", loop.Pos())
200 elemName := chooseValueName(firstSliceIdxAssign, sliceStr)
201 elemName = freshName(info, index, info.Scopes[loop], loop.Pos(), bodyCur, bodyCur, token.NoPos, elemName)
202
203 // Replace each s[i] with elemName (except for in the statement of the
204 // form "name := s[i]" where we might have gotten elemName from - we will
205 // delete this entire statement instead).
206 for _, sx := range sliceIdxsReplace {
207 edits = append(edits, analysis.TextEdit{
208 Pos: sx.Pos(),
209 End: sx.End(),
210 NewText: []byte(elemName),
211 })
212 }
213
214 if firstSliceIdxAssign != nil {
215 edits = append(edits, analysis.TextEdit{
216 Pos: firstSliceIdxAssign.Pos(),
217 End: firstSliceIdxAssign.End(),
218 })
219 }
220
221 // Replace the loop header with a range over slices.Backward. In
222 // well-typed code, at least one of the index or value variables must be
223 // referenced inside the loop body (otherUses + sliceIndexes > 0).
224 var vars string
225 if otherUses == 0 { // sliceIdxs > 0
226 // All uses of i are s[i]; drop the index variable.
227 vars = fmt.Sprintf("_, %s", elemName)
228 } else if sliceIdxs == 0 { // otherUses > 0
229 // Index i is not used in any s[i] expressions; drop the value variable.
230 vars = indexIdent.Name
231 } else { // otherUses > 0 && sliceIdxs > 0, keep both variables.
232 vars = fmt.Sprintf("%s, %s", indexIdent.Name, elemName)
233 }
234 header := fmt.Sprintf("%s := range %sBackward(%s)", vars, prefix, sliceStr)
235 edits = append(edits, analysis.TextEdit{
236 Pos: loop.Init.Pos(),
237 End: loop.Post.End(),
238 NewText: []byte(header),
239 })
240
241 pass.Report(analysis.Diagnostic{
242 Pos: loop.Init.Pos(),
243 End: loop.Post.End(),
244 Message: "backward loop over slice can be modernized using slices.Backward",
245 SuggestedFixes: []analysis.SuggestedFix{{
246 Message: fmt.Sprintf("Replace with range slices.Backward(%s)", sliceStr),
247 TextEdits: edits,
248 }},
249 })
250 }
251 }
252 return nil, nil
253 }
254
255 // chooseValueName uses a heuristic to generate a name for the value variable in
256 // the call to slices.Backward.
257 func chooseValueName(assign *ast.AssignStmt, sliceStr string) string {
258 if assign != nil {
259 return assign.Lhs[0].(*ast.Ident).Name
260 }
261 // Heuristic: remove plural s suffix from slice var
262 // if present, otherwise use first letter.
263 if token.IsIdentifier(sliceStr) && len(sliceStr) > 1 {
264 if single, ok := strings.CutSuffix(sliceStr, "s"); ok {
265 return single
266 }
267 return sliceStr[:1] // first letter (assuming ASCII)
268 }
269 return "v"
270 }