-
Notifications
You must be signed in to change notification settings - Fork 0
/
noiferr.go
83 lines (73 loc) · 1.8 KB
/
noiferr.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
package noiferr
import (
"go/token"
"go/types"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/buildssa"
"golang.org/x/tools/go/ssa"
)
const doc = "noiferr is static analysis tool which detects if received errors are handled with if statement"
var Analyzer = &analysis.Analyzer{
Name: "noiferr",
Doc: doc,
Run: run,
Requires: []*analysis.Analyzer{
buildssa.Analyzer,
},
}
var errType = types.Universe.Lookup("error").Type().Underlying().(*types.Interface)
func run(pass *analysis.Pass) (interface{}, error) {
funcs := pass.ResultOf[buildssa.Analyzer].(*buildssa.SSA).SrcFuncs
for _, f := range funcs {
for _, b := range f.Blocks {
for _, instr := range b.Instrs {
switch instr := instr.(type) {
case *ssa.Call:
if !isHandledWithCond(instr) {
pass.Reportf(instr.Pos(), "error received but not handled")
}
}
}
}
}
return nil, nil
}
func isError(typ types.Type) bool {
return types.Implements(typ, errType) || types.Implements(types.NewPointer(typ), errType)
}
func isHandledWithCond(callInstr *ssa.Call) bool {
switch typ := callInstr.Type().(type) {
case *types.Tuple:
for i := 0; i < typ.Len(); i++ {
if isError(typ.At(i).Type()) {
ref := (*callInstr.Referrers())[i]
extract, ok := ref.(*ssa.Extract)
if ok && !errorVarHandled(extract.Referrers()) {
return false
}
}
}
default:
if isError(typ) {
return errorVarHandled(callInstr.Referrers())
}
}
return true
}
func errorVarHandled(instrs *[]ssa.Instruction) bool {
for _, instr := range *instrs {
switch instr := instr.(type) {
case *ssa.BinOp:
if instr.Op != token.NEQ && instr.Op != token.EQL {
continue
}
for _, ref := range *instr.Referrers() {
_, ok := ref.(*ssa.If)
if ok {
return true
}
}
}
}
return false
}