-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanalyzer.go
More file actions
51 lines (43 loc) · 1.07 KB
/
Copy pathanalyzer.go
File metadata and controls
51 lines (43 loc) · 1.07 KB
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
package analyzer
import (
"go/ast"
"go/types"
"golang.org/x/tools/go/analysis"
)
var Analyzer = &analysis.Analyzer{
Name: "nilinterface",
Doc: "check for nil passed to interface parameters",
Run: run,
}
func run(pass *analysis.Pass) (interface{}, error) {
for _, file := range pass.Files {
ast.Inspect(file, func(n ast.Node) bool {
callExpr, ok := n.(*ast.CallExpr)
if !ok {
return true
}
for i, arg := range callExpr.Args {
if ident, ok := arg.(*ast.Ident); ok && ident.Name == "nil" {
if sig, ok := pass.TypesInfo.TypeOf(callExpr.Fun).(*types.Signature); ok {
if i < sig.Params().Len() && isInterfaceish(sig.Params().At(i).Type()) {
pass.Reportf(arg.Pos(), "nil passed to interface parameter")
}
}
}
}
return true
})
}
return nil, nil
}
func isInterfaceish(t types.Type) bool {
return isInterface(t) || isFunction(t)
}
func isInterface(t types.Type) bool {
_, ok := t.Underlying().(*types.Interface)
return ok
}
func isFunction(t types.Type) bool {
_, ok := t.Underlying().(*types.Signature)
return ok
}