forked from golangci/golangci-lint
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdogsled.go
110 lines (91 loc) · 2.24 KB
/
dogsled.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
package golinters
import (
"fmt"
"go/ast"
"go/token"
"sync"
"golang.org/x/tools/go/analysis"
"github.com/golangci/golangci-lint/pkg/config"
"github.com/golangci/golangci-lint/pkg/goanalysis"
"github.com/golangci/golangci-lint/pkg/lint/linter"
"github.com/golangci/golangci-lint/pkg/result"
)
const dogsledName = "dogsled"
func NewDogsled(settings *config.DogsledSettings) *goanalysis.Linter {
var mu sync.Mutex
var resIssues []goanalysis.Issue
analyzer := &analysis.Analyzer{
Name: dogsledName,
Doc: goanalysis.TheOnlyanalyzerDoc,
Run: func(pass *analysis.Pass) (any, error) {
issues := runDogsled(pass, settings)
if len(issues) == 0 {
return nil, nil
}
mu.Lock()
resIssues = append(resIssues, issues...)
mu.Unlock()
return nil, nil
},
}
return goanalysis.NewLinter(
dogsledName,
"Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f())",
[]*analysis.Analyzer{analyzer},
nil,
).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue {
return resIssues
}).WithLoadMode(goanalysis.LoadModeSyntax)
}
func runDogsled(pass *analysis.Pass, settings *config.DogsledSettings) []goanalysis.Issue {
var reports []goanalysis.Issue
for _, f := range pass.Files {
v := &returnsVisitor{
maxBlanks: settings.MaxBlankIdentifiers,
f: pass.Fset,
}
ast.Walk(v, f)
for i := range v.issues {
reports = append(reports, goanalysis.NewIssue(&v.issues[i], pass))
}
}
return reports
}
type returnsVisitor struct {
f *token.FileSet
maxBlanks int
issues []result.Issue
}
func (v *returnsVisitor) Visit(node ast.Node) ast.Visitor {
funcDecl, ok := node.(*ast.FuncDecl)
if !ok {
return v
}
if funcDecl.Body == nil {
return v
}
for _, expr := range funcDecl.Body.List {
assgnStmt, ok := expr.(*ast.AssignStmt)
if !ok {
continue
}
numBlank := 0
for _, left := range assgnStmt.Lhs {
ident, ok := left.(*ast.Ident)
if !ok {
continue
}
if ident.Name == "_" {
numBlank++
}
}
if numBlank > v.maxBlanks {
v.issues = append(v.issues, result.Issue{
FromLinter: dogsledName,
Text: fmt.Sprintf("declaration has %v blank identifiers", numBlank),
Pos: v.f.Position(assgnStmt.Pos()),
})
}
}
return v
}