-
Notifications
You must be signed in to change notification settings - Fork 2
/
tickeryzer.go
197 lines (175 loc) · 4.91 KB
/
tickeryzer.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
// Copyright 2021 Orijtech, Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tickeryzer
import (
"go/ast"
"go/types"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/ctrlflow"
"golang.org/x/tools/go/analysis/passes/inspect"
"golang.org/x/tools/go/ast/inspector"
)
const Doc = `check that (*time.Ticker).Stop is called
The (*time.Ticker).Stop method must be called to release
associated resources hold by the Ticker.
`
var Analyzer = &analysis.Analyzer{
Name: "tickeryzer",
Doc: Doc,
Run: run,
Requires: []*analysis.Analyzer{
inspect.Analyzer,
ctrlflow.Analyzer,
},
}
func run(pass *analysis.Pass) (interface{}, error) {
inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
// Fast path: if the package doesn't import time,
// skip the traversal.
if !imports(pass.Pkg, "time") {
return nil, nil
}
nodeFilter := []ast.Node{
(*ast.CallExpr)(nil),
}
inspect.WithStack(nodeFilter, func(n ast.Node, push bool, stack []ast.Node) bool {
if !push {
return true
}
// Returning from main.main terminates the process, so we don't have to check.
if fd, ok := stack[1].(*ast.FuncDecl); ok && fd.Name.Name == "main" && pass.Pkg.Name() == "main" {
return false
}
call := n.(*ast.CallExpr)
if !isTimeNewTicker(pass.TypesInfo, call) {
return true // the function call is not related to this check.
}
// Find the innermost containing block, and get the list
// of statements starting with the one containing call.
stmts := restOfBlock(stack)
if len(stmts) == 0 {
return true
}
asg, ok := stmts[0].(*ast.AssignStmt)
if !ok {
return true // the first statement is not assignment.
}
ticker := rootIdent(asg.Lhs[0])
if ticker == nil {
return true // could not find the *time.Ticker in the assignment.
}
if hasTickerStopCall(pass, ticker, stmts[1:]) {
return true
}
pass.ReportRangef(ticker, "missing %s.Stop() call", ticker.Name)
return true
})
return nil, nil
}
func hasTickerStopCall(pass *analysis.Pass, ticker *ast.Ident, stmts []ast.Stmt) bool {
for _, stmt := range stmts {
var root *ast.Ident
switch stmt := stmt.(type) {
case *ast.DeferStmt:
root = rootIdent(stmt.Call.Fun)
case *ast.ExprStmt:
root = rootIdent(stmt.X)
case *ast.ForStmt:
if hasTickerStopCall(pass, ticker, stmt.Body.List) {
return true
}
case *ast.SelectStmt:
if hasTickerStopCall(pass, ticker, stmt.Body.List) {
return true
}
case *ast.CommClause:
if hasTickerStopCall(pass, ticker, stmt.Body) {
return true
}
case *ast.CaseClause:
if hasTickerStopCall(pass, ticker, stmt.Body) {
return true
}
}
if root == nil {
continue
}
if root.Obj == ticker.Obj {
return true
}
}
return false
}
func isTimeNewTicker(info *types.Info, expr *ast.CallExpr) bool {
fun, _ := expr.Fun.(*ast.SelectorExpr)
sig, _ := info.Types[fun].Type.(*types.Signature)
if sig == nil {
return false
}
res := sig.Results()
if res.Len() != 1 {
return false // the function called does not return one value.
}
if ptr, ok := res.At(0).Type().(*types.Pointer); !ok || !isNamedType(ptr.Elem(), "time", "Ticker") {
return false // the first return type is not *time.Ticker.
}
return true
}
// restOfBlock, given a traversal stack, finds the innermost containing
// block and returns the suffix of its statements starting with the
// current node (the last element of stack).
func restOfBlock(stack []ast.Node) []ast.Stmt {
for i := len(stack) - 1; i >= 0; i-- {
if b, ok := stack[i].(*ast.BlockStmt); ok {
for j, v := range b.List {
if v == stack[i+1] {
return b.List[j:]
}
}
break
}
}
return nil
}
// rootIdent finds the root identifier x in a chain of selections x.y.z, or nil if not found.
func rootIdent(n ast.Node) *ast.Ident {
switch n := n.(type) {
case *ast.SelectorExpr:
return rootIdent(n.X)
case *ast.CallExpr:
return rootIdent(n.Fun)
case *ast.Ident:
return n
default:
return nil
}
}
// isNamedType reports whether t is the named type path.name.
func isNamedType(t types.Type, path, name string) bool {
n, ok := t.(*types.Named)
if !ok {
return false
}
obj := n.Obj()
return obj.Name() == name && obj.Pkg() != nil && obj.Pkg().Path() == path
}
// Imports returns true if path is imported by pkg.
func imports(pkg *types.Package, path string) bool {
for _, imp := range pkg.Imports() {
if imp.Path() == path {
return true
}
}
return false
}