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
|
package rule
import (
"fmt"
"go/ast"
"go/token"
"github.com/mgechev/revive/lint"
)
// UnexportedNamingRule lints wrongly named unexported symbols.
type UnexportedNamingRule struct{}
// Apply applies the rule to given file.
func (r *UnexportedNamingRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure {
var failures []lint.Failure
onFailure := func(failure lint.Failure) {
failures = append(failures, failure)
}
ba := &unexportablenamingLinter{onFailure}
ast.Walk(ba, file.AST)
return failures
}
// Name returns the rule name.
func (r *UnexportedNamingRule) Name() string {
return "unexported-naming"
}
type unexportablenamingLinter struct {
onFailure func(lint.Failure)
}
func (unl unexportablenamingLinter) Visit(node ast.Node) ast.Visitor {
switch n := node.(type) {
case *ast.FuncDecl:
unl.lintFunction(n.Type, n.Body)
return nil
case *ast.FuncLit:
unl.lintFunction(n.Type, n.Body)
return nil
case *ast.AssignStmt:
if n.Tok != token.DEFINE {
return nil
}
ids := []*ast.Ident{}
for _, e := range n.Lhs {
id, ok := e.(*ast.Ident)
if !ok {
continue
}
ids = append(ids, id)
}
unl.lintIDs(ids)
case *ast.DeclStmt:
gd, ok := n.Decl.(*ast.GenDecl)
if !ok {
return nil
}
if len(gd.Specs) < 1 {
return nil
}
vs, ok := gd.Specs[0].(*ast.ValueSpec)
if !ok {
return nil
}
unl.lintIDs(vs.Names)
}
return unl
}
func (unl unexportablenamingLinter) lintFunction(ft *ast.FuncType, body *ast.BlockStmt) {
unl.lintFields(ft.Params)
unl.lintFields(ft.Results)
if body != nil {
ast.Walk(unl, body)
}
}
func (unl unexportablenamingLinter) lintFields(fields *ast.FieldList) {
if fields == nil {
return
}
ids := []*ast.Ident{}
for _, field := range fields.List {
ids = append(ids, field.Names...)
}
unl.lintIDs(ids)
}
func (unl unexportablenamingLinter) lintIDs(ids []*ast.Ident) {
for _, id := range ids {
if id.IsExported() {
unl.onFailure(lint.Failure{
Node: id,
Confidence: 1,
Category: "naming",
Failure: fmt.Sprintf("the symbol %s is local, its name should start with a lowercase letter", id.String()),
})
}
}
}
|