| 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 | "log" |
| 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/typeparams" |
| 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 RangeIntAnalyzer = &analysis.Analyzer{ |
| 29 | Name: "rangeint", |
| 30 | Doc: analyzerutil.MustExtractDoc(doc, "rangeint"), |
| 31 | Requires: []*analysis.Analyzer{ |
| 32 | inspect.Analyzer, |
| 33 | typeindexanalyzer.Analyzer, |
| 34 | }, |
| 35 | Run: rangeint, |
| 36 | URL: "https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/modernize#rangeint", |
| 37 | } |
| 38 | |
| 39 | // rangeint offers a fix to replace a 3-clause 'for' loop: |
| 40 | // |
| 41 | // for i := 0; i < limit; i++ {} |
| 42 | // |
| 43 | // by a range loop with an integer operand: |
| 44 | // |
| 45 | // for i := range limit {} |
| 46 | // |
| 47 | // Variants: |
| 48 | // - The ':=' may be replaced by '='. |
| 49 | // - The fix may remove "i :=" if it would become unused. |
| 50 | // |
| 51 | // Restrictions: |
| 52 | // - The variable i must not be assigned or address-taken within the |
| 53 | // loop, because a "for range int" loop does not respect assignments |
| 54 | // to the loop index. |
| 55 | // - The limit must not be b.N, to avoid redundancy with bloop's fixes. |
| 56 | // |
| 57 | // Caveats: |
| 58 | // |
| 59 | // The fix causes the limit expression to be evaluated exactly once, |
| 60 | // instead of once per iteration. So, to avoid changing the |
| 61 | // cardinality of side effects, the limit expression must not involve |
| 62 | // function calls (e.g. seq.Len()) or channel receives. Moreover, the |
| 63 | // value of the limit expression must be loop invariant, which in |
| 64 | // practice means it must take one of the following forms: |
| 65 | // |
| 66 | // - a local variable that is assigned only once and not address-taken; |
| 67 | // - a constant; or |
| 68 | // - len(s), where s has the above properties. |
| 69 | func rangeint(pass *analysis.Pass) (any, error) { |
| 70 | var ( |
| 71 | info = pass.TypesInfo |
| 72 | typeindex = pass.ResultOf[typeindexanalyzer.Analyzer].(*typeindex.Index) |
| 73 | ) |
| 74 | |
| 75 | for curFile := range filesUsingGoVersion(pass, versions.Go1_22) { |
| 76 | nextLoop: |
| 77 | for curLoop := range curFile.Preorder((*ast.ForStmt)(nil)) { |
| 78 | loop := curLoop.Node().(*ast.ForStmt) |
| 79 | if init, ok := loop.Init.(*ast.AssignStmt); ok && |
| 80 | isSimpleAssign(init) && |
| 81 | is[*ast.Ident](init.Lhs[0]) && |
| 82 | isZeroIntConst(info, init.Rhs[0]) { |
| 83 | // Have: for i = 0; ... (or i := 0) |
| 84 | index := init.Lhs[0].(*ast.Ident) |
| 85 | |
| 86 | if compare, ok := loop.Cond.(*ast.BinaryExpr); ok && |
| 87 | compare.Op == token.LSS && |
| 88 | astutil.EqualSyntax(compare.X, init.Lhs[0]) { |
| 89 | // Have: for i = 0; i < limit; ... {} |
| 90 | |
| 91 | limit := compare.Y |
| 92 | |
| 93 | // If limit is "len(slice)", simplify it to "slice". |
| 94 | // |
| 95 | // (Don't replace "for i := 0; i < len(map); i++" |
| 96 | // with "for range m" because it's too hard to prove |
| 97 | // that len(m) is loop-invariant). |
| 98 | if call, ok := limit.(*ast.CallExpr); ok && |
| 99 | typeutil.Callee(info, call) == builtinLen && |
| 100 | is[*types.Slice](info.TypeOf(call.Args[0]).Underlying()) { |
| 101 | limit = call.Args[0] |
| 102 | } |
| 103 | |
| 104 | // Check the form of limit: must be a constant, |
| 105 | // or a local var that is not assigned or address-taken. |
| 106 | limitOK := false |
| 107 | if info.Types[limit].Value != nil { |
| 108 | limitOK = true // constant |
| 109 | } else if id, ok := limit.(*ast.Ident); ok { |
| 110 | if v, ok := info.Uses[id].(*types.Var); ok && |
| 111 | !(v.Exported() && typesinternal.IsPackageLevel(v)) { |
| 112 | // limit is a local or unexported global var. |
| 113 | // (An exported global may have uses we can't see.) |
| 114 | for cur := range typeindex.Uses(v) { |
| 115 | if isScalarLvalue(info, cur) { |
| 116 | // Limit var is assigned or address-taken. |
| 117 | continue nextLoop |
| 118 | } |
| 119 | } |
| 120 | limitOK = true |
| 121 | } |
| 122 | } |
| 123 | if !limitOK { |
| 124 | continue nextLoop |
| 125 | } |
| 126 | |
| 127 | validIncrement := false |
| 128 | if inc, ok := loop.Post.(*ast.IncDecStmt); ok && |
| 129 | inc.Tok == token.INC && |
| 130 | astutil.EqualSyntax(compare.X, inc.X) { |
| 131 | // Have: i++ |
| 132 | validIncrement = true |
| 133 | } else if assign, ok := loop.Post.(*ast.AssignStmt); ok && |
| 134 | assign.Tok == token.ADD_ASSIGN && |
| 135 | len(assign.Rhs) == 1 && isIntLiteral(info, assign.Rhs[0], 1) && |
| 136 | len(assign.Lhs) == 1 && astutil.EqualSyntax(compare.X, assign.Lhs[0]) { |
| 137 | // Have: i += 1 |
| 138 | validIncrement = true |
| 139 | } |
| 140 | |
| 141 | if validIncrement { |
| 142 | // Have: for i = 0; i < limit; i++ {} |
| 143 | |
| 144 | // Find references to i within the loop body. |
| 145 | v := info.ObjectOf(index).(*types.Var) |
| 146 | switch v.Kind() { |
| 147 | case types.PackageVar: |
| 148 | continue nextLoop |
| 149 | case types.ResultVar: |
| 150 | // If v is a named result, it is implicitly |
| 151 | // used after the loop (go.dev/issue/76880). |
| 152 | continue nextLoop |
| 153 | } |
| 154 | |
| 155 | used := false |
| 156 | for curId := range curLoop.Child(loop.Body).Preorder((*ast.Ident)(nil)) { |
| 157 | id := curId.Node().(*ast.Ident) |
| 158 | if info.Uses[id] == v { |
| 159 | used = true |
| 160 | |
| 161 | // Reject if any is an l-value (assigned or address-taken): |
| 162 | // a "for range int" loop does not respect assignments to |
| 163 | // the loop variable. |
| 164 | if isScalarLvalue(info, curId) { |
| 165 | continue nextLoop |
| 166 | } |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | // If i is no longer used, delete "i := ". |
| 171 | var edits []analysis.TextEdit |
| 172 | if !used && init.Tok == token.DEFINE { |
| 173 | edits = append(edits, analysis.TextEdit{ |
| 174 | Pos: index.Pos(), |
| 175 | End: init.Rhs[0].Pos(), |
| 176 | }) |
| 177 | } |
| 178 | |
| 179 | // If i is used after the loop, |
| 180 | // don't offer a fix, as a range loop |
| 181 | // leaves i with a different final value (limit-1). |
| 182 | if init.Tok == token.ASSIGN { |
| 183 | // Find the nearest ancestor that is not a label. |
| 184 | // Otherwise, checking for i usage outside of a for |
| 185 | // loop might not function properly further below. |
| 186 | // This is because the i usage might be a child of |
| 187 | // the loop's parent's parent, for example: |
| 188 | // var i int |
| 189 | // Loop: |
| 190 | // for i = 0; i < 10; i++ { break loop } |
| 191 | // // i is in the sibling of the label, not the loop |
| 192 | // fmt.Println(i) |
| 193 | // |
| 194 | ancestor := curLoop.Parent() |
| 195 | for is[*ast.LabeledStmt](ancestor.Node()) { |
| 196 | ancestor = ancestor.Parent() |
| 197 | } |
| 198 | for curId := range ancestor.Preorder((*ast.Ident)(nil)) { |
| 199 | id := curId.Node().(*ast.Ident) |
| 200 | if info.Uses[id] == v { |
| 201 | // Is i used after loop? |
| 202 | if id.Pos() > loop.End() { |
| 203 | continue nextLoop |
| 204 | } |
| 205 | // Is i used within a defer statement |
| 206 | // that is within the scope of i? |
| 207 | // var i int |
| 208 | // defer func() { print(i)} |
| 209 | // for i = ... { ... } |
| 210 | for curDefer := range curId.Enclosing((*ast.DeferStmt)(nil)) { |
| 211 | if curDefer.Node().Pos() > v.Pos() { |
| 212 | continue nextLoop |
| 213 | } |
| 214 | } |
| 215 | } |
| 216 | } |
| 217 | } |
| 218 | |
| 219 | // The loop index (v) must not be a type parameter constrained by |
| 220 | // multiple distinct integer types, or a type parameter constrained |
| 221 | // by non-integer types. Transforming such instances to a range loop |
| 222 | // would result in a compiler error. |
| 223 | // See golang/go#78571. |
| 224 | terms, err := typeparams.NormalTerms(v.Type()) // NormalTerms works for any type |
| 225 | if err != nil { |
| 226 | log.Fatalf("internal error: cannot compute type set of loop var %v: %v", v, err) |
| 227 | } |
| 228 | if len(terms) != 0 { |
| 229 | // From the spec (https://go.dev/ref/spec#For_range): |
| 230 | // "If the type of the range expression is a type parameter, all |
| 231 | // types in its type set must have the same underlying type and the |
| 232 | // range expression must be valid for that type." |
| 233 | // |
| 234 | // Check if all terms have the same underlying type by comparing |
| 235 | // them to the first term. |
| 236 | u := terms[0].Type().Underlying() |
| 237 | // If the constraint has any non-integer terms, skip. (Range over |
| 238 | // float is not allowed.) |
| 239 | if !isInteger(u) { |
| 240 | continue nextLoop |
| 241 | } |
| 242 | for _, term := range terms[1:] { |
| 243 | if !types.Identical(u, term.Type().Underlying()) { |
| 244 | continue nextLoop |
| 245 | } |
| 246 | } |
| 247 | } |
| 248 | |
| 249 | // If limit is len(slice), |
| 250 | // simplify "range len(slice)" to "range slice". |
| 251 | if call, ok := limit.(*ast.CallExpr); ok && |
| 252 | typeutil.Callee(info, call) == builtinLen && |
| 253 | is[*types.Slice](info.TypeOf(call.Args[0]).Underlying()) { |
| 254 | limit = call.Args[0] |
| 255 | } |
| 256 | |
| 257 | // If the limit is a untyped constant of non-integer type, |
| 258 | // such as "const limit = 1e3", its effective type may |
| 259 | // differ between the two forms. |
| 260 | // In a for loop, it must be comparable with int i, |
| 261 | // for i := 0; i < limit; i++ {} |
| 262 | // but in a range loop it would become a float, |
| 263 | // for i := range limit {} |
| 264 | // which is a type error. We need to convert it to int |
| 265 | // in this case. |
| 266 | // |
| 267 | // Unfortunately go/types discards the untyped type |
| 268 | // (but see Untyped in golang/go#70638) so we must |
| 269 | // re-type check the expression to detect this case. |
| 270 | var beforeLimit, afterLimit string |
| 271 | if v := info.Types[limit].Value; v != nil { |
| 272 | tVar := info.TypeOf(init.Rhs[0]) |
| 273 | file := curFile.Node().(*ast.File) |
| 274 | // TODO(mkalil): use a types.Qualifier that respects the existing |
| 275 | // imports of this file that are visible (not shadowed) at the current position. |
| 276 | qual := typesinternal.FileQualifier(file, pass.Pkg) |
| 277 | beforeLimit, afterLimit = fmt.Sprintf("%s(", types.TypeString(tVar, qual)), ")" |
| 278 | info2 := &types.Info{Types: make(map[ast.Expr]types.TypeAndValue)} |
| 279 | if types.CheckExpr(pass.Fset, pass.Pkg, limit.Pos(), limit, info2) == nil { |
| 280 | tLimit := info2.TypeOf(limit) |
| 281 | // Eliminate conversion when safe. |
| 282 | // |
| 283 | // Redundant conversions are not only unsightly but may in some cases cause |
| 284 | // architecture-specific types (e.g. syscall.Timespec.Nsec) to be inserted |
| 285 | // into otherwise portable files. |
| 286 | // |
| 287 | // The operand must have an integer type (not, say, '1e6') |
| 288 | // even when assigning to an existing integer variable. |
| 289 | if isInteger(tLimit) { |
| 290 | // When declaring a new var from an untyped limit, |
| 291 | // the limit's default type is what matters. |
| 292 | if init.Tok != token.ASSIGN { |
| 293 | tLimit = types.Default(tLimit) |
| 294 | } |
| 295 | if types.AssignableTo(tLimit, tVar) { |
| 296 | beforeLimit, afterLimit = "", "" |
| 297 | } |
| 298 | } |
| 299 | } |
| 300 | } |
| 301 | |
| 302 | pass.Report(analysis.Diagnostic{ |
| 303 | Pos: init.Pos(), |
| 304 | End: loop.Post.End(), |
| 305 | Message: "for loop can be modernized using range over int", |
| 306 | SuggestedFixes: []analysis.SuggestedFix{{ |
| 307 | Message: fmt.Sprintf("Replace for loop with range %s", |
| 308 | astutil.Format(pass.Fset, limit)), |
| 309 | TextEdits: append(edits, []analysis.TextEdit{ |
| 310 | // for i := 0; i < limit; i++ {} |
| 311 | // ----- --- |
| 312 | // ------- |
| 313 | // for i := range limit {} |
| 314 | |
| 315 | // Delete init. |
| 316 | { |
| 317 | Pos: init.Rhs[0].Pos(), |
| 318 | End: limit.Pos(), |
| 319 | NewText: []byte("range "), |
| 320 | }, |
| 321 | // Add "int(" before limit, if needed. |
| 322 | { |
| 323 | Pos: limit.Pos(), |
| 324 | End: limit.Pos(), |
| 325 | NewText: []byte(beforeLimit), |
| 326 | }, |
| 327 | // Delete inc. |
| 328 | { |
| 329 | Pos: limit.End(), |
| 330 | End: loop.Post.End(), |
| 331 | }, |
| 332 | // Add ")" after limit, if needed. |
| 333 | { |
| 334 | Pos: limit.End(), |
| 335 | End: limit.End(), |
| 336 | NewText: []byte(afterLimit), |
| 337 | }, |
| 338 | }...), |
| 339 | }}, |
| 340 | }) |
| 341 | } |
| 342 | } |
| 343 | } |
| 344 | } |
| 345 | } |
| 346 | return nil, nil |
| 347 | } |
| 348 | |
| 349 | // isScalarLvalue reports whether the specified identifier is |
| 350 | // address-taken or appears on the left side of an assignment. |
| 351 | // |
| 352 | // This function is valid only for scalars (x = ...), |
| 353 | // not for aggregates (x.a[i] = ...) |
| 354 | func isScalarLvalue(info *types.Info, curId inspector.Cursor) bool { |
| 355 | // Unfortunately we can't simply use info.Types[e].Assignable() |
| 356 | // as it is always true for a variable even when that variable is |
| 357 | // used only as an r-value. So we must inspect enclosing syntax. |
| 358 | |
| 359 | cur := astutil.UnparenEnclosingCursor(curId) |
| 360 | |
| 361 | switch cur.ParentEdgeKind() { |
| 362 | case edge.AssignStmt_Lhs: |
| 363 | assign := cur.Parent().Node().(*ast.AssignStmt) |
| 364 | if assign.Tok != token.DEFINE { |
| 365 | return true // i = j or i += j |
| 366 | } |
| 367 | id := curId.Node().(*ast.Ident) |
| 368 | if v, ok := info.Defs[id]; ok && v.Pos() != id.Pos() { |
| 369 | return true // reassignment of i (i, j := 1, 2) |
| 370 | } |
| 371 | case edge.RangeStmt_Key: |
| 372 | rng := cur.Parent().Node().(*ast.RangeStmt) |
| 373 | if rng.Tok == token.ASSIGN { |
| 374 | return true // "for k, v = range x" is like an AssignStmt to k, v |
| 375 | } |
| 376 | case edge.IncDecStmt_X: |
| 377 | return true // i++, i-- |
| 378 | case edge.UnaryExpr_X: |
| 379 | if cur.Parent().Node().(*ast.UnaryExpr).Op == token.AND { |
| 380 | return true // &i |
| 381 | } |
| 382 | } |
| 383 | return false |
| 384 | } |