forked from kyoh86/looppointer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlooppointer.go
228 lines (195 loc) · 5.39 KB
/
looppointer.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
222
223
224
225
226
227
228
package looppointer
import (
"fmt"
"go/ast"
"go/token"
"github.com/kyoh86/nolint"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/inspect"
"golang.org/x/tools/go/ast/inspector"
)
var Analyzer = &analysis.Analyzer{
Name: "looppointer",
Doc: "checks for pointers to enclosing loop variables",
Run: run,
RunDespiteErrors: true,
Requires: []*analysis.Analyzer{inspect.Analyzer, nolint.Analyzer},
// ResultType reflect.Type
// FactTypes []Fact
}
func init() {
// Analyzer.Flags.StringVar(&v, "name", "default", "description")
}
type messagesFormats struct {
dMsgFormat string
fMsgFormat string
}
const (
loopPointer = "looppointer"
funcReference = "func-reference"
)
var detectionTypeToMessageFormats = map[string]messagesFormats{
loopPointer: {
"taking a pointer for the loop variable %s",
"loop variable %s should be pinned",
},
funcReference: {
"using loop variable in function literal %s",
"loop variable %s should be pinned",
},
}
func run(pass *analysis.Pass) (interface{}, error) {
inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
noLinter := pass.ResultOf[nolint.Analyzer].(*nolint.NoLinter)
search := &Searcher{
Stats: map[token.Pos]struct{}{},
}
nodeFilter := []ast.Node{
(*ast.RangeStmt)(nil),
(*ast.ForStmt)(nil),
(*ast.UnaryExpr)(nil),
(*ast.Ident)(nil),
}
inspect.WithStack(nodeFilter, func(n ast.Node, push bool, stack []ast.Node) bool {
issueType, id, insert, digg := search.Check(n, stack)
if id != nil && !noLinter.IgnoreNode(id, "looppointer") {
dMsg := fmt.Sprintf(detectionTypeToMessageFormats[issueType].dMsgFormat, id.Name)
fMsg := fmt.Sprintf(detectionTypeToMessageFormats[issueType].fMsgFormat, id.Name)
var suggest []analysis.SuggestedFix
if insert != token.NoPos {
suggest = []analysis.SuggestedFix{{
Message: fMsg,
TextEdits: []analysis.TextEdit{{
Pos: insert,
End: insert,
NewText: []byte(fmt.Sprintf("%[1]s := %[1]s\n", id.Name)),
}},
}}
}
pass.Report(analysis.Diagnostic{
Pos: id.Pos(),
End: id.End(),
Message: dMsg,
Category: "looppointer",
SuggestedFixes: suggest,
})
}
return digg
})
return nil, nil
}
type Searcher struct {
// statement variables
Stats map[token.Pos]struct{}
}
func (s *Searcher) Check(n ast.Node, stack []ast.Node) (string, *ast.Ident, token.Pos, bool) {
switch typed := n.(type) {
case *ast.RangeStmt:
s.parseRangeStmt(typed)
case *ast.ForStmt:
s.parseForStmt(typed)
case *ast.UnaryExpr:
return s.checkUnaryExpr(typed, stack)
case *ast.Ident:
return s.checkIdent(typed, stack)
}
return "", nil, token.NoPos, true
}
func (s *Searcher) parseRangeStmt(n *ast.RangeStmt) {
s.addStat(n.Key)
s.addStat(n.Value)
}
func (s *Searcher) parseForStmt(n *ast.ForStmt) {
switch post := n.Post.(type) {
case *ast.AssignStmt:
// e.g. for p = head; p != nil; p = p.next
for _, lhs := range post.Lhs {
s.addStat(lhs)
}
case *ast.IncDecStmt:
// e.g. for i := 0; i < n; i++
s.addStat(post.X)
}
}
func (s *Searcher) addStat(expr ast.Expr) {
if id, ok := expr.(*ast.Ident); ok {
s.Stats[id.Pos()] = struct{}{}
}
}
func insertionPosition(block *ast.BlockStmt) token.Pos {
if len(block.List) > 0 {
return block.List[0].Pos()
}
return token.NoPos
}
func (s *Searcher) innermostLoop(stack []ast.Node) (ast.Node, token.Pos) {
for i := len(stack) - 1; i >= 0; i-- {
switch typed := stack[i].(type) {
case *ast.RangeStmt:
return typed, insertionPosition(typed.Body)
case *ast.ForStmt:
return typed, insertionPosition(typed.Body)
}
}
return nil, token.NoPos
}
func (s *Searcher) checkIdent(n *ast.Ident, stack []ast.Node) (string, *ast.Ident, token.Pos, bool) {
// Get identity of the referred item
id := getIdentity(n)
if id == nil || id.Obj == nil {
return "", nil, token.NoPos, true
}
if _, isStat := s.Stats[id.Obj.Pos()]; isStat {
// Find any function literals in the stack above
for i := len(stack) - 1; i >= 0; i-- {
stackNode := stack[i]
if fl, ok := stackNode.(*ast.FuncLit); ok {
// If this is a usage within a function literal, but the variable was declared in this function literal
// then there's no issue.
if n.Obj.Pos() > fl.Pos() && n.Obj.Pos() < fl.End() {
return "", nil, n.Pos(), true
}
return funcReference, n, n.Pos(), false
}
}
}
return "", nil, n.Pos(), true
}
func (s *Searcher) checkUnaryExpr(n *ast.UnaryExpr, stack []ast.Node) (string, *ast.Ident, token.Pos, bool) {
loop, insert := s.innermostLoop(stack)
if loop == nil {
return "", nil, token.NoPos, true
}
if n.Op != token.AND {
return "", nil, token.NoPos, true
}
// Get identity of the referred item
id := getIdentity(n.X)
if id == nil || id.Obj == nil {
return "", nil, token.NoPos, true
}
// If the identity is not the loop statement variable,
// it will not be reported.
if _, isStat := s.Stats[id.Obj.Pos()]; !isStat {
return "", nil, token.NoPos, true
}
return loopPointer, id, insert, false
}
// Get variable identity
func getIdentity(expr ast.Expr) *ast.Ident {
switch typed := expr.(type) {
case *ast.SelectorExpr:
// Get parent identity
// i.e.
// `a` of the `a.b`.
// `a.b` of the `a.b.c`.
return getIdentity(typed.X)
case *ast.Ident:
// Get simple identity; i.e. `a` of the `a`.
if typed.Obj == nil {
return nil
}
return typed
}
return nil
}