|
| 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 | + |
| 12 | + "golang.org/x/tools/go/analysis" |
| 13 | + "golang.org/x/tools/go/analysis/passes/inspect" |
| 14 | + "golang.org/x/tools/go/ast/inspector" |
| 15 | + "golang.org/x/tools/internal/analysisinternal" |
| 16 | + "golang.org/x/tools/internal/astutil/cursor" |
| 17 | + "golang.org/x/tools/internal/astutil/edge" |
| 18 | +) |
| 19 | + |
| 20 | +// rangeint offers a fix to replace a 3-clause 'for' loop: |
| 21 | +// |
| 22 | +// for i := 0; i < limit; i++ {} |
| 23 | +// |
| 24 | +// by a range loop with an integer operand: |
| 25 | +// |
| 26 | +// for i := range limit {} |
| 27 | +// |
| 28 | +// Variants: |
| 29 | +// - The ':=' may be replaced by '='. |
| 30 | +// - The fix may remove "i :=" if it would become unused. |
| 31 | +// |
| 32 | +// Restrictions: |
| 33 | +// - The variable i must not be assigned or address-taken within the |
| 34 | +// loop, because a "for range int" loop does not respect assignments |
| 35 | +// to the loop index. |
| 36 | +// - The limit must not be b.N, to avoid redundancy with bloop's fixes. |
| 37 | +// |
| 38 | +// Caveats: |
| 39 | +// - The fix will cause the limit expression to be evaluated exactly |
| 40 | +// once, instead of once per iteration. The limit may be a function call |
| 41 | +// (e.g. seq.Len()). The fix may change the cardinality of side effects. |
| 42 | +func rangeint(pass *analysis.Pass) { |
| 43 | + info := pass.TypesInfo |
| 44 | + |
| 45 | + inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) |
| 46 | + for curFile := range filesUsing(inspect, info, "go1.22") { |
| 47 | + nextLoop: |
| 48 | + for curLoop := range curFile.Preorder((*ast.ForStmt)(nil)) { |
| 49 | + loop := curLoop.Node().(*ast.ForStmt) |
| 50 | + if init, ok := loop.Init.(*ast.AssignStmt); ok && |
| 51 | + isSimpleAssign(init) && |
| 52 | + is[*ast.Ident](init.Lhs[0]) && |
| 53 | + isZeroLiteral(init.Rhs[0]) { |
| 54 | + // Have: for i = 0; ... (or i := 0) |
| 55 | + index := init.Lhs[0].(*ast.Ident) |
| 56 | + |
| 57 | + if compare, ok := loop.Cond.(*ast.BinaryExpr); ok && |
| 58 | + compare.Op == token.LSS && |
| 59 | + equalSyntax(compare.X, init.Lhs[0]) { |
| 60 | + // Have: for i = 0; i < limit; ... {} |
| 61 | + limit := compare.Y |
| 62 | + |
| 63 | + // Skip loops up to b.N in benchmarks; see [bloop]. |
| 64 | + if sel, ok := limit.(*ast.SelectorExpr); ok && |
| 65 | + sel.Sel.Name == "N" && |
| 66 | + analysisinternal.IsPointerToNamed(info.TypeOf(sel.X), "testing", "B") { |
| 67 | + continue // skip b.N |
| 68 | + } |
| 69 | + |
| 70 | + if inc, ok := loop.Post.(*ast.IncDecStmt); ok && |
| 71 | + inc.Tok == token.INC && |
| 72 | + equalSyntax(compare.X, inc.X) { |
| 73 | + // Have: for i = 0; i < limit; i++ {} |
| 74 | + |
| 75 | + // Find references to i within the loop body. |
| 76 | + v := info.Defs[index] |
| 77 | + used := false |
| 78 | + for curId := range curLoop.Child(loop.Body).Preorder((*ast.Ident)(nil)) { |
| 79 | + id := curId.Node().(*ast.Ident) |
| 80 | + if info.Uses[id] == v { |
| 81 | + used = true |
| 82 | + |
| 83 | + // Reject if any is an l-value (assigned or address-taken): |
| 84 | + // a "for range int" loop does not respect assignments to |
| 85 | + // the loop variable. |
| 86 | + if isScalarLvalue(curId) { |
| 87 | + continue nextLoop |
| 88 | + } |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + // If i is no longer used, delete "i := ". |
| 93 | + var edits []analysis.TextEdit |
| 94 | + if !used && init.Tok == token.DEFINE { |
| 95 | + edits = append(edits, analysis.TextEdit{ |
| 96 | + Pos: index.Pos(), |
| 97 | + End: init.Rhs[0].Pos(), |
| 98 | + }) |
| 99 | + } |
| 100 | + |
| 101 | + pass.Report(analysis.Diagnostic{ |
| 102 | + Pos: init.Pos(), |
| 103 | + End: inc.End(), |
| 104 | + Category: "rangeint", |
| 105 | + Message: "for loop can be modernized using range over int", |
| 106 | + SuggestedFixes: []analysis.SuggestedFix{{ |
| 107 | + Message: fmt.Sprintf("Replace for loop with range %s", |
| 108 | + analysisinternal.Format(pass.Fset, limit)), |
| 109 | + TextEdits: append(edits, []analysis.TextEdit{ |
| 110 | + // for i := 0; i < limit; i++ {} |
| 111 | + // ----- --- |
| 112 | + // ------- |
| 113 | + // for i := range limit {} |
| 114 | + { |
| 115 | + Pos: init.Rhs[0].Pos(), |
| 116 | + End: limit.Pos(), |
| 117 | + NewText: []byte("range "), |
| 118 | + }, |
| 119 | + { |
| 120 | + Pos: limit.End(), |
| 121 | + End: inc.End(), |
| 122 | + }, |
| 123 | + }...), |
| 124 | + }}, |
| 125 | + }) |
| 126 | + } |
| 127 | + } |
| 128 | + } |
| 129 | + } |
| 130 | + } |
| 131 | +} |
| 132 | + |
| 133 | +// isScalarLvalue reports whether the specified identifier is |
| 134 | +// address-taken or appears on the left side of an assignment. |
| 135 | +// |
| 136 | +// This function is valid only for scalars (x = ...), |
| 137 | +// not for aggregates (x.a[i] = ...) |
| 138 | +func isScalarLvalue(curId cursor.Cursor) bool { |
| 139 | + // Unfortunately we can't simply use info.Types[e].Assignable() |
| 140 | + // as it is always true for a variable even when that variable is |
| 141 | + // used only as an r-value. So we must inspect enclosing syntax. |
| 142 | + |
| 143 | + cur := curId |
| 144 | + |
| 145 | + // Strip enclosing parens. |
| 146 | + ek, _ := cur.Edge() |
| 147 | + for ek == edge.ParenExpr_X { |
| 148 | + cur = cur.Parent() |
| 149 | + ek, _ = cur.Edge() |
| 150 | + } |
| 151 | + |
| 152 | + switch ek { |
| 153 | + case edge.AssignStmt_Lhs: |
| 154 | + return true // i = j |
| 155 | + case edge.IncDecStmt_X: |
| 156 | + return true // i++, i-- |
| 157 | + case edge.UnaryExpr_X: |
| 158 | + if cur.Parent().Node().(*ast.UnaryExpr).Op == token.AND { |
| 159 | + return true // &i |
| 160 | + } |
| 161 | + } |
| 162 | + return false |
| 163 | +} |
0 commit comments