-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathast.go
109 lines (91 loc) · 1.77 KB
/
ast.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
package knife
import (
"fmt"
"go/ast"
"go/constant"
"go/token"
"go/types"
)
type ASTNode struct {
Node ast.Node
Scope *Scope
Type *Type
Name string
Object Object
Value constant.Value
}
var _ fmt.Stringer = (*ASTNode)(nil)
func (n *ASTNode) Pos() token.Pos {
return n.Node.Pos()
}
func (n *ASTNode) String() string {
return fmt.Sprintf("%T", n.Node)
}
func (n *ASTNode) BoolVal() bool {
return constant.BoolVal(n.Value)
}
func (n *ASTNode) StringVal() string {
return constant.StringVal(n.Value)
}
func (n *ASTNode) Float32Val() float32 {
v, ok := constant.Float32Val(n.Value)
if !ok {
panic("unkown kind")
}
return v
}
func (n *ASTNode) Float64Val() float64 {
v, ok := constant.Float64Val(n.Value)
if !ok {
panic("unkown kind")
}
return v
}
func (n *ASTNode) Int64Val() int64 {
v, ok := constant.Int64Val(n.Value)
if !ok {
panic("unkown kind")
}
return v
}
func (n *ASTNode) Uint64Val() uint64 {
v, ok := constant.Uint64Val(n.Value)
if !ok {
panic("unkown kind")
}
return v
}
func (n *ASTNode) Val() any {
return constant.Val(n.Value)
}
func NewASTNode(typesInfo *types.Info, n ast.Node) *ASTNode {
if n == nil {
return nil
}
v, _ := cache.Load(n)
cached, _ := v.(*ASTNode)
if cached != nil {
return cached
}
var nn ASTNode
cache.Store(n, &nn)
nn.Node = n
nn.Scope = NewScope(typesInfo.Scopes[n])
if id, ok := n.(*ast.Ident); ok {
obj := typesInfo.ObjectOf(id)
if obj != nil {
nn.Object = NewObject(obj)
nn.Name = obj.Name()
if scopeHolder, ok := obj.(interface{ Scope() *types.Scope }); ok {
nn.Scope = NewScope(scopeHolder.Scope())
}
}
}
if expr, ok := n.(ast.Expr); ok {
nn.Type = NewType(typesInfo.TypeOf(expr))
if tv, ok := typesInfo.Types[expr]; ok {
nn.Value = tv.Value
}
}
return &nn
}