/
closeafterusagecheck.go
199 lines (167 loc) · 5.12 KB
/
closeafterusagecheck.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
package closeafterusagecheck
import (
"flag"
"go/ast"
"slices"
"strings"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/inspect"
"golang.org/x/tools/go/ast/inspector"
)
func sliceMap(s []string, f func(value string) string) []string {
mapped := make([]string, 0, len(s))
for _, value := range s {
mapped = append(mapped, f(value))
}
return mapped
}
type nodeAndStack struct {
node ast.Node
stack []ast.Node
}
func Analyzer() *analysis.Analyzer {
flagSet := flag.NewFlagSet("closeafterusagecheck", flag.ExitOnError)
mustBeClosedTypes := flagSet.String(
"must-be-closed-after-usage-types",
"",
`full paths of the types for whom Close() must be immediately closed after usage`,
)
skip := flagSet.String("skip-pkg", "", "package(s) to skip for linting")
return &analysis.Analyzer{
Name: "closeafterusagecheck",
Doc: "reports any variables of the specified types that are not Close()-ed immediately after usage",
Run: func(pass *analysis.Pass) (any, error) {
// Check for a skipped package.
if len(*skip) > 0 {
skipped := sliceMap(strings.Split(*skip, ","), strings.TrimSpace)
for _, s := range skipped {
if strings.Contains(pass.Pkg.Path(), s) {
return nil, nil
}
}
}
entries := strings.Split(*mustBeClosedTypes, ";")
typePaths := map[string]struct{}{}
for _, entry := range entries {
if len(entry) == 0 {
continue
}
typePaths[entry] = struct{}{}
}
inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
nodeFilter := []ast.Node{
(*ast.ExprStmt)(nil),
(*ast.AssignStmt)(nil),
(*ast.CallExpr)(nil),
(*ast.Ident)(nil),
(*ast.DeferStmt)(nil),
}
varsToWatch := map[string]nodeAndStack{}
varsLastUsed := map[string]nodeAndStack{}
varsClosed := map[string]nodeAndStack{}
inspect.WithStack(nodeFilter, func(n ast.Node, push bool, stack []ast.Node) bool {
switch s := n.(type) {
case *ast.DeferStmt:
// Skip so we don't treat this as a valid immediately Close.
return false
case *ast.CallExpr:
foundType := pass.TypesInfo.TypeOf(s.Fun)
if foundType == nil {
return false
}
if selector, ok := s.Fun.(*ast.SelectorExpr); ok {
if selector.Sel.Name == "Close" {
if ident, ok := selector.X.(*ast.Ident); ok {
foundType := pass.TypesInfo.TypeOf(selector.X)
if foundType == nil {
return false
}
varTypeString := foundType.String()
if _, ok := typePaths[varTypeString]; ok {
varName := fullName(ident, stack)
varsClosed[varName] = nodeAndStack{n, slices.Clone(stack)}
return false
}
}
}
}
return true
case *ast.Ident:
varName := fullName(s, stack)
if _, ok := varsToWatch[varName]; ok {
varsLastUsed[varName] = nodeAndStack{s, slices.Clone(stack)}
}
case *ast.AssignStmt:
for _, expr := range s.Lhs {
foundType := pass.TypesInfo.TypeOf(expr)
if foundType == nil {
continue
}
varTypeString := foundType.String()
if _, ok := typePaths[varTypeString]; ok {
varName := fullName(expr.(*ast.Ident), stack)
varsToWatch[varName] = nodeAndStack{expr, slices.Clone(stack)}
}
}
}
return true
})
for varName, nas := range varsToWatch {
closed, ok := varsClosed[varName]
if !ok {
pass.Reportf(nas.node.Pos(), "In package %s: variable %s is missing required non-defer-ed Close() call after usage", pass.Pkg.Path(), varName)
continue
}
lastUsed, ok := varsLastUsed[varName]
if !ok {
lastUsed = nas
}
if !isStatementRightAfter(lastUsed, closed) {
pass.Reportf(lastUsed.node.End(), "In package %s: expected variable %s to have a call to Close after here", pass.Pkg.Path(), varName)
continue
}
}
return nil, nil
},
Requires: []*analysis.Analyzer{inspect.Analyzer},
Flags: *flagSet,
}
}
func fullName(ident *ast.Ident, stack []ast.Node) string {
for _, node := range stack {
if fun, ok := node.(*ast.FuncDecl); ok {
return fun.Name.Name + "." + ident.Name
}
}
return ident.Name
}
func isStatementRightAfter(first nodeAndStack, second nodeAndStack) bool {
containingStatement, firstIndex, secondIndex := findSharedContainingStatement(
append(slices.Clone(first.stack), first.node),
append(slices.Clone(second.stack), second.node),
)
if containingStatement == nil {
return false
}
return secondIndex == firstIndex+1
}
func findSharedContainingStatement(first []ast.Node, second []ast.Node) (ast.Node, int, int) {
for i := 0; i < min(len(first), len(second)); i++ {
if i > 0 && first[i] != second[i] {
for j := i - 1; j >= 0; j-- {
if block, ok := first[j].(*ast.BlockStmt); ok {
return block, stIndex(block.List, first[j+1]), stIndex(block.List, second[j+1])
}
if cse, ok := first[j].(*ast.CaseClause); ok {
return cse, stIndex(cse.Body, first[j+1]), stIndex(cse.Body, second[j+1])
}
}
}
}
return nil, -1, -1
}
func stIndex(statements []ast.Stmt, node ast.Node) int {
return slices.IndexFunc(statements, func(current ast.Stmt) bool {
return current == node
})
}