-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanalyzer.go
More file actions
405 lines (346 loc) · 9.19 KB
/
analyzer.go
File metadata and controls
405 lines (346 loc) · 9.19 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
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
// Package analyzer provides a static analysis tool that checks Equals() method
// implementations for KRT-style semantic equality issues.
package analyzer
import (
"go/ast"
"go/token"
"go/types"
"strings"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/inspect"
"golang.org/x/tools/go/ast/inspector"
)
// Config controls optional checks performed by the krtequals analyzer.
type Config struct {
// DeepEqual toggles the rule that flags usage of reflect.DeepEqual inside Equals methods.
// This check is disabled by default for incremental rollout.
DeepEqual bool `json:"deepEqual"`
// CheckUnexported toggles whether unexported (lowercase) fields are checked.
// By default, only exported fields are validated. Enable this to also check
// that unexported fields are used in Equals methods.
CheckUnexported bool `json:"checkUnexported"`
}
// Analyzer is the default analyzer instance with all checks disabled.
// Use NewAnalyzer for custom configuration.
var Analyzer = NewAnalyzer(&Config{})
// NewAnalyzer creates a new krtequals analyzer with the given configuration.
func NewAnalyzer(cfg *Config) *analysis.Analyzer {
if cfg == nil {
cfg = &Config{}
}
a := &analyzerImpl{cfg: *cfg}
return &analysis.Analyzer{
Name: "krtequals",
Doc: "Checks Equals() implementations for KRT-style semantic equality issues",
Run: a.Run,
Requires: []*analysis.Analyzer{inspect.Analyzer},
}
}
type analyzerImpl struct {
cfg Config
}
type structInfo struct {
name string
fields map[string]*fieldInfo
}
type fieldInfo struct {
name string
pos token.Pos
exported bool
ignore bool
todo bool
}
func (a *analyzerImpl) Run(pass *analysis.Pass) (any, error) {
ins := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
structs := collectStructs(ins)
processedEquals := make(map[string]bool)
ins.Preorder([]ast.Node{(*ast.FuncDecl)(nil)}, func(n ast.Node) {
fd, ok := n.(*ast.FuncDecl)
if !ok || fd.Name == nil || fd.Body == nil {
return
}
if fd.Name.Name != "Equals" {
return
}
if a.cfg.DeepEqual {
checkReflectDeepEqual(pass, fd)
}
if fd.Recv == nil || len(fd.Recv.List) == 0 {
return
}
recvField := fd.Recv.List[0]
recvTypeName := namedTypeFromExpr(recvField.Type)
if recvTypeName == "" {
return
}
if processedEquals[recvTypeName] {
return
}
processedEquals[recvTypeName] = true
recvIdent := ""
if len(recvField.Names) > 0 && recvField.Names[0] != nil {
recvIdent = recvField.Names[0].Name
}
paramNames := paramIdentsWithType(fd.Type.Params, recvTypeName)
usedFields := collectUsedFieldsInEquals(fd.Body, recvIdent, paramNames)
// Check for struct comparisons that may bypass +noKrtEquals markers
checkStructComparisons(pass, fd, recvIdent, paramNames, structs)
sinfo, ok := structs[recvTypeName]
if !ok {
return
}
for _, f := range sinfo.fields {
if f.ignore || f.todo {
continue
}
// Skip unexported fields unless checkUnexported is enabled
if !f.exported && !a.cfg.CheckUnexported {
continue
}
if !usedFields[f.name] {
pass.Reportf(f.pos, "field %q in type %q is not used in Equals; either compare it or add // +noKrtEquals", f.name, sinfo.name)
}
}
})
return nil, nil
}
func collectStructs(ins *inspector.Inspector) map[string]*structInfo {
structs := make(map[string]*structInfo)
ins.Preorder([]ast.Node{(*ast.TypeSpec)(nil)}, func(n ast.Node) {
ts, ok := n.(*ast.TypeSpec)
if !ok {
return
}
st, ok := ts.Type.(*ast.StructType)
if !ok {
return
}
si := &structInfo{
name: ts.Name.Name,
fields: make(map[string]*fieldInfo),
}
if st.Fields == nil {
structs[si.name] = si
return
}
for _, field := range st.Fields.List {
if len(field.Names) == 0 {
continue
}
ignore, todo := fieldMarkers(field)
for _, nameIdent := range field.Names {
if nameIdent == nil {
continue
}
fi := &fieldInfo{
name: nameIdent.Name,
pos: field.Pos(),
exported: nameIdent.IsExported(),
ignore: ignore,
todo: todo,
}
si.fields[fi.name] = fi
}
}
structs[si.name] = si
})
return structs
}
// checkStructComparisons detects when struct-typed fields are compared using == or !=
// instead of delegating to an Equals() method. This is problematic because Go's default
// struct comparison compares ALL fields, potentially comparing fields that have
// +noKrtEquals or +krtEqualsTodo markers that should be excluded.
func checkStructComparisons(pass *analysis.Pass, fd *ast.FuncDecl, recvIdent string, paramIdents []string, structs map[string]*structInfo) {
if pass.TypesInfo == nil {
return
}
paramSet := make(map[string]struct{}, len(paramIdents))
for _, p := range paramIdents {
paramSet[p] = struct{}{}
}
ast.Inspect(fd.Body, func(n ast.Node) bool {
binExpr, ok := n.(*ast.BinaryExpr)
if !ok {
return true
}
// Check for == or != comparisons
if binExpr.Op != token.EQL && binExpr.Op != token.NEQ {
return true
}
// Check if left side is a field access from receiver or param
leftSel, leftOk := binExpr.X.(*ast.SelectorExpr)
if !leftOk {
return true
}
leftIdent, leftIdentOk := leftSel.X.(*ast.Ident)
if !leftIdentOk {
return true
}
// Check if it's from receiver or parameter
isRecv := leftIdent.Name == recvIdent
_, isParam := paramSet[leftIdent.Name]
if !isRecv && !isParam {
return true
}
// Get the type of the field being compared
leftType := pass.TypesInfo.TypeOf(leftSel)
if leftType == nil {
return true
}
// Check if it's a named struct type
namedType, ok := leftType.(*types.Named)
if !ok {
// Try unwrapping pointer
if ptrType, isPtrType := leftType.(*types.Pointer); isPtrType {
namedType, ok = ptrType.Elem().(*types.Named)
}
if !ok {
return true
}
}
_, ok = namedType.Underlying().(*types.Struct)
if !ok {
return true
}
// Check if the struct type has any ignored fields
typeName := namedType.Obj().Name()
structInfo, ok := structs[typeName]
if !ok {
return true
}
// Check if any fields have +noKrtEquals markers
hasIgnoredFields := false
for _, field := range structInfo.fields {
if field.ignore || field.todo {
hasIgnoredFields = true
break
}
}
if hasIgnoredFields {
opStr := "=="
if binExpr.Op == token.NEQ {
opStr = "!="
}
pass.Reportf(binExpr.Pos(), "field %q of struct type %q is compared using %s which ignores +noKrtEquals/+krtEqualsTodo markers; use .Equals() method instead",
leftSel.Sel.Name, typeName, opStr)
}
return true
})
}
func checkReflectDeepEqual(pass *analysis.Pass, fd *ast.FuncDecl) {
if pass.TypesInfo == nil {
return
}
ast.Inspect(fd.Body, func(n ast.Node) bool {
call, ok := n.(*ast.CallExpr)
if !ok {
return true
}
sel, ok := call.Fun.(*ast.SelectorExpr)
if !ok {
return true
}
pkgIdent, ok := sel.X.(*ast.Ident)
if !ok {
return true
}
obj := pass.TypesInfo.Uses[pkgIdent]
pkgName, ok := obj.(*types.PkgName)
if !ok {
return true
}
if pkgName.Imported().Path() == "reflect" && sel.Sel.Name == "DeepEqual" {
pass.Reportf(call.Pos(), "Equals() method uses reflect.DeepEqual which is slow and ignores //+noKrtEquals markers")
}
return true
})
}
func namedTypeFromExpr(expr ast.Expr) string {
switch t := expr.(type) {
case *ast.Ident:
return t.Name
case *ast.StarExpr:
if id, ok := t.X.(*ast.Ident); ok {
return id.Name
}
}
return ""
}
func paramIdentsWithType(params *ast.FieldList, typeName string) []string {
if params == nil {
return nil
}
var out []string
for _, field := range params.List {
if !sameNamedType(field.Type, typeName) {
continue
}
for _, nameIdent := range field.Names {
if nameIdent != nil && nameIdent.Name != "" {
out = append(out, nameIdent.Name)
}
}
}
return out
}
func sameNamedType(expr ast.Expr, typeName string) bool {
switch t := expr.(type) {
case *ast.Ident:
return t.Name == typeName
case *ast.StarExpr:
if id, ok := t.X.(*ast.Ident); ok {
return id.Name == typeName
}
}
return false
}
func collectUsedFieldsInEquals(body *ast.BlockStmt, recvIdent string, paramIdents []string) map[string]bool {
used := make(map[string]bool)
if body == nil {
return used
}
paramSet := make(map[string]struct{}, len(paramIdents))
for _, p := range paramIdents {
paramSet[p] = struct{}{}
}
ast.Inspect(body, func(n ast.Node) bool {
sel, ok := n.(*ast.SelectorExpr)
if !ok {
return true
}
id, ok := sel.X.(*ast.Ident)
if !ok {
return true
}
if id.Name == recvIdent {
used[sel.Sel.Name] = true
return true
}
if _, ok := paramSet[id.Name]; ok {
used[sel.Sel.Name] = true
}
return true
})
return used
}
func fieldMarkers(field *ast.Field) (ignore bool, todo bool) {
ignoreDoc, todoDoc := extractSpecialMarkers(field.Doc)
ignoreLine, todoLine := extractSpecialMarkers(field.Comment)
return ignoreDoc || ignoreLine, todoDoc || todoLine
}
func extractSpecialMarkers(cg *ast.CommentGroup) (ignore bool, todo bool) {
if cg == nil {
return
}
for _, c := range cg.List {
text := strings.ToLower(c.Text)
if strings.Contains(text, "+krtequalstodo") {
ignore = true
todo = true
}
if strings.Contains(text, "+nokrtequals") {
ignore = true
}
}
return
}