-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconsistent.go
More file actions
413 lines (326 loc) · 10.5 KB
/
consistent.go
File metadata and controls
413 lines (326 loc) · 10.5 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
406
407
408
409
410
411
412
413
package consistent
import (
"go/ast"
"go/token"
"slices"
"strconv"
"strings"
"github.com/go-toolsmith/astcast"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/inspect"
"golang.org/x/tools/go/ast/inspector"
)
type configuration struct {
params enumValue
returns enumValue
typeParams enumValue
funcTypeParams enumValue
singleImports enumValue
newAllocs enumValue
makeAllocs enumValue
hexLits enumValue
rangeChecks enumValue
andNOTs enumValue
floatLits enumValue
lenChecks enumValue
switchCases enumValue
switchDefaults enumValue
emptyIfaces enumValue
slogAttrs enumValue
labelsRegexp regexpValue
fileCommentIgnoreRegexp regexpValue
}
const flagIgnore = "ignore"
// NewAnalyzer returns a new analyzer.
func NewAnalyzer() *analysis.Analyzer {
cfg := configuration{
params: enumValue{
allowed: paramsFlagAllowedValues,
value: fieldListExplicit,
},
returns: enumValue{
allowed: returnsFlagAllowedValues,
value: fieldListExplicit,
},
typeParams: enumValue{
allowed: typeParamsFlagAllowedValues,
value: fieldListExplicit,
},
funcTypeParams: enumValue{
allowed: funcTypeParamsFlagAllowedValues,
value: fieldListExplicit,
},
singleImports: enumValue{
allowed: singleImportsFlagAllowedValues,
value: singleImportsBare,
},
newAllocs: enumValue{
allowed: newAllocsFlagAllowedValues,
value: newAllocsLiteral,
},
makeAllocs: enumValue{
allowed: makeAllocsFlagAllowedValues,
value: makeAllocsLiteral,
},
hexLits: enumValue{
allowed: hexLitsFlagAllowedValues,
value: hexLitsLower,
},
rangeChecks: enumValue{
allowed: rangeChecksFlagAllowedValues,
value: rangeChecksLeft,
},
andNOTs: enumValue{
allowed: andNOTsFlagAllowedValues,
value: andNOTsANDNOT,
},
floatLits: enumValue{
allowed: floatLitsFlagAllowedValues,
value: floatLitsExplicit,
},
lenChecks: enumValue{
allowed: lenChecksFlagAllowedValues,
value: lenChecksEqualZero,
},
switchCases: enumValue{
allowed: switchCasesFlagAllowedValues,
value: switchCasesComma,
},
switchDefaults: enumValue{
allowed: switchDefaultsFlagAllowedValues,
value: switchDefaultsLast,
},
emptyIfaces: enumValue{
allowed: emptyIfacesFlagAllowedValues,
value: emptyIfacesAny,
},
slogAttrs: enumValue{
allowed: slogAttrsFlagAllowedValues,
value: slogAttrsAttr,
},
labelsRegexp: newRegexpValue("^[a-z][a-zA-Z0-9]*$"),
fileCommentIgnoreRegexp: newRegexpValue(""),
}
ana := analysis.Analyzer{
Name: "consistent",
Doc: "checks that common constructs are used consistently",
Run: func(pass *analysis.Pass) (any, error) {
run(pass, &cfg)
return nil, nil
},
Requires: []*analysis.Analyzer{
inspect.Analyzer,
},
}
ana.Flags.Var(&cfg.params, "params", cfg.params.description("check function/method parameter types"))
ana.Flags.Var(&cfg.returns, "returns", cfg.returns.description("check function/method return value types"))
ana.Flags.Var(&cfg.typeParams, "typeParams", cfg.typeParams.description("check type parameter types"))
ana.Flags.Var(&cfg.funcTypeParams, "funcTypeParams", cfg.funcTypeParams.description("check function type parameter types"))
ana.Flags.Var(&cfg.singleImports, "singleImports", cfg.singleImports.description("check single import declarations"))
ana.Flags.Var(&cfg.newAllocs, "newAllocs", cfg.newAllocs.description("check allocations using new"))
ana.Flags.Var(&cfg.makeAllocs, "makeAllocs", cfg.makeAllocs.description("check allocations using make"))
ana.Flags.Var(&cfg.hexLits, "hexLits", cfg.hexLits.description("check upper/lowercase in hex literals"))
ana.Flags.Var(&cfg.rangeChecks, "rangeChecks", cfg.rangeChecks.description("check range checks"))
ana.Flags.Var(&cfg.andNOTs, "andNOTs", cfg.andNOTs.description("check AND-NOT expressions"))
ana.Flags.Var(&cfg.floatLits, "floatLits", cfg.floatLits.description("check floating-point literals"))
ana.Flags.Var(&cfg.lenChecks, "lenChecks", cfg.lenChecks.description("check len/cap checks"))
ana.Flags.Var(&cfg.switchCases, "switchCases", cfg.switchCases.description("check switch case clauses"))
ana.Flags.Var(&cfg.switchDefaults, "switchDefaults", cfg.switchDefaults.description("check switch default clauses"))
ana.Flags.Var(&cfg.emptyIfaces, "emptyIfaces", cfg.emptyIfaces.description("check empty interfaces"))
ana.Flags.Var(&cfg.slogAttrs, "slogAttrs", cfg.slogAttrs.description("check log/slog argument types"))
ana.Flags.Var(&cfg.labelsRegexp, "labelsRegexp", "check labels against regexp (\"\" to disable)")
ana.Flags.Var(&cfg.fileCommentIgnoreRegexp, "fileCommentIgnoreRegexp", "ignore files containing comment matching regexp")
return &ana
}
func run(pass *analysis.Pass, cfg *configuration) { //nolint:cyclop // it's only basic dispatcher logic
inspector := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) //nolint:forcetypeassert // inspect.Analyzer always returns *inspector.Inspector
ignoreFiles := filesToIgnore(pass, cfg)
filter := []ast.Node{
(*ast.AssignStmt)(nil),
(*ast.BasicLit)(nil),
(*ast.BinaryExpr)(nil),
(*ast.CallExpr)(nil),
(*ast.CompositeLit)(nil),
(*ast.Field)(nil),
(*ast.File)(nil),
(*ast.FuncDecl)(nil),
(*ast.FuncLit)(nil),
(*ast.FuncType)(nil),
(*ast.InterfaceType)(nil),
(*ast.LabeledStmt)(nil),
(*ast.SwitchStmt)(nil),
(*ast.TypeSpec)(nil),
(*ast.UnaryExpr)(nil),
(*ast.ValueSpec)(nil),
}
funcDecls := []*ast.FuncDecl{}
funcLits := []*ast.FuncLit{}
funcTypes := []*ast.FuncType{}
ignoreCurrentFile := false
inspector.Preorder(filter, func(node ast.Node) {
if ignoreCurrentFile {
return
}
switch node := node.(type) {
case *ast.AssignStmt:
checkAndNotAssignStmt(pass, node, cfg.andNOTs.value)
case *ast.BasicLit:
checkHexLit(pass, node, cfg.hexLits.value)
checkFloatLit(pass, node, cfg.floatLits.value)
case *ast.BinaryExpr:
checkRangeCheck(pass, node, cfg.rangeChecks.value)
checkAndNotExpr(pass, node, cfg.andNOTs.value)
checkLenCheck(pass, node, cfg.lenChecks.value)
case *ast.CallExpr:
checkNewAllocNew(pass, node, cfg.newAllocs.value)
checkMakeAllocMake(pass, node, cfg.makeAllocs.value)
checkSlogAttrs(pass, node, cfg.slogAttrs.value)
case *ast.CompositeLit:
checkMakeAllocLit(pass, node, cfg.makeAllocs.value)
case *ast.Field:
checkEmptyIface(pass, node, cfg.emptyIfaces.value)
case *ast.File:
ignoreCurrentFile = slices.Contains(ignoreFiles, node)
if ignoreCurrentFile {
return
}
checkSingleImports(pass, node, cfg.singleImports.value)
case *ast.FuncDecl:
funcDecls = append(funcDecls, node)
if node.Recv == nil {
checkParamsFunc(pass, node, cfg.params.value)
checkReturnsFunc(pass, node, cfg.returns.value)
checkTypeParamsFunc(pass, node, cfg.typeParams.value)
return
}
checkParamsMethod(pass, node, cfg.params.value)
checkReturnsMethod(pass, node, cfg.returns.value)
case *ast.FuncLit:
funcLits = append(funcLits, node)
checkParamsFuncLit(pass, node, cfg.params.value)
checkReturnsFuncLit(pass, node, cfg.returns.value)
case *ast.FuncType:
funcTypes = append(funcTypes, node)
case *ast.InterfaceType:
checkEmptyIface(pass, node, cfg.emptyIfaces.value)
case *ast.LabeledStmt:
checkLabel(pass, node, cfg.labelsRegexp)
case *ast.SwitchStmt:
checkSwitchCases(pass, node, cfg.switchCases.value)
checkSwitchDefault(pass, node, cfg.switchDefaults.value)
case *ast.TypeSpec:
checkTypeParamsType(pass, node, cfg.typeParams.value)
checkEmptyIface(pass, node, cfg.emptyIfaces.value)
case *ast.UnaryExpr:
checkNewAllocLit(pass, node, cfg.newAllocs.value)
case *ast.ValueSpec:
checkEmptyIface(pass, node, cfg.emptyIfaces.value)
}
})
for _, typ := range funcTypes {
if isFuncDefinition(typ, funcDecls, funcLits) {
continue
}
checkParamsFuncType(pass, typ, cfg.funcTypeParams.value)
}
}
func filesToIgnore(pass *analysis.Pass, cfg *configuration) []*ast.File {
if cfg.fileCommentIgnoreRegexp.r == nil {
return nil
}
files := []*ast.File{}
for _, file := range pass.Files {
for _, comment := range file.Comments {
if cfg.fileCommentIgnoreRegexp.r.MatchString(comment.Text()) {
files = append(files, file)
break
}
}
}
return files
}
func reportf(pass *analysis.Pass, pos token.Pos, format string, args ...any) {
if noLintDirectivePos(pass, pos) {
return
}
pass.Reportf(pos, format, args...)
}
func noLintDirectivePos(pass *analysis.Pass, pos token.Pos) bool {
line := pass.Fset.Position(pos).Line
for _, file := range pass.Files {
if pos < file.FileStart || pos > file.FileEnd {
continue
}
for _, comment := range file.Comments {
if pass.Fset.Position(comment.Pos()).Line < line {
continue
}
return noLintDirective(comment.List[0].Text)
}
}
return false
}
func noLintDirective(comment string) bool {
if !strings.HasPrefix(comment, "//nolint:") {
return false
}
comment = comment[9:]
secondaryCommentPos := strings.Index(comment, "//")
if secondaryCommentPos >= 0 {
comment = comment[:secondaryCommentPos]
}
for _, p := range strings.Split(comment, ",") {
if strings.TrimSpace(p) == "consistent" {
return true
}
}
return false
}
func isFuncDefinition(typ *ast.FuncType, decls []*ast.FuncDecl, lits []*ast.FuncLit) bool {
for _, decl := range decls {
if decl.Type == typ {
return true
}
}
for _, lit := range lits {
if lit.Type == typ {
return true
}
}
return false
}
func litInt(expr ast.Expr) (int, bool) {
lit := astcast.ToBasicLit(expr)
if lit.Kind != token.INT {
return 0, false
}
val := strings.ToLower(strings.ReplaceAll(lit.Value, "_", ""))
base := 10
switch {
case strings.HasPrefix(val, "0x"):
val = val[2:]
base = 16
case strings.HasPrefix(val, "0b"):
val = val[2:]
base = 2
case strings.HasPrefix(val, "0o"):
val = val[2:]
base = 8
case strings.HasPrefix(val, "0") && strings.TrimLeft(val, "0") == "":
return 0, true
case strings.HasPrefix(val, "0"):
val = val[1:]
base = 8
}
i, err := strconv.ParseInt(val, base, 32)
if err != nil {
return 0, false
}
return int(i), true
}
func namedFields(fields *ast.FieldList) bool {
return fields != nil && len(fields.List) != 0 && len(fields.List[0].Names) != 0
}
func unnamedFields(fields *ast.FieldList) bool {
return fields != nil && len(fields.List) != 0 && len(fields.List[0].Names) == 0
}