-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathnargs.go
502 lines (411 loc) · 13.4 KB
/
nargs.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
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
package nargs
import (
"fmt"
"go/ast"
"go/build"
"go/token"
"log"
"sort"
"strconv"
"strings"
)
func init() {
build.Default.UseAllFiles = true
}
// Flags contains configuration specific to nargs
// * IncludeTests - include test files in analysis
// * SetExitStatus - set exit status to 1 if any issues are found
// * IncludeNamedReturns - include unused named returns
// * IncludeReceivers - include unused receivers
type Flags struct {
IncludeTests bool
SetExitStatus bool
IncludeNamedReturns bool
IncludeReceivers bool
}
type unusedVisitor struct {
fileSet *token.FileSet
currentFile *token.File
resultsSet map[string]struct{}
includeNamedReturns bool
includeReceivers bool
errsFound bool
}
// CheckForUnusedFunctionArgs will parse the files/packages contained in args
// and walk the AST searching for unused function parameters.
func CheckForUnusedFunctionArgs(args []string, flags Flags) (results []string, exitWithStatus bool, _ error) {
fset := token.NewFileSet()
files, err := parseInput(args, fset, flags.IncludeTests)
if err != nil {
return nil, false, fmt.Errorf("could not parse input, %v", err)
}
retVis := &unusedVisitor{
fileSet: fset,
includeNamedReturns: flags.IncludeNamedReturns,
includeReceivers: flags.IncludeReceivers,
resultsSet: make(map[string]struct{}),
}
// visitorResult contains the results for a specific visitor and is cleared on each
// iteration
var visitorResult []string
for _, f := range files {
if f == nil {
continue
}
ast.Walk(retVis, f)
for result := range retVis.resultsSet {
visitorResult = append(visitorResult, result)
}
// Due to our analysis, of the ast.File, we may end up getting our results out of order. Sort by line number to keep
// the results in a consistent format.
sort.Sort(byLineNumber(visitorResult))
results = append(results, visitorResult...)
visitorResult = nil
retVis.resultsSet = make(map[string]struct{})
}
return results, retVis.errsFound && flags.SetExitStatus, nil
}
// ugly, but not sure if there's another option..
type byLineNumber []string
func (a byLineNumber) Len() int { return len(a) }
func (a byLineNumber) Less(i, j int) bool {
iLine := strings.Split(a[i], ":")
num := strings.Split(iLine[1], " ")
iNum, _ := strconv.Atoi(num[0])
jLine := strings.Split(a[j], ":")
num = strings.Split(jLine[1], " ")
jNum, _ := strconv.Atoi(num[0])
return iNum < jNum
}
func (a byLineNumber) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
// Visit implements the ast.Visitor Visit method.
func (v *unusedVisitor) Visit(node ast.Node) ast.Visitor {
var stmtList []ast.Stmt
var file *token.File
paramMap := make(map[string]bool)
var funcDecl *ast.FuncDecl
switch topLevelType := node.(type) {
case *ast.FuncDecl:
funcDecl = topLevelType
if funcDecl.Body == nil {
// This means funcDecl is an external (non-Go) function, these
// should not be included in the analysis
return v
}
stmtList = v.handleFuncDecl(paramMap, funcDecl, stmtList)
file = v.fileSet.File(funcDecl.Pos())
v.currentFile = file
case *ast.File:
file = v.fileSet.File(topLevelType.Pos())
v.currentFile = file
if topLevelType.Decls != nil {
stmtList = v.handleDecls(paramMap, topLevelType.Decls, stmtList)
}
default:
return v
}
// We cannot exit if len(paramMap) == 0, we may have a function closure with
// unused variables
// Analyze body of function
v.handleStmts(paramMap, stmtList)
for paramName, used := range paramMap {
if used {
continue
}
if file == nil {
continue
}
if funcDecl == nil {
continue
}
if funcDecl.Name == nil {
continue
}
// TODO print parameter vs parameter(s)?
// TODO differentiation of used parameter vs. receiver?
resStr := fmt.Sprintf("%v:%v %v contains unused parameter %v\n", file.Name(), file.Position(funcDecl.Pos()).Line, funcDecl.Name.Name, paramName)
v.resultsSet[resStr] = struct{}{}
v.errsFound = true
}
return v
}
func (v *unusedVisitor) handleStmts(paramMap map[string]bool, stmtList []ast.Stmt) {
for len(stmtList) != 0 {
stmt := stmtList[0]
switch s := stmt.(type) {
case *ast.IfStmt:
stmtList = append(stmtList, s.Init, s.Body, s.Else)
stmtList = v.handleExprs(paramMap, []ast.Expr{s.Cond}, stmtList)
case *ast.AssignStmt:
assigned := false
for index, right := range s.Rhs {
funcLit, ok := right.(*ast.FuncLit)
if !ok {
continue
}
funcName, ok := s.Lhs[index].(*ast.Ident)
if !ok {
// TODO - understand this case a little more
// log.Printf("@@@@@@@@@@@@@@@@@@@@@@@@@2 wat")
continue
}
v.handleFuncLit(paramMap, funcLit, funcName)
assigned = true
}
if !assigned {
stmtList = v.handleExprs(paramMap, s.Lhs, stmtList)
stmtList = v.handleExprs(paramMap, s.Rhs, stmtList)
}
case *ast.BlockStmt:
stmtList = append(stmtList, s.List...)
case *ast.ReturnStmt:
stmtList = v.handleExprs(paramMap, s.Results, stmtList)
case *ast.DeclStmt:
stmtList = v.handleDecls(paramMap, []ast.Decl{s.Decl}, stmtList)
case *ast.ExprStmt:
stmtList = v.handleExprs(paramMap, []ast.Expr{s.X}, stmtList)
case *ast.RangeStmt:
stmtList = append(stmtList, s.Body)
stmtList = v.handleExprs(paramMap, []ast.Expr{s.X}, stmtList)
case *ast.ForStmt:
stmtList = append(stmtList, s.Init)
stmtList = append(stmtList, s.Body)
stmtList = v.handleExprs(paramMap, []ast.Expr{s.Cond}, stmtList)
stmtList = append(stmtList, s.Post)
case *ast.TypeSwitchStmt:
stmtList = append(stmtList, s.Body, s.Assign, s.Init)
case *ast.CaseClause:
stmtList = v.handleExprs(paramMap, s.List, stmtList)
stmtList = append(stmtList, s.Body...)
case *ast.SendStmt:
stmtList = v.handleExprs(paramMap, []ast.Expr{s.Chan, s.Value}, stmtList)
case *ast.GoStmt:
stmtList = v.handleExprs(paramMap, []ast.Expr{s.Call}, stmtList)
case *ast.DeferStmt:
stmtList = v.handleExprs(paramMap, []ast.Expr{s.Call}, stmtList)
case *ast.SelectStmt:
stmtList = append(stmtList, s.Body)
case *ast.CommClause:
stmtList = append(stmtList, s.Body...)
stmtList = append(stmtList, s.Comm)
case *ast.BranchStmt:
handleIdent(paramMap, s.Label)
case *ast.SwitchStmt:
stmtList = append(stmtList, s.Body, s.Init)
stmtList = v.handleExprs(paramMap, []ast.Expr{s.Tag}, stmtList)
case *ast.LabeledStmt:
handleIdent(paramMap, s.Label)
stmtList = append(stmtList, s.Stmt)
case *ast.IncDecStmt:
stmtList = v.handleExprs(paramMap, []ast.Expr{s.X}, stmtList)
case nil, *ast.EmptyStmt:
// no-op
default:
log.Printf("ERROR: unknown stmt type %T in file %v\n", s, v.currentFile.Name())
}
stmtList = stmtList[1:]
}
}
func handleIdents(paramMap map[string]bool, identList []*ast.Ident) {
for _, ident := range identList {
handleIdent(paramMap, ident)
}
}
func handleIdent(paramMap map[string]bool, ident *ast.Ident) {
if ident == nil {
return
}
if ident.Obj != nil && ident.Obj.Kind == ast.Var {
if _, ok := paramMap[ident.Obj.Name]; ok {
paramMap[ident.Obj.Name] = true
}
/*else {
if ident.Obj.Name != "_" {
paramMap[ident.Obj.Name] = false
}
}*/
}
// TODO - ensure this truly isn't needed - can we rely on the
// ident object name?
// if _, ok := paramMap[ident.Name]; ok {
// paramMap[ident.Name] = true
// }
}
func (v *unusedVisitor) handleExprs(paramMap map[string]bool, exprList []ast.Expr, stmtList []ast.Stmt) []ast.Stmt {
for len(exprList) != 0 {
expr := exprList[0]
switch e := expr.(type) {
case *ast.Ident:
handleIdent(paramMap, e)
case *ast.BinaryExpr:
exprList = append(exprList, e.X) // TODO, do we need to then worry about x.left being used?
exprList = append(exprList, e.Y) // TODO, do we need to then worry about x.left being used?
case *ast.CallExpr:
exprList = append(exprList, e.Args...)
exprList = append(exprList, e.Fun)
case *ast.IndexExpr:
exprList = append(exprList, e.X)
exprList = append(exprList, e.Index)
case *ast.KeyValueExpr:
exprList = append(exprList, e.Key, e.Value)
case *ast.ParenExpr:
exprList = append(exprList, e.X)
case *ast.SelectorExpr:
exprList = append(exprList, e.X)
handleIdent(paramMap, e.Sel)
case *ast.SliceExpr:
exprList = append(exprList, e.Low, e.High, e.Max, e.X)
case *ast.StarExpr:
// need to dig deeper to see if this is a derefenced type
exprList = append(exprList, e.X)
case *ast.TypeAssertExpr:
exprList = append(exprList, e.X, e.Type)
case *ast.UnaryExpr:
exprList = append(exprList, e.X)
case *ast.BasicLit:
// nothing to do here, no variable name
case *ast.FuncLit:
exprList = append(exprList, e.Type)
stmtList = append(stmtList, e.Body)
case *ast.CompositeLit:
exprList = append(exprList, e.Elts...)
case *ast.ArrayType:
exprList = append(exprList, e.Elt, e.Len)
case *ast.ChanType:
exprList = append(exprList, e.Value)
case *ast.FuncType:
exprList, stmtList = handleFieldList(paramMap, e.Params, exprList, stmtList)
exprList, stmtList = handleFieldList(paramMap, e.Results, exprList, stmtList)
case *ast.InterfaceType:
exprList, stmtList = handleFieldList(paramMap, e.Methods, exprList, stmtList)
case *ast.MapType:
exprList = append(exprList, e.Key, e.Value)
case *ast.StructType:
// TODO: no-op, unless it contains funcs I guess? revisit this
// exprList, stmtList = handleFieldList(paramMap, e.Fields, exprList, stmtList)
case *ast.Ellipsis:
exprList = append(exprList, e.Elt)
case *ast.IndexListExpr:
exprList = append(exprList, e.X)
exprList = append(exprList, e.Indices...)
case nil:
// no op
default:
log.Printf("ERROR: unknown expr type %T in file %v\n", e, v.currentFile.Name())
}
exprList = exprList[1:]
}
return stmtList
}
func handleFieldList(paramMap map[string]bool, fieldList *ast.FieldList, exprList []ast.Expr, stmtList []ast.Stmt) ([]ast.Expr, []ast.Stmt) {
if fieldList == nil {
return exprList, stmtList
}
for _, field := range fieldList.List {
exprList = append(exprList, field.Type)
handleIdents(paramMap, field.Names)
}
return exprList, stmtList
}
func (v *unusedVisitor) handleDecls(paramMap map[string]bool, decls []ast.Decl, initialStmts []ast.Stmt) []ast.Stmt {
for _, decl := range decls {
switch d := decl.(type) {
case *ast.GenDecl:
for _, spec := range d.Specs {
switch specType := spec.(type) {
case *ast.ValueSpec:
// TODO - I think the only specs we care about here are when we have a function declaration
handleIdents(paramMap, specType.Names)
initialStmts = v.handleExprs(paramMap, []ast.Expr{specType.Type}, initialStmts)
initialStmts = v.handleExprs(paramMap, specType.Values, initialStmts)
for index, value := range specType.Values {
funcLit, ok := value.(*ast.FuncLit)
if !ok {
continue
}
funcName := specType.Names[index]
// get arguments of function, this is a candidate
// with potentially unused arguments
v.handleFuncLit(paramMap, funcLit, funcName)
}
case *ast.TypeSpec:
handleIdent(paramMap, specType.Name)
initialStmts = v.handleExprs(paramMap, []ast.Expr{specType.Type}, initialStmts)
case *ast.ImportSpec:
// no-op, ImportSpecs do not contain functions
default:
log.Printf("ERROR: unknown spec type %T\n", specType)
}
}
case *ast.FuncDecl:
initialStmts = v.handleFuncDecl(paramMap, d, initialStmts)
default:
log.Printf("ERROR: unknown decl type %T\n", d)
}
}
return initialStmts
}
// paramMap is passed in for cases where we have an outer function with a parameter
// that is captured by closure by the function literal
func (v *unusedVisitor) handleFuncLit(paramMap map[string]bool, funcLit *ast.FuncLit, funcName *ast.Ident) {
if funcLit.Type != nil && funcLit.Type.Params != nil {
// declare a separate parameter map for handling
funcParamMap := make(map[string]bool)
for _, param := range funcLit.Type.Params.List {
for _, paramName := range param.Names {
if paramName.Name != "_" {
funcParamMap[paramName.Name] = false
}
}
}
// generate potential statements
v.handleStmts(funcParamMap, []ast.Stmt{funcLit.Body})
v.handleStmts(paramMap, []ast.Stmt{funcLit.Body})
for paramName, used := range funcParamMap {
if !used && paramName != "_" {
// TODO: this append currently causes things to appear out of order (2)
file := v.fileSet.File(funcLit.Pos())
resStr := fmt.Sprintf("%v:%v %v contains unused parameter %v\n", file.Name(), file.Position(funcLit.Pos()).Line, funcName.Name, paramName)
v.resultsSet[resStr] = struct{}{}
}
}
}
}
func (v *unusedVisitor) handleFuncDecl(paramMap map[string]bool, funcDecl *ast.FuncDecl, initialStmts []ast.Stmt) []ast.Stmt {
if funcDecl.Body != nil {
initialStmts = append(initialStmts, funcDecl.Body.List...)
}
if funcDecl.Type != nil {
if funcDecl.Type.Params != nil {
for _, paramList := range funcDecl.Type.Params.List {
for _, name := range paramList.Names {
if name.Name == "_" {
continue
}
paramMap[name.Name] = false
}
}
}
if v.includeNamedReturns && funcDecl.Type.Results != nil {
for _, paramList := range funcDecl.Type.Results.List {
for _, name := range paramList.Names {
if name.Name == "_" {
continue
}
paramMap[name.Name] = false
}
}
}
}
if v.includeReceivers && funcDecl.Recv != nil {
for _, field := range funcDecl.Recv.List {
for _, name := range field.Names {
if name.Name == "_" {
continue
}
paramMap[name.Name] = false
}
}
}
return initialStmts
}