File tree 2 files changed +35
-7
lines changed
2 files changed +35
-7
lines changed Original file line number Diff line number Diff line change @@ -8,21 +8,21 @@ import (
8
8
9
9
type visitor struct {
10
10
ast.BaseVisitor
11
- lastSeenInteger int64
11
+ identifiers [] string
12
12
}
13
13
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 )
16
16
}
17
17
18
18
func TestWalk (t * testing.T ) {
19
19
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" },
23
23
}
24
24
25
25
visitor := & visitor {}
26
26
ast .Walk (node , visitor )
27
- assert .Equal (t , int64 ( 42 ), visitor .lastSeenInteger )
27
+ assert .Equal (t , [] string { "foo" , "bar" }, visitor .identifiers )
28
28
}
Original file line number Diff line number Diff line change @@ -190,3 +190,31 @@ Compiled program is possible to marshal and unmarshal before running.
190
190
191
191
fmt.Printf (" %v " , output) // outputs 3
192
192
```
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
+ ```
You can’t perform that action at this time.
0 commit comments