-
Notifications
You must be signed in to change notification settings - Fork 3
/
zerologlint.go
261 lines (232 loc) · 6.38 KB
/
zerologlint.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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
package zerologlint
import (
"go/token"
"go/types"
"strings"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/buildssa"
"golang.org/x/tools/go/ssa"
"github.com/gostaticanalysis/comment/passes/commentmap"
)
var Analyzer = &analysis.Analyzer{
Name: "zerologlint",
Doc: "Detects the wrong usage of `zerolog` that a user forgets to dispatch with `Send` or `Msg`",
Run: run,
Requires: []*analysis.Analyzer{
buildssa.Analyzer,
commentmap.Analyzer,
},
}
type posser interface {
Pos() token.Pos
}
// callDefer is an interface just to hold both ssa.Call and ssa.Defer in our set
type callDefer interface {
Common() *ssa.CallCommon
Pos() token.Pos
}
type linter struct {
// eventSet holds all the ssa block that is a zerolog.Event type instance
// that should be dispatched.
// Everytime the zerolog.Event is dispatched with Msg() or Send(),
// deletes that block from this set.
// At the end, check if the set is empty, or report the not dispatched block.
eventSet map[posser]struct{}
// deleteLater holds the ssa block that should be deleted from eventSet after
// all the inspection is done.
// this is required because `else` ssa block comes after the dispatch of `if`` block.
// e.g., if err != nil { log.Error() } else { log.Info() } log.Send()
// deleteLater takes care of the log.Info() block.
deleteLater map[posser]struct{}
recLimit uint
}
func run(pass *analysis.Pass) (interface{}, error) {
srcFuncs := pass.ResultOf[buildssa.Analyzer].(*buildssa.SSA).SrcFuncs
l := &linter{
eventSet: make(map[posser]struct{}),
deleteLater: make(map[posser]struct{}),
recLimit: 100,
}
for _, sf := range srcFuncs {
for _, b := range sf.Blocks {
for _, instr := range b.Instrs {
if c, ok := instr.(*ssa.Call); ok {
l.inspect(c)
} else if c, ok := instr.(*ssa.Defer); ok {
l.inspect(c)
}
}
}
}
// apply deleteLater to envetSet for else branches of if-else cases
for k := range l.deleteLater {
delete(l.eventSet, k)
}
// At the end, if the set is clear -> ok.
// Otherwise, there must be a left zerolog.Event var that weren't dispatched. So report it.
for k := range l.eventSet {
pass.Reportf(k.Pos(), "must be dispatched by Msg or Send method")
}
return nil, nil
}
func (l *linter) inspect(cd callDefer) {
c := cd.Common()
// check if it's in github.com/rs/zerolog/log since there's some
// functions in github.com/rs/zerolog that returns zerolog.Event
// which should not be included. However, zerolog.Logger receiver is an exception.
if isInLogPkg(*c) || isLoggerRecv(*c) {
if isZerologEvent(c.Value) {
// this ssa block should be dispatched afterwards at some point
l.eventSet[cd] = struct{}{}
return
}
}
// if the call does not return zerolog.Event,
// check if the base is zerolog.Event.
// if so, check if the StaticCallee is Send() or Msg().
// if so, remove the arg[0] from the set.
f := c.StaticCallee()
if f == nil {
return
}
if !isDispatchMethod(f) {
shouldReturn := true
for _, p := range f.Params {
if isZerologEvent(p) {
// check if this zerolog.Event as a parameter is dispatched in the function
// TODO: technically, it can be dispatched in another function that is called in this function, and
// this algorithm cannot track that. But I'm tired of thinking about that for now.
for _, b := range f.Blocks {
for _, instr := range b.Instrs {
switch v := instr.(type) {
case *ssa.Call:
if inspectDispatchInFunction(v.Common()) {
shouldReturn = false
break
}
case *ssa.Defer:
if inspectDispatchInFunction(v.Common()) {
shouldReturn = false
break
}
}
}
}
}
}
if shouldReturn {
return
}
}
for _, arg := range c.Args {
if isZerologEvent(arg) {
// if there's branch, track both ways
// this is for the case like:
// logger := log.Info()
// if err != nil {
// logger = log.Error()
// }
// logger.Send()
//
// Similar case like below goes to the same root but that doesn't
// have any side effect.
// logger := log.Info()
// if err != nil {
// logger = logger.Str("a", "b")
// }
// logger.Send()
if phi, ok := arg.(*ssa.Phi); ok {
for _, edge := range phi.Edges {
l.dfsEdge(edge, make(map[ssa.Value]struct{}), 0)
}
} else {
val := getRootSsaValue(arg)
delete(l.eventSet, val)
}
}
}
}
func (l *linter) dfsEdge(v ssa.Value, visit map[ssa.Value]struct{}, cnt uint) {
// only for safety
if cnt > l.recLimit {
return
}
cnt++
if _, ok := visit[v]; ok {
return
}
visit[v] = struct{}{}
val := getRootSsaValue(v)
phi, ok := val.(*ssa.Phi)
if !ok {
l.deleteLater[val] = struct{}{}
return
}
for _, edge := range phi.Edges {
l.dfsEdge(edge, visit, cnt)
}
}
func inspectDispatchInFunction(cc *ssa.CallCommon) bool {
if isDispatchMethod(cc.StaticCallee()) {
for _, arg := range cc.Args {
if isZerologEvent(arg) {
return true
}
}
}
return false
}
func isInLogPkg(c ssa.CallCommon) bool {
switch v := c.Value.(type) {
case ssa.Member:
p := v.Package()
if p == nil {
return false
}
return strings.HasSuffix(p.Pkg.Path(), "github.com/rs/zerolog/log")
}
return false
}
func isLoggerRecv(c ssa.CallCommon) bool {
switch f := c.Value.(type) {
case *ssa.Function:
if recv := f.Signature.Recv(); recv != nil {
return strings.HasSuffix(types.TypeString(recv.Type(), nil), "zerolog.Logger")
}
}
return false
}
func isZerologEvent(v ssa.Value) bool {
ts := v.Type().String()
return strings.HasSuffix(ts, "github.com/rs/zerolog.Event")
}
func isDispatchMethod(f *ssa.Function) bool {
if f == nil {
return false
}
m := f.Name()
if m == "Send" || m == "Msg" || m == "Msgf" || m == "MsgFunc" {
return true
}
return false
}
func getRootSsaValue(v ssa.Value) ssa.Value {
if c, ok := v.(*ssa.Call); ok {
v := c.Value()
// When there is no receiver, that's the block of zerolog.Event
// eg. Error() method in log.Error().Str("foo", "bar").Send()
if len(v.Call.Args) == 0 {
return v
}
// Even when there is a receiver, if it's a zerolog.Logger instance, return this block
// eg. Info() method in zerolog.New(os.Stdout).Info()
root := v.Call.Args[0]
if !isZerologEvent(root) {
return v
}
// Ok to just return the receiver because all the method in this
// chain is zerolog.Event at this point.
return getRootSsaValue(root)
}
return v
}