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