Skip to content

Commit f7352f2

Browse files
committed
Add visitor docs
1 parent c9e9dc8 commit f7352f2

File tree

2 files changed

+35
-7
lines changed

2 files changed

+35
-7
lines changed

ast/visitor_test.go

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,21 +8,21 @@ import (
88

99
type visitor struct {
1010
ast.BaseVisitor
11-
lastSeenInteger int64
11+
identifiers []string
1212
}
1313

14-
func (v *visitor) IntegerNode(node *ast.IntegerNode) {
15-
v.lastSeenInteger = node.Value
14+
func (v *visitor) IdentifierNode(node *ast.IdentifierNode) {
15+
v.identifiers = append(v.identifiers, node.Value)
1616
}
1717

1818
func TestWalk(t *testing.T) {
1919
node := &ast.BinaryNode{
20-
Operator: "",
21-
Left: &ast.IntegerNode{Value: 12},
22-
Right: &ast.IntegerNode{Value: 42},
20+
Operator: "+",
21+
Left: &ast.IdentifierNode{Value: "foo"},
22+
Right: &ast.IdentifierNode{Value: "bar"},
2323
}
2424

2525
visitor := &visitor{}
2626
ast.Walk(node, visitor)
27-
assert.Equal(t, int64(42), visitor.lastSeenInteger)
27+
assert.Equal(t, []string{"foo", "bar"}, visitor.identifiers)
2828
}

docs/README.md

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,3 +190,31 @@ Compiled program is possible to marshal and unmarshal before running.
190190

191191
fmt.Printf("%v", output) // outputs 3
192192
```
193+
194+
## Visitor
195+
196+
[ast](https://godoc.org/github.com/antonmedv/expr/ast) package provides `Visitor` interface and `BaseVisitor` implementation.
197+
You can use it for traveling ast tree of compiled program.
198+
199+
For example if you want to collect all variable names:
200+
201+
```go
202+
import "github.com/antonmedv/expr/ast"
203+
204+
type visitor struct {
205+
ast.BaseVisitor
206+
identifiers []string
207+
}
208+
209+
func (v *visitor) IdentifierNode(node *ast.IdentifierNode) {
210+
v.identifiers = append(v.identifiers, node.Value)
211+
}
212+
213+
program, err := expr.Compile("foo + bar", expr.Env(env))
214+
215+
visitor := &visitor{}
216+
ast.Walk(node, visitor)
217+
218+
fmt.Printf("%v", visitor.identifiers) // outputs [foo bar]
219+
220+
```

0 commit comments

Comments
 (0)