|
| 1 | +// Copyright 2024 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/inspector" |
| 16 | + "golang.org/x/tools/go/types/typeutil" |
| 17 | + "golang.org/x/tools/internal/astutil/cursor" |
| 18 | + "golang.org/x/tools/internal/typesinternal" |
| 19 | + "golang.org/x/tools/internal/versions" |
| 20 | +) |
| 21 | + |
| 22 | +// bloop updates benchmarks that use "for range b.N", replacing it |
| 23 | +// with go1.24's b.Loop() and eliminating any preceding |
| 24 | +// b.{Start,Stop,Reset}Timer calls. |
| 25 | +// |
| 26 | +// Variants: |
| 27 | +// |
| 28 | +// for i := 0; i < b.N; i++ {} => for b.Loop() {} |
| 29 | +// for range b.N {} |
| 30 | +func bloop(pass *analysis.Pass) { |
| 31 | + if !_imports(pass.Pkg, "testing") { |
| 32 | + return |
| 33 | + } |
| 34 | + |
| 35 | + info := pass.TypesInfo |
| 36 | + |
| 37 | + // edits computes the text edits for a matched for/range loop |
| 38 | + // at the specified cursor. b is the *testing.B value, and |
| 39 | + // (start, end) is the portion using b.N to delete. |
| 40 | + edits := func(cur cursor.Cursor, b ast.Expr, start, end token.Pos) (edits []analysis.TextEdit) { |
| 41 | + // Within the same function, delete all calls to |
| 42 | + // b.{Start,Stop,Timer} that precede the loop. |
| 43 | + filter := []ast.Node{(*ast.ExprStmt)(nil), (*ast.FuncLit)(nil)} |
| 44 | + fn, _ := enclosingFunc(cur) |
| 45 | + fn.Inspect(filter, func(cur cursor.Cursor, push bool) (descend bool) { |
| 46 | + if push { |
| 47 | + node := cur.Node() |
| 48 | + if is[*ast.FuncLit](node) { |
| 49 | + return false // don't descend into FuncLits (e.g. sub-benchmarks) |
| 50 | + } |
| 51 | + stmt := node.(*ast.ExprStmt) |
| 52 | + if stmt.Pos() > start { |
| 53 | + return false // not preceding: stop |
| 54 | + } |
| 55 | + if call, ok := stmt.X.(*ast.CallExpr); ok { |
| 56 | + fn := typeutil.StaticCallee(info, call) |
| 57 | + if fn != nil && |
| 58 | + (isMethod(fn, "testing", "B", "StopTimer") || |
| 59 | + isMethod(fn, "testing", "B", "StartTimer") || |
| 60 | + isMethod(fn, "testing", "B", "ResetTimer")) { |
| 61 | + |
| 62 | + // Delete call statement. |
| 63 | + // TODO(adonovan): delete following newline, or |
| 64 | + // up to start of next stmt? (May delete a comment.) |
| 65 | + edits = append(edits, analysis.TextEdit{ |
| 66 | + Pos: stmt.Pos(), |
| 67 | + End: stmt.End(), |
| 68 | + }) |
| 69 | + } |
| 70 | + } |
| 71 | + } |
| 72 | + return true |
| 73 | + }) |
| 74 | + |
| 75 | + // Replace ...b.N... with b.Loop(). |
| 76 | + return append(edits, analysis.TextEdit{ |
| 77 | + Pos: start, |
| 78 | + End: end, |
| 79 | + NewText: fmt.Appendf(nil, "%s.Loop()", formatNode(pass.Fset, b)), |
| 80 | + }) |
| 81 | + } |
| 82 | + |
| 83 | + // Find all for/range statements. |
| 84 | + inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) |
| 85 | + filter := []ast.Node{ |
| 86 | + (*ast.File)(nil), |
| 87 | + (*ast.ForStmt)(nil), |
| 88 | + (*ast.RangeStmt)(nil), |
| 89 | + } |
| 90 | + cursor.Root(inspect).Inspect(filter, func(cur cursor.Cursor, push bool) (descend bool) { |
| 91 | + if push { |
| 92 | + switch n := cur.Node().(type) { |
| 93 | + case *ast.File: |
| 94 | + if versions.Before(info.FileVersions[n], "go1.24") { |
| 95 | + return false |
| 96 | + } |
| 97 | + |
| 98 | + case *ast.ForStmt: |
| 99 | + // for _; i < b.N; _ {} |
| 100 | + if cmp, ok := n.Cond.(*ast.BinaryExpr); ok && cmp.Op == token.LSS { |
| 101 | + if sel, ok := cmp.Y.(*ast.SelectorExpr); ok && |
| 102 | + sel.Sel.Name == "N" && |
| 103 | + isPtrToNamed(info.TypeOf(sel.X), "testing", "B") { |
| 104 | + |
| 105 | + delStart, delEnd := n.Cond.Pos(), n.Cond.End() |
| 106 | + |
| 107 | + // Eliminate variable i if no longer needed: |
| 108 | + // for i := 0; i < b.N; i++ { |
| 109 | + // ...no references to i... |
| 110 | + // } |
| 111 | + body, _ := cur.LastChild() |
| 112 | + if assign, ok := n.Init.(*ast.AssignStmt); ok && |
| 113 | + assign.Tok == token.DEFINE && |
| 114 | + len(assign.Rhs) == 1 && |
| 115 | + isZeroLiteral(assign.Rhs[0]) && |
| 116 | + is[*ast.IncDecStmt](n.Post) && |
| 117 | + n.Post.(*ast.IncDecStmt).Tok == token.INC && |
| 118 | + equalSyntax(n.Post.(*ast.IncDecStmt).X, assign.Lhs[0]) && |
| 119 | + !uses(info, body, info.Defs[assign.Lhs[0].(*ast.Ident)]) { |
| 120 | + |
| 121 | + delStart, delEnd = n.Init.Pos(), n.Post.End() |
| 122 | + } |
| 123 | + |
| 124 | + pass.Report(analysis.Diagnostic{ |
| 125 | + // Highlight "i < b.N". |
| 126 | + Pos: n.Cond.Pos(), |
| 127 | + End: n.Cond.End(), |
| 128 | + Category: "bloop", |
| 129 | + Message: "b.N can be modernized using b.Loop()", |
| 130 | + SuggestedFixes: []analysis.SuggestedFix{{ |
| 131 | + Message: "Replace b.N with b.Loop()", |
| 132 | + TextEdits: edits(cur, sel.X, delStart, delEnd), |
| 133 | + }}, |
| 134 | + }) |
| 135 | + } |
| 136 | + } |
| 137 | + |
| 138 | + case *ast.RangeStmt: |
| 139 | + // for range b.N {} -> for b.Loop() {} |
| 140 | + // |
| 141 | + // TODO(adonovan): handle "for i := range b.N". |
| 142 | + if sel, ok := n.X.(*ast.SelectorExpr); ok && |
| 143 | + n.Key == nil && |
| 144 | + n.Value == nil && |
| 145 | + sel.Sel.Name == "N" && |
| 146 | + isPtrToNamed(info.TypeOf(sel.X), "testing", "B") { |
| 147 | + |
| 148 | + pass.Report(analysis.Diagnostic{ |
| 149 | + // Highlight "range b.N". |
| 150 | + Pos: n.Range, |
| 151 | + End: n.X.End(), |
| 152 | + Category: "bloop", |
| 153 | + Message: "b.N can be modernized using b.Loop()", |
| 154 | + SuggestedFixes: []analysis.SuggestedFix{{ |
| 155 | + Message: "Replace b.N with b.Loop()", |
| 156 | + TextEdits: edits(cur, sel.X, n.Range, n.X.End()), |
| 157 | + }}, |
| 158 | + }) |
| 159 | + } |
| 160 | + } |
| 161 | + } |
| 162 | + return true |
| 163 | + }) |
| 164 | +} |
| 165 | + |
| 166 | +// isPtrToNamed reports whether t is type "*pkgpath.Name". |
| 167 | +func isPtrToNamed(t types.Type, pkgpath, name string) bool { |
| 168 | + if ptr, ok := t.(*types.Pointer); ok { |
| 169 | + named, ok := ptr.Elem().(*types.Named) |
| 170 | + return ok && |
| 171 | + named.Obj().Name() == name && |
| 172 | + named.Obj().Pkg().Path() == pkgpath |
| 173 | + } |
| 174 | + return false |
| 175 | +} |
| 176 | + |
| 177 | +// uses reports whether the subtree cur contains a use of obj. |
| 178 | +func uses(info *types.Info, cur cursor.Cursor, obj types.Object) bool { |
| 179 | + for curId := range cur.Preorder((*ast.Ident)(nil)) { |
| 180 | + if info.Uses[curId.Node().(*ast.Ident)] == obj { |
| 181 | + return true |
| 182 | + } |
| 183 | + } |
| 184 | + return false |
| 185 | +} |
| 186 | + |
| 187 | +// isMethod reports whether fn is pkgpath.(T).Name. |
| 188 | +func isMethod(fn *types.Func, pkgpath, T, name string) bool { |
| 189 | + if recv := fn.Signature().Recv(); recv != nil { |
| 190 | + _, recvName := typesinternal.ReceiverNamed(recv) |
| 191 | + return recvName != nil && |
| 192 | + isPackageLevel(recvName.Obj(), pkgpath, T) && |
| 193 | + fn.Name() == name |
| 194 | + } |
| 195 | + return false |
| 196 | +} |
| 197 | + |
| 198 | +// enclosingFunc returns the cursor for the innermost Func{Decl,Lit} |
| 199 | +// that encloses (or is) c, if any. |
| 200 | +// |
| 201 | +// TODO(adonovan): consider adding: |
| 202 | +// |
| 203 | +// func (Cursor) AnyEnclosing(filter ...ast.Node) (Cursor bool) |
| 204 | +// func (Cursor) Enclosing[N ast.Node]() (Cursor, bool) |
| 205 | +// |
| 206 | +// See comments at [cursor.Cursor.Stack]. |
| 207 | +func enclosingFunc(c cursor.Cursor) (cursor.Cursor, bool) { |
| 208 | + for { |
| 209 | + switch c.Node().(type) { |
| 210 | + case *ast.FuncLit, *ast.FuncDecl: |
| 211 | + return c, true |
| 212 | + case nil: |
| 213 | + return cursor.Cursor{}, false |
| 214 | + } |
| 215 | + c = c.Parent() |
| 216 | + } |
| 217 | +} |
0 commit comments