forked from raeperd/recvcheck
-
Notifications
You must be signed in to change notification settings - Fork 0
/
analyzer.go
118 lines (99 loc) · 2.55 KB
/
analyzer.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
package recvcheck
import (
"go/ast"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/inspect"
"golang.org/x/tools/go/ast/inspector"
)
// NewAnalyzer returns a new analyzer to check for receiver type consistency.
func NewAnalyzer(s Settings) *analysis.Analyzer {
// Default excludes for Marshal/Encode methods https://github.com/raeperd/recvcheck/issues/7
excludedMethods := map[string]struct{}{
"MarshalText": {},
"MarshalJSON": {},
"MarshalYAML": {},
"MarshalXML": {},
"MarshalBinary": {},
"GobEncode": {},
"Value": {},
}
if s.DisableBuiltin {
excludedMethods = map[string]struct{}{}
}
a := &analyzer{excludedMethods: excludedMethods}
return &analysis.Analyzer{
Name: "recvcheck",
Doc: "checks for receiver type consistency",
Run: a.run,
Requires: []*analysis.Analyzer{inspect.Analyzer},
}
}
// Settings is the configuration for the analyzer.
type Settings struct {
// DisableBuiltin if true, disables the built-in method excludes.
// Built-in excluded methods:
// - "MarshalText"
// - "MarshalJSON"
// - "MarshalYAML"
// - "MarshalXML"
// - "MarshalBinary"
// - "GobEncode"
// - "Value"
DisableBuiltin bool
}
type analyzer struct {
excludedMethods map[string]struct{}
}
func (r *analyzer) run(pass *analysis.Pass) (any, error) {
inspector := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
structs := map[string]*structType{}
inspector.Preorder([]ast.Node{(*ast.FuncDecl)(nil)}, func(n ast.Node) {
funcDecl, ok := n.(*ast.FuncDecl)
if !ok || funcDecl.Recv == nil || len(funcDecl.Recv.List) != 1 {
return
}
if r.isExcluded(funcDecl) {
return
}
var recv *ast.Ident
var isStar bool
switch recvType := funcDecl.Recv.List[0].Type.(type) {
case *ast.StarExpr:
isStar = true
if recv, ok = recvType.X.(*ast.Ident); !ok {
return
}
case *ast.Ident:
recv = recvType
default:
return
}
st, ok := structs[recv.Name]
if !ok {
structs[recv.Name] = &structType{}
st = structs[recv.Name]
}
if isStar {
st.starUsed = true
} else {
st.typeUsed = true
}
})
for recv, st := range structs {
if st.starUsed && st.typeUsed {
pass.Reportf(pass.Pkg.Scope().Lookup(recv).Pos(), "the methods of %q use pointer receiver and non-pointer receiver.", recv)
}
}
return nil, nil
}
func (r *analyzer) isExcluded(f *ast.FuncDecl) bool {
if f.Name == nil || f.Name.Name == "" {
return true
}
_, found := r.excludedMethods[f.Name.Name]
return found
}
type structType struct {
starUsed bool
typeUsed bool
}