-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheck.go
349 lines (322 loc) · 7.92 KB
/
check.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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
package readonly
import (
"bytes"
"go/ast"
"go/printer"
"go/token"
"go/types"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/ast/inspector"
"golang.org/x/tools/go/packages"
"path/filepath"
)
func initTypes(pkgs []*packages.Package) []*inspector.Inspector {
allPackages = pkgs
funcTypes = make(map[token.Pos]*funcInfo)
moduleDir = pkgs[0].Module.Dir
var inspectors []*inspector.Inspector
for _, pkg := range pkgs {
i := inspector.New(pkg.Syntax)
inspectors = append(inspectors, i)
i.Preorder([]ast.Node{&ast.FuncDecl{}}, func(n ast.Node) {
fd := n.(*ast.FuncDecl)
object := pkg.TypesInfo.Defs[fd.Name].(*types.Func)
info := &funcInfo{decl: fd, fullName: object.FullName()}
info.calcDecl()
funcTypes[fd.Name.Pos()] = info
})
}
for i := 0; i < 100; i++ {
changed := false
for _, info := range funcTypes {
old := info.roMask
info.calcBody()
if old != info.roMask {
changed = true
}
}
if !changed {
break
}
}
return inspectors
}
func checkStmt(pass *analysis.Pass, stmt ast.Stmt) {
fset := pass.Fset
ast.Inspect(stmt, func(node ast.Node) bool {
if expr, ok := node.(ast.Expr); ok {
checkExpr(pass, expr)
}
return true
})
switch e := stmt.(type) {
case *ast.IncDecStmt:
if getExprReadonlyFlag(e.X) > 0 {
var buf bytes.Buffer
_ = printer.Fprint(&buf, fset, e.X)
pass.Reportf(e.X.Pos(), `variable "%s" cannot be modify`, buf.String())
}
case *ast.AssignStmt:
assign, lhs, rhs := collectAssignStmt(e)
lhsFlag, skipFlag := collectLhsFlag(lhs)
rhsFlag := collectRhsFlag(rhs, skipFlag)
checkAssign(assign, lhs, rhs, lhsFlag, rhsFlag, skipFlag, pass)
case *ast.DeclStmt:
decl := e.Decl.(*ast.GenDecl)
for _, spec := range decl.Specs {
valueSpec, ok := spec.(*ast.ValueSpec)
if !ok {
continue
}
assign, lhs, rhs := collectValueSpec(valueSpec)
lhsFlag, skipFlag := collectLhsFlag(lhs)
rhsFlag := collectRhsFlag(rhs, skipFlag)
checkAssign(assign, lhs, rhs, lhsFlag, rhsFlag, skipFlag, pass)
}
case *ast.RangeStmt:
var lhs, rhs []ast.Expr
lhs = append(lhs, e.Key, e.Value)
rhs = append(rhs, e.X)
lhsFlag, skipFlag := collectLhsFlag(lhs)
rhsFlag := collectRhsFlag(rhs, skipFlag)
rhsFlag |= rhsFlag << 1
checkAssign(false, lhs, rhs, lhsFlag, rhsFlag, skipFlag, pass)
}
}
func checkExpr(pass *analysis.Pass, expr ast.Expr) {
fset := pass.Fset
roFlag := false
unwrapCheckExpr(expr, func(expr ast.Expr) {
if getExprReadonlyFlag(expr) > 0 {
roFlag = true
} else if roFlag {
ident, ok := expr.(*ast.Ident)
if !ok {
return
}
_, ok = funcTypes[getNamePos(ident)]
if !ok {
return
}
var buf bytes.Buffer
_ = printer.Fprint(&buf, fset, expr)
pass.Reportf(expr.Pos(), `variable "%s" cannot call non readonly method`, buf.String())
}
})
}
func checkAssign(isAssign bool, lhs, rhs []ast.Expr, lhsFlag, rhsFlag uint64, skipFlag uint64, pass *analysis.Pass) {
fset := pass.Fset
skipIndexes := make([]bool, len(lhs))
for i := range lhs {
if skipFlag&(1<<i) != 0 {
skipIndexes[i] = true
}
}
if isAssign {
for i := 0; i < len(lhs); i++ {
if skipIndexes[i] {
continue
}
if lhsFlag&(1<<i) != 0 {
skipIndexes[i] = true
var buf bytes.Buffer
_ = printer.Fprint(&buf, fset, lhs[i])
pass.Reportf(lhs[i].Pos(), `variable "%s" cannot be assigned`, buf.String())
}
}
}
for i := 0; i < len(lhs); i++ {
if skipIndexes[i] {
continue
}
// 如果右值为非只读,或者左值是只读,则跳过
if rhsFlag&(1<<i) == 0 || lhsFlag&(1<<i) != 0 {
continue
}
var rhsBuf, lhsBuf bytes.Buffer
_ = printer.Fprint(&lhsBuf, fset, lhs[i])
var rhsPos token.Pos
if len(rhs) == len(lhs) {
rhsPos = rhs[i].Pos()
_ = printer.Fprint(&rhsBuf, fset, rhs[i])
} else {
rhsPos = rhs[0].Pos()
_ = printer.Fprint(&rhsBuf, fset, rhs[0])
}
pass.Reportf(lhs[i].Pos(), `variable "%s" cannot assigned with
readonly variable "%s" at %v `, lhsBuf.String(), rhsBuf.String(), getPosition(fset, rhsPos))
}
}
// collectLhsFlag 获取左值的只读标记和跳过标记
// 左值和右值不一样的地方在于,左值类型限制更严格,右值更随意一些
func collectLhsFlag(lhs []ast.Expr) (roFlag uint64, skipFlag uint64) {
/*
左值可能为这些情况
变量 *ast.Ident a = 10
指针解引用 *ast.StarExpr *p = 20
数组或切片的元素 *ast.IndexExpr arr[0] = 5
结构体字段 *ast.SelectorExpr person.name = "John"
字典(映射)元素 *ast.IndexExpr m["key"] = "value"
接口变量的底层实现字段 *ast.SelectorExpr w.Write([]byte("Hello"))
*/
for i, expr := range lhs {
if ident, ok := expr.(*ast.Ident); ok && ident.Name == "_" {
skipFlag |= 1 << i
continue
}
t := getExprType(expr)
if _, ok := t.(*types.Basic); ok {
skipFlag |= 1 << i
continue
}
tmp := getExprReadonlyFlag(expr)
if tmp > 0 {
roFlag |= 1 << i
}
}
return
}
func collectRhsFlag(rhs []ast.Expr, skipFlag uint64) uint64 {
flag := uint64(0)
for i, expr := range rhs {
if skipFlag&(1<<i) != 0 {
continue
}
tmp := getExprReadonlyFlag(expr)
if tmp > 0 {
flag |= 1 << i
}
}
return flag
}
func collectAssignStmt(stmt *ast.AssignStmt) (isAssign bool, lhs []ast.Expr, rhs []ast.Expr) {
return stmt.Tok == token.ASSIGN, stmt.Lhs, stmt.Rhs
}
func collectValueSpec(spec *ast.ValueSpec) (isAssign bool, lhs []ast.Expr, rhs []ast.Expr) {
isAssign = false
for _, v := range spec.Names {
lhs = append(lhs, v)
}
rhs = spec.Values
return
}
func unwrapCheckExpr(expr ast.Expr, f func(ast.Expr)) {
cur := expr
for cur != nil {
switch e := cur.(type) {
case *ast.Ident:
f(e)
cur = nil
case *ast.StarExpr:
cur = e.X
case *ast.ParenExpr:
cur = e.X
case *ast.UnaryExpr:
cur = e.X
case *ast.IndexExpr:
unwrapCheckExpr(e.Index, f)
cur = e.X
case *ast.IndexListExpr:
for _, v := range e.Indices {
unwrapCheckExpr(v, f)
}
cur = e.X
case *ast.CallExpr:
for _, v := range e.Args {
unwrapCheckExpr(v, f)
}
unwrapCheckExpr(e.Fun, f)
cur = nil
case *ast.SelectorExpr:
unwrapCheckExpr(e.X, f)
f(e.Sel)
cur = nil
default:
cur = nil
}
if cur != nil {
f(cur)
}
}
}
func getExprReadonlyFlag(expr ast.Expr) uint64 {
switch t := expr.(type) {
case *ast.Ident:
if checkName(t.Name) {
return 1
}
pos := getNamePos(t)
if info, ok := funcTypes[pos]; ok {
return info.getResultFlag()
}
return 0
case *ast.SelectorExpr:
return getSelectorRoFlag(t)
case *ast.CallExpr:
return getRoFuncResultFlag(t)
case *ast.StarExpr:
return getExprReadonlyFlag(t.X)
case *ast.IndexExpr:
return getExprReadonlyFlag(t.X)
case *ast.IndexListExpr:
return getExprReadonlyFlag(t.X)
case *ast.UnaryExpr:
return getExprReadonlyFlag(t.X)
default:
return 0
}
}
func getSelectorRoFlag(sel *ast.SelectorExpr) uint64 {
flag := getExprReadonlyFlag(sel.Sel)
if flag > 0 {
return flag
}
flag = getExprReadonlyFlag(sel.X)
if flag > 0 {
return 1
}
return 0
}
func getRoFuncResultFlag(call *ast.CallExpr) uint64 {
ident, ok := call.Fun.(*ast.Ident)
if ok {
pos := getNamePos(ident)
info, ok := funcTypes[pos]
// 可能是类型强转
if !ok {
return 0
}
return info.getResultFlag()
}
return getExprReadonlyFlag(call.Fun)
}
func getNamePos(ident *ast.Ident) token.Pos {
for _, p := range allPackages {
if obj, ok := p.TypesInfo.Uses[ident]; ok {
return obj.Pos()
}
if obj, ok := p.TypesInfo.Defs[ident]; ok && obj != nil {
return obj.Pos()
}
}
return token.NoPos
}
func getExprType(expr ast.Expr) types.Type {
for _, p := range allPackages {
if obj, ok := p.TypesInfo.Types[expr]; ok {
return obj.Type
}
}
return nil
}
func checkName(name string) bool {
l := len(roPrefix)
return name == roPrefix ||
(len(name) > l && name[:l] == roPrefix && name[l] >= 'A' && name[l] <= 'Z')
}
func getPosition(fset *token.FileSet, pos token.Pos) token.Position {
p := fset.Position(pos)
shortPath, _ := filepath.Rel(moduleDir, p.Filename)
p.Filename = shortPath
return p
}