-
Notifications
You must be signed in to change notification settings - Fork 0
/
noouterval.go
180 lines (153 loc) · 3.94 KB
/
noouterval.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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
// Package noouterval finds uses of values from the outer scope,
// despite values of same type is defined in the inner scope.
package noouterval
import (
"fmt"
"go/ast"
"go/types"
"strings"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/inspect"
"golang.org/x/tools/go/ast/inspector"
)
var Analyzer = &analysis.Analyzer{
Name: "noouterval",
Doc: "check for uses of values from the outer scope despite values of same type in the inner scope",
Run: run,
Requires: []*analysis.Analyzer{
inspect.Analyzer,
},
}
var typePath string // -type flag
func init() {
Analyzer.Flags.StringVar(&typePath, "type", typePath, "`path/to/pkg.type` to check for")
}
func lookupType(pkg *types.Package, typePath string) (types.Object, error) {
pos := strings.LastIndex(typePath, ".")
if pos == -1 {
return nil, fmt.Errorf("invalid type path: %s", typePath)
}
pkgPath := typePath[:pos]
typeName := typePath[pos+1:]
visited := map[*types.Package]bool{}
queue := []*types.Package{pkg}
for len(queue) > 0 {
pkg := queue[0]
queue = queue[1:]
if visited[pkg] {
continue
}
visited[pkg] = true
queue = append(queue, pkg.Imports()...)
if pkg.Path() != pkgPath {
continue
}
typ := pkg.Scope().Lookup(typeName)
if typ != nil {
return typ, nil
}
}
return nil, nil
}
func assinableTo(t1, t2 types.Type) bool {
if bt, ok := t1.(*types.Basic); ok && bt.Kind() == types.Invalid {
return false
}
return types.AssignableTo(t1, t2)
}
func baseIdent(node ast.Node) *ast.Ident {
switch node := node.(type) {
case *ast.Ident:
return node
case *ast.SelectorExpr:
return baseIdent(node.X)
default:
return nil
}
}
func run(pass *analysis.Pass) (interface{}, error) {
targetType, err := lookupType(pass.Pkg, typePath)
if err != nil {
return nil, err
}
if targetType == nil {
// fail silently
return nil, nil
}
ins := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
ins.WithStack([]ast.Node{(*ast.Ident)(nil)}, func(node ast.Node, push bool, stack []ast.Node) bool {
if !push {
return false
}
foundIdent := node.(*ast.Ident)
foundIdentObj, ok := pass.TypesInfo.Uses[foundIdent].(*types.Var)
if !ok {
return true
}
if assinableTo(foundIdentObj.Type(), targetType.Type()) {
// node is a variable of the targetType
} else {
return true
}
var (
foundExpr ast.Expr = foundIdent
foundScope = foundIdentObj.Parent()
)
if foundIdentObj.IsField() {
for i := range stack {
if expr, ok := stack[len(stack)-1-i].(*ast.SelectorExpr); ok && expr.Sel == foundIdent {
if base := baseIdent(expr); base != nil {
foundExpr = expr
foundScope = pass.TypesInfo.Uses[base].Parent()
break
}
return true
}
if kv, ok := stack[len(stack)-1-i].(*ast.KeyValueExpr); ok && kv.Key == foundIdent {
// node is K in Struct{ K: ... }
return true
}
}
}
thisScope := pass.Pkg.Scope().Innermost(foundIdent.Pos())
if foundScope == thisScope {
return true
}
for thisScope != nil && thisScope != foundScope && thisScope != types.Universe {
for _, name := range thisScope.Names() {
objInScope := thisScope.Lookup(name)
if !assinableTo(objInScope.Type(), targetType.Type()) {
continue
}
pass.Report(
analysis.Diagnostic{
Pos: foundExpr.Pos(),
End: foundExpr.End(),
Message: fmt.Sprintf(
"using %s from the outer scope but %s is defined inner at %s",
types.ExprString(foundExpr),
objInScope.Name(),
pass.Fset.Position(objInScope.Pos()),
),
SuggestedFixes: []analysis.SuggestedFix{
{
Message: "use inner value of the same type",
TextEdits: []analysis.TextEdit{
{
Pos: foundExpr.Pos(),
End: foundExpr.End(),
NewText: []byte(objInScope.Name()),
},
},
},
},
},
)
return true
}
thisScope = thisScope.Parent()
}
return true
})
return nil, nil
}