@@ -8,14 +8,50 @@ import (
8
8
"golang.org/x/tools/go/ast/inspector"
9
9
)
10
10
11
- var Analyzer = & analysis.Analyzer {
12
- Name : "recvcheck" ,
13
- Doc : "checks for receiver type consistency" ,
14
- Run : run ,
15
- Requires : []* analysis.Analyzer {inspect .Analyzer },
11
+ // NewAnalyzer returns a new analyzer to check for receiver type consistency.
12
+ func NewAnalyzer (s Settings ) * analysis.Analyzer {
13
+ // Default excludes for Marshal/Encode methods https://github.com/raeperd/recvcheck/issues/7
14
+ excludedMethods := map [string ]struct {}{
15
+ "MarshalText" : {},
16
+ "MarshalJSON" : {},
17
+ "MarshalYAML" : {},
18
+ "MarshalXML" : {},
19
+ "MarshalBinary" : {},
20
+ "GobEncode" : {},
21
+ }
22
+
23
+ if s .DisableBuiltin {
24
+ excludedMethods = map [string ]struct {}{}
25
+ }
26
+
27
+ a := & analyzer {excludedMethods : excludedMethods }
28
+
29
+ return & analysis.Analyzer {
30
+ Name : "recvcheck" ,
31
+ Doc : "checks for receiver type consistency" ,
32
+ Run : a .run ,
33
+ Requires : []* analysis.Analyzer {inspect .Analyzer },
34
+ }
35
+ }
36
+
37
+ // Settings is the configuration for the analyzer.
38
+ type Settings struct {
39
+ // DisableBuiltin if true, disables the built-in method excludes.
40
+ // Built-in excluded methods:
41
+ // - "MarshalText"
42
+ // - "MarshalJSON"
43
+ // - "MarshalYAML"
44
+ // - "MarshalXML"
45
+ // - "MarshalBinary"
46
+ // - "GobEncode"
47
+ DisableBuiltin bool
16
48
}
17
49
18
- func run (pass * analysis.Pass ) (any , error ) {
50
+ type analyzer struct {
51
+ excludedMethods map [string ]struct {}
52
+ }
53
+
54
+ func (r * analyzer ) run (pass * analysis.Pass ) (any , error ) {
19
55
inspector := pass .ResultOf [inspect .Analyzer ].(* inspector.Inspector )
20
56
21
57
structs := map [string ]* structType {}
@@ -25,6 +61,10 @@ func run(pass *analysis.Pass) (any, error) {
25
61
return
26
62
}
27
63
64
+ if r .isExcluded (funcDecl ) {
65
+ return
66
+ }
67
+
28
68
var recv * ast.Ident
29
69
var isStar bool
30
70
switch recvType := funcDecl .Recv .List [0 ].Type .(type ) {
@@ -61,6 +101,15 @@ func run(pass *analysis.Pass) (any, error) {
61
101
return nil , nil
62
102
}
63
103
104
+ func (r * analyzer ) isExcluded (f * ast.FuncDecl ) bool {
105
+ if f .Name == nil || f .Name .Name == "" {
106
+ return true
107
+ }
108
+
109
+ _ , found := r .excludedMethods [f .Name .Name ]
110
+ return found
111
+ }
112
+
64
113
type structType struct {
65
114
starUsed bool
66
115
typeUsed bool
0 commit comments