-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathnoinlineerr.go
More file actions
154 lines (126 loc) · 3.45 KB
/
noinlineerr.go
File metadata and controls
154 lines (126 loc) · 3.45 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
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
package noinlineerr
import (
"bytes"
"go/ast"
"go/printer"
"go/types"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/inspect"
"golang.org/x/tools/go/ast/inspector"
)
const errMessage = "avoid inline error handling using `if err := ...; err != nil`; use plain assignment `err := ...`"
func NewAnalyzer() *analysis.Analyzer {
return &analysis.Analyzer{
Name: "noinlineerr",
Doc: "Disallows inline error handling (`if err := ...; err != nil {`)",
Run: run,
Requires: []*analysis.Analyzer{inspect.Analyzer},
}
}
func run(pass *analysis.Pass) (any, error) {
insp, ok := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
if !ok {
return nil, nil //nolint:nilnil // nothing to return
}
nodeFilter := []ast.Node{
(*ast.IfStmt)(nil),
}
insp.Preorder(nodeFilter, inlineErrorInspector(pass))
return nil, nil //nolint:nilnil // nothing to return
}
func inlineErrorInspector(pass *analysis.Pass) func(n ast.Node) {
return func(n ast.Node) {
ifStmt, ok := n.(*ast.IfStmt)
if !ok || ifStmt.Init == nil {
return
}
// check if the init clause is an assignment
assignStmt, ok := ifStmt.Init.(*ast.AssignStmt)
if !ok {
return
}
// iterate over left-hand side variables of the assignment
for _, lhs := range assignStmt.Lhs {
ident, ok := lhs.(*ast.Ident)
if !ok {
continue
}
// confirm type is error and it is used in condition
obj := pass.TypesInfo.ObjectOf(ident)
if !isError(obj) || ident.Name == "_" || !errorUsedInCondition(ifStmt.Cond, ident.Name) {
continue
}
// if there are more than 1 assignment
// or there are any variables with same name
// then we can make a shadow conflict with other variables
// so don't do anything beside simple error message
if len(assignStmt.Lhs) != 1 || shadowVarsExists(ident.Name, pass.TypesInfo.Scopes[ifStmt]) {
pass.Reportf(ident.Pos(), errMessage)
return
}
// else we know there is a simple err assignment like
// if err := func(); err != nil {}
// and we can autofix that
var buf bytes.Buffer
_ = printer.Fprint(&buf, pass.Fset, assignStmt)
assignText := buf.String()
// report usage of inline error assignment
pass.Report(analysis.Diagnostic{
Pos: ident.Pos(),
End: ident.End(),
Message: errMessage,
SuggestedFixes: []analysis.SuggestedFix{
{
Message: "move err assignment outside if",
TextEdits: []analysis.TextEdit{
{
// insert err := ... before if
Pos: ifStmt.Pos(),
End: ifStmt.Pos(),
NewText: []byte(assignText + "\n"),
},
{
// delete Init part
Pos: assignStmt.Pos(),
End: assignStmt.End() + 1, // +1 for ;
NewText: nil,
},
},
},
},
})
}
}
}
func isError(obj types.Object) bool {
if obj == nil {
return false
}
errorType := types.Universe.Lookup("error").Type()
return types.AssignableTo(obj.Type(), errorType)
}
func shadowVarsExists(name string, scope *types.Scope) bool {
if scope == nil {
return false
}
parentScope := scope.Parent()
if parentScope == nil {
return false
}
return parentScope.Lookup(name) != nil
}
func errorUsedInCondition(cond ast.Expr, errIdentName string) bool {
used := false
ast.Inspect(cond, func(n ast.Node) bool {
ident, ok := n.(*ast.Ident)
if !ok {
return true
}
if ident.Name == errIdentName {
used = true
return false
}
return true
})
return used
}