forked from thingio/kapacitor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
walk.go
70 lines (68 loc) · 1.49 KB
/
walk.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
package ast
import "errors"
// Walk calls f on all nodes reachable from the root node.
// The node returned will replace the node provided within the AST.
// Returning an error from f will stop the walking process and f will not be called on any other nodes.
func Walk(root Node, f func(n Node) (Node, error)) (Node, error) {
replacement, err := f(root)
if err != nil {
return nil, err
}
switch node := replacement.(type) {
case *LambdaNode:
r, err := Walk(node.Expression, f)
if err != nil {
return nil, err
}
node.Expression = r
case *UnaryNode:
r, err := Walk(node.Node, f)
if err != nil {
return nil, err
}
node.Node = r
case *BinaryNode:
r, err := Walk(node.Left, f)
if err != nil {
return nil, err
}
node.Left = r
r, err = Walk(node.Right, f)
if err != nil {
return nil, err
}
node.Right = r
case *DeclarationNode:
r, err := Walk(node.Left, f)
if err != nil {
return nil, err
}
ident, ok := r.(*IdentifierNode)
if !ok {
return nil, errors.New("declaration node must always have an IdentifierNode")
}
node.Left = ident
r, err = Walk(node.Right, f)
if err != nil {
return nil, err
}
node.Right = r
case *FunctionNode:
for i := range node.Args {
r, err := Walk(node.Args[i], f)
if err != nil {
return nil, err
}
node.Args[i] = r
}
case *ProgramNode:
for i := range node.Nodes {
r, err := Walk(node.Nodes[i], f)
if err != nil {
return nil, err
}
node.Nodes[i] = r
}
}
return replacement, nil
}