-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
ast.go
85 lines (76 loc) · 1.49 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
package main
import (
"bytes"
"fmt"
"go/ast"
"go/format"
"go/token"
)
func GetBlock(node ast.Node) *[]ast.Stmt {
switch n := node.(type) {
case *ast.BlockStmt:
return &n.List
case *ast.CaseClause:
return &n.Body
}
return nil
}
type NodeTree struct {
Node ast.Node
Parent *NodeTree
Callback func(tree *NodeTree) bool
}
func (tree *NodeTree) Visit(node ast.Node) ast.Visitor {
if node == nil {
return nil
}
sub := &NodeTree{node, tree, tree.Callback}
if tree.Callback(sub) {
return sub
}
return nil
}
func (tree *NodeTree) SearchParent(callback func(*NodeTree) bool) chan *NodeTree {
ret := make(chan *NodeTree)
go func() {
cur := tree
for cur.Parent != nil {
cur = cur.Parent
if callback(cur) {
ret <- cur
}
}
close(ret)
}()
return ret
}
func (tree *NodeTree) Print(fset *token.FileSet) {
bytes, err := CodeBytes(fset, tree.Node)
if err != nil {
panic(err)
}
fmt.Printf("%s\n", bytes)
}
func WalkAst(node ast.Node, callback func(tree *NodeTree) bool) {
ast.Walk(&NodeTree{node, nil, callback}, node)
}
func CodeBytes(fset *token.FileSet, node interface{}) ([]byte, error) {
var buf bytes.Buffer
if err := format.Node(&buf, fset, node); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func FilterAst(top ast.Node, callback func(n ast.Node) bool) chan *NodeTree {
ret := make(chan *NodeTree)
go func() {
WalkAst(top, func(n *NodeTree) bool {
if callback(n.Node) {
ret <- n
}
return true
})
close(ret)
}()
return ret
}