Skip to content

Commit 579de74

Browse files
committed
Add ast.Find
1 parent 35bdb68 commit 579de74

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

ast/find.go

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package ast
2+
3+
func Find(node Node, fn func(node Node) bool) Node {
4+
v := &finder{fn: fn}
5+
Walk(&node, v)
6+
return v.node
7+
}
8+
9+
type finder struct {
10+
node Node
11+
fn func(node Node) bool
12+
}
13+
14+
func (f *finder) Visit(node *Node) {
15+
if f.fn(*node) {
16+
f.node = *node
17+
}
18+
}

ast/find_test.go

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package ast_test
2+
3+
import (
4+
"testing"
5+
6+
"github.com/expr-lang/expr/internal/testify/require"
7+
8+
"github.com/expr-lang/expr/ast"
9+
)
10+
11+
func TestFind(t *testing.T) {
12+
left := &ast.IdentifierNode{
13+
Value: "a",
14+
}
15+
var root ast.Node = &ast.BinaryNode{
16+
Operator: "+",
17+
Left: left,
18+
Right: &ast.IdentifierNode{
19+
Value: "b",
20+
},
21+
}
22+
23+
x := ast.Find(root, func(node ast.Node) bool {
24+
if n, ok := node.(*ast.IdentifierNode); ok {
25+
return n.Value == "a"
26+
}
27+
return false
28+
})
29+
30+
require.Equal(t, left, x)
31+
}

0 commit comments

Comments
 (0)