-
Notifications
You must be signed in to change notification settings - Fork 3
/
safe_expr.go
73 lines (67 loc) · 2 KB
/
safe_expr.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
package typep
import (
"go/ast"
"go/token"
"go/types"
)
// SideEffectFree reports whether expr is softly safe expression and contains
// no significant side-effects. As opposed to strictly safe expressions,
// soft safe expressions permit some forms of side-effects, like
// panic possibility during indexing or nil pointer dereference.
//
// Uses types info to determine type conversion expressions that
// are the only permitted kinds of call expressions.
// Note that is does not check whether called function really
// has any side effects. The analysis is very conservative.
func SideEffectFree(info *types.Info, expr ast.Expr) bool {
// This list switch is not comprehensive and uses
// whitelist to be on the conservative side.
// Can be extended as needed.
if expr == nil {
return true
}
switch expr := expr.(type) {
case *ast.StarExpr:
return SideEffectFree(info, expr.X)
case *ast.BinaryExpr:
return SideEffectFree(info, expr.X) &&
SideEffectFree(info, expr.Y)
case *ast.UnaryExpr:
return expr.Op != token.ARROW &&
SideEffectFree(info, expr.X)
case *ast.BasicLit, *ast.Ident:
return true
case *ast.SliceExpr:
return SideEffectFree(info, expr.X) &&
SideEffectFree(info, expr.Low) &&
SideEffectFree(info, expr.High) &&
SideEffectFree(info, expr.Max)
case *ast.IndexExpr:
return SideEffectFree(info, expr.X) &&
SideEffectFree(info, expr.Index)
case *ast.SelectorExpr:
return SideEffectFree(info, expr.X)
case *ast.ParenExpr:
return SideEffectFree(info, expr.X)
case *ast.TypeAssertExpr:
return SideEffectFree(info, expr.X)
case *ast.CompositeLit:
return SideEffectFreeList(info, expr.Elts)
case *ast.CallExpr:
return IsTypeExpr(info, expr.Fun) &&
SideEffectFreeList(info, expr.Args)
default:
return false
}
}
// SideEffectFreeList reports whether every expr in list is safe.
//
// See SideEffectFree.
func SideEffectFreeList(info *types.Info, list []ast.Expr) bool {
for _, expr := range list {
if !SideEffectFree(info, expr) {
return false
}
}
return true
}