-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsametype.go
85 lines (73 loc) · 2.09 KB
/
sametype.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
package sametype
import (
"go/ast"
"go/types"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/inspect"
"golang.org/x/tools/go/ast/inspector"
"golang.org/x/tools/go/types/typeutil"
)
var Analyzer = &analysis.Analyzer {
Name: "cmpequal",
Doc: "Check arg types of cmp.Equal",
Requires:
[]*analysis.Analyzer{inspect.Analyzer},
FactTypes: []analysis.Fact{(*SameType)(nil)},
Run: run,
}
type SameType struct{}
func (s *SameType) AFact() {}
func run(pass *analysis.Pass) (interface{}, error) {
inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
checkForFact := func(n ast.Node) {
call := n.(*ast.CallExpr)
fn, _ := typeutil.Callee(pass.TypesInfo, call).(*types.Func)
if fn == nil {
return // not a function call
}
var sameType SameType
if !pass.ImportObjectFact(fn, &sameType) {
return
}
typ0 := pass.TypesInfo.Types[call.Args[0]].Type
typ1 := pass.TypesInfo.Types[call.Args[1]].Type
if !types.Identical(typ0, typ1) {
pass.Reportf(call.Pos(),
"Calls to %v must have arguments of the same type; "+
"is called with %v and %v",
fn.Name(), typ0, typ1)
}}
maybeAddFact := func(n ast.Node, push bool, stack []ast.Node) bool {
if !push {
return true
}
call := n.(*ast.CallExpr)
fn, _ := typeutil.Callee(pass.TypesInfo, call).(*types.Func)
if fn == nil {
return false // not a function call
}
if fn.FullName() != "annotate.SameType" {
return false // not an annotation
}
var enclosingFunc *ast.FuncDecl
for _, node := range stack {
if v, ok := node.(*ast.FuncDecl); ok {
enclosingFunc = v
break
}
}
if enclosingFunc == nil {
return false // we didn't find the enclosing call
} else if len(enclosingFunc.Type.Params.List) != 2 {
pass.Reportf(call.Pos(), "SameType annotation can only be added to funcs with two arguments")
}
obj := pass.TypesInfo.Defs[enclosingFunc.Name]
pass.ExportObjectFact(obj, &SameType{})
return false
}
inspect.WithStack([]ast.Node{(*ast.CallExpr)(nil)}, maybeAddFact)
inspect.Preorder(
[]ast.Node{(*ast.CallExpr)(nil)},
checkForFact)
return nil, nil
}