Debian Codegraph @

ast/walk_example_test.go

raw symbols SCIP
1 package ast_test
2
3 import (
4 "fmt"
5 "log"
6
7 "github.com/robertkrimen/otto/ast"
8 "github.com/robertkrimen/otto/file"
9 "github.com/robertkrimen/otto/parser"
10 )
11
12 type walkExample struct {
13 source string
14 shift file.Idx
15 }
16
17 func (w *walkExample) Enter(n ast.Node) ast.Visitor {
18 if id, ok := n.(*ast.Identifier); ok && id != nil {
19 idx := n.Idx0() + w.shift - 1
20 s := w.source[:idx] + "new_" + w.source[idx:]
21 w.source = s
22 w.shift += 4
23 }
24 if v, ok := n.(*ast.VariableExpression); ok && v != nil {
25 idx := n.Idx0() + w.shift - 1
26 s := w.source[:idx] + "varnew_" + w.source[idx:]
27 w.source = s
28 w.shift += 7
29 }
30
31 return w
32 }
33
34 func (w *walkExample) Exit(n ast.Node) {
35 // AST node n has had all its children walked. Pop it out of your
36 // stack, or do whatever processing you need to do, if any.
37 }
38
39 func ExampleVisitor_codeRewrite() {
40 source := `var b = function() {test(); try {} catch(e) {} var test = "test(); var test = 1"} // test`
41 program, err := parser.ParseFile(nil, "", source, 0)
42 if err != nil {
43 log.Fatal(err)
44 }
45
46 w := &walkExample{source: source}
47
48 ast.Walk(w, program)
49
50 fmt.Println(w.source)
51 // Output: var varnew_b = function() {new_test(); try {} catch(new_e) {} var varnew_test = "test(); var test = 1"} // test
52 }