-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdll.go
99 lines (84 loc) · 1.66 KB
/
dll.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
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"os"
)
type report struct {
sourceName string
lineNumber int
}
func (r *report) String() string {
return fmt.Sprintf("%s:%d found defer statement in for loop", r.sourceName, r.lineNumber)
}
type visitFunc func(ast.Node) ast.Visitor
func (vf visitFunc) Visit(node ast.Node) ast.Visitor {
return vf(node)
}
func gather(source string, asFile bool) ([]*report, error) {
fset := token.NewFileSet()
var (
f *ast.File
err error
)
if asFile {
f, err = parser.ParseFile(fset, source, nil, 0)
} else {
f, err = parser.ParseFile(fset, "", source, 0)
}
if err != nil {
return nil, err
}
var (
reports []*report
findLoop, findDefer ast.Visitor
)
findLoop = visitFunc(func(n ast.Node) ast.Visitor {
if n == nil {
return nil
}
switch n.(type) {
case *ast.RangeStmt, *ast.ForStmt:
return findDefer
default:
return findLoop
}
})
findDefer = visitFunc(func(n ast.Node) ast.Visitor {
if n == nil {
return nil
}
switch n := n.(type) {
case *ast.DeferStmt:
source := fset.File(f.Pos())
reports = append(reports, &report{
sourceName: source.Name(),
lineNumber: source.Line(n.Pos()),
})
return findDefer
case *ast.FuncLit:
return findLoop
default:
return findDefer
}
})
ast.Walk(findLoop, f)
return reports, nil
}
func main() {
if len(os.Args) < 2 {
fmt.Fprintln(os.Stderr, "no source files supplied")
}
for _, source := range os.Args[1:] {
r, err := gather(source, true)
if err != nil {
fmt.Fprintf(os.Stderr, "error parsing %s: %s\n", source, err)
continue
}
for _, rep := range r {
fmt.Println(rep)
}
}
}