-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
setval.go
61 lines (49 loc) · 1.39 KB
/
setval.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
package setval
import (
"go/ast"
"go/token"
"go/types"
"golang.org/x/tools/go/analysis"
)
var Analyzer = &analysis.Analyzer{
Name: "setval",
Doc: "find Cmder types that are missing a SetVal method",
Run: func(pass *analysis.Pass) (interface{}, error) {
cmderTypes := make(map[string]token.Pos)
typesWithSetValMethod := make(map[string]bool)
for _, file := range pass.Files {
for _, decl := range file.Decls {
funcName, receiverType := parseFuncDecl(decl, pass.TypesInfo)
switch funcName {
case "Result":
cmderTypes[receiverType] = decl.Pos()
case "SetVal":
typesWithSetValMethod[receiverType] = true
}
}
}
for cmder, pos := range cmderTypes {
if !typesWithSetValMethod[cmder] {
pass.Reportf(pos, "%s is missing a SetVal method", cmder)
}
}
return nil, nil
},
}
func parseFuncDecl(decl ast.Decl, typesInfo *types.Info) (funcName, receiverType string) {
funcDecl, ok := decl.(*ast.FuncDecl)
if !ok {
return "", "" // Not a function declaration.
}
if funcDecl.Recv == nil {
return "", "" // Not a method.
}
if len(funcDecl.Recv.List) != 1 {
return "", "" // Unexpected number of receiver arguments. (Can this happen?)
}
receiverTypeObj := typesInfo.TypeOf(funcDecl.Recv.List[0].Type)
if receiverTypeObj == nil {
return "", "" // Unable to determine the receiver type.
}
return funcDecl.Name.Name, receiverTypeObj.String()
}