/
gofor.go
221 lines (190 loc) · 4.95 KB
/
gofor.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
// gofor analyzes the types of for loops encountered in Go code.
// It is geared towards detecting counting loops -- loops of the form
// for i := min; i < max; i += stride
// and its categorizations are mostly steps on the way to ruling out
// non-counting loops and then detecting interesting types of counting
// loops -- special values for min and stride (0 and 1 respectively)
// and literal vs non-literal min/max/stride.
//
// It is intended to be used in conjunction with sort and uniq.
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"os"
"strings"
"github.com/josharian/gofor/github.com/kr/fs"
)
type visitor struct{}
func (v visitor) Visit(node ast.Node) (w ast.Visitor) {
if node == nil {
return v
}
if _, ok := node.(*ast.RangeStmt); ok {
fmt.Println("range")
return v
}
// for _ := range _ {
stmt, ok := node.(*ast.ForStmt)
if !ok {
return v
}
// for {
if stmt.Init == nil && stmt.Cond == nil && stmt.Post == nil {
fmt.Println("bare for")
return v
}
// for scan.Scan() {
if stmt.Init == nil && stmt.Post == nil {
fmt.Println("cond only")
return v
}
if stmt.Init == nil {
fmt.Println("missing init")
return v
}
if stmt.Post == nil {
fmt.Println("missing post")
return v
}
// condition not a < b or a <= b
binExpr, ok := stmt.Cond.(*ast.BinaryExpr)
if !ok || (binExpr.Op != token.LSS && binExpr.Op != token.LEQ) {
fmt.Println("cond not < or <=")
return v
}
// cond lhs not identifier
condLhs, ok := binExpr.X.(*ast.Ident)
if !ok {
fmt.Println("cond lhs not identifier")
return v
}
initAssign, ok := stmt.Init.(*ast.AssignStmt)
// init not i := n
if !ok {
fmt.Println("init not i := n")
return v
}
// init has multiple values on lhs/rhs
if len(initAssign.Lhs) != 1 || len(initAssign.Rhs) != 1 {
fmt.Println("init multiple values")
return v
}
initLhs, ok := initAssign.Lhs[0].(*ast.Ident)
// init lhs not an identifier?!
if !ok {
fmt.Println("init lhs not identifier")
return v
}
if initLhs.Name != condLhs.Name {
fmt.Println("init lhs != cond lhs")
return v
}
postAssign, postAssignOk := stmt.Post.(*ast.AssignStmt)
postIncDec, postIncDecOk := stmt.Post.(*ast.IncDecStmt)
if !postAssignOk && !postIncDecOk {
fmt.Println("post not assign or inc/dec")
return v
}
if postAssignOk {
if len(postAssign.Lhs) != 1 || len(postAssign.Rhs) != 1 {
fmt.Println("post assign multiple values")
return v
}
postAssignLhs, ok := postAssign.Lhs[0].(*ast.Ident)
if !ok {
fmt.Println("post assign lhs not ident")
return v
}
if postAssignLhs.Name != initLhs.Name {
fmt.Println("init lhs != post assign lhs")
return v
}
if postAssign.Tok != token.ADD_ASSIGN && postAssign.Tok != token.SUB_ASSIGN {
fmt.Println("post assign not += or -= (but might be i = i - 1, oh well)")
return v
}
}
if postIncDecOk {
postIncDecLhs, ok := postIncDec.X.(*ast.Ident)
if !ok {
fmt.Println("post incdec lhs not ident")
return v
}
if postIncDecLhs.Name != initLhs.Name {
fmt.Println("init lhs != post incdec lhs")
return v
}
}
// Ok, at this point we know we have a statement of one of these three forms:
// for i := ?; i <[=] ?; i += [?] {
// for i := ?; i <[=] ?; i++ {
// for i := ?; i <[=] ?; i-- {
// For each of the question marks here -- min, max, stride -- there are multiple
// cases we might want to distinguish. Figure out which it is.
var min string
if initRhsLit, ok := initAssign.Rhs[0].(*ast.BasicLit); ok {
if initRhsLit.Value == "0" {
min = "0"
} else {
min = "literal"
}
} else {
min = "non-literal"
}
var max string
if _, ok := binExpr.Y.(*ast.BasicLit); ok {
max = "literal"
} else {
max = "non-literal"
}
var stride string
var postAssignRhsLit *ast.BasicLit
var postAssignRhsLitOk bool
if postAssignOk {
postAssignRhsLit, postAssignRhsLitOk = postAssign.Rhs[0].(*ast.BasicLit)
}
switch {
case postIncDecOk && postIncDec.Tok == token.INC:
stride = "1"
case postIncDecOk: // must be DEC
stride = "literal" // -1
case !postAssignRhsLitOk:
stride = "non-literal"
case postAssignRhsLit.Value == "1" && postAssign.Tok == token.ADD_ASSIGN:
stride = "1"
// ignore possibility of code doing i -= -1. That's dumb.
default:
stride = "literal"
}
fmt.Printf("counting loop min %s, max %s, stride %s\n", min, max, stride)
return v
}
func main() {
if len(os.Args) < 2 {
fmt.Fprintf(os.Stderr, "usage: gofor <dir> | sort | uniq -c | sort -n -r")
os.Exit(1)
}
walker := fs.Walk(os.Args[1])
var v visitor
for walker.Step() {
if err := walker.Err(); err != nil {
fmt.Printf("Error during filesystem walk: %v\n", err)
continue
}
if walker.Stat().IsDir() || !strings.HasSuffix(walker.Path(), ".go") {
continue
}
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, walker.Path(), nil, 0)
// fmt.Println(walker.Path())
if err != nil {
// don't print err here; it is too chatty, due to (un?)surprising
// amounts of broken code in the wild
continue
}
ast.Walk(v, f)
}
}