| 1 |
package js |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"regexp" |
| 6 |
"testing" |
| 7 |
|
| 8 |
"github.com/tdewolff/parse/v2" |
| 9 |
"github.com/tdewolff/test" |
| 10 |
) |
| 11 |
|
| 12 |
type walker struct{} |
| 13 |
|
| 14 |
func (w *walker) Enter(n INode) IVisitor { |
| 15 |
switch n := n.(type) { |
| 16 |
case *Var: |
| 17 |
if bytes.Equal(n.Data, []byte("x")) { |
| 18 |
n.Data = []byte("obj") |
| 19 |
} |
| 20 |
} |
| 21 |
|
| 22 |
return w |
| 23 |
} |
| 24 |
|
| 25 |
func (w *walker) Exit(n INode) {} |
| 26 |
|
| 27 |
func TestWalk(t *testing.T) { |
| 28 |
js := ` |
| 29 |
if (true) { |
| 30 |
for (i = 0; i < 1; i++) { |
| 31 |
x.y = i |
| 32 |
} |
| 33 |
}` |
| 34 |
|
| 35 |
ast, err := Parse(parse.NewInputString(js), Options{}) |
| 36 |
if err != nil { |
| 37 |
t.Fatal(err) |
| 38 |
} |
| 39 |
|
| 40 |
Walk(&walker{}, ast) |
| 41 |
|
| 42 |
re := regexp.MustCompile("\n *") |
| 43 |
t.Run("TestWalk", func(t *testing.T) { |
| 44 |
src := ast.JSString() |
| 45 |
src = re.ReplaceAllString(src, " ") |
| 46 |
test.String(t, src, "if (true) { for (i = 0; i < 1; i++) { obj.y = i; } }") |
| 47 |
}) |
| 48 |
} |
| 49 |
|
| 50 |
func TestWalkNilNode(t *testing.T) { |
| 51 |
nodes := []INode{ |
| 52 |
&AST{}, |
| 53 |
&Var{}, |
| 54 |
&BlockStmt{}, |
| 55 |
&EmptyStmt{}, |
| 56 |
&ExprStmt{}, |
| 57 |
&IfStmt{}, |
| 58 |
&DoWhileStmt{}, |
| 59 |
&WhileStmt{}, |
| 60 |
&ForStmt{}, |
| 61 |
&ForInStmt{}, |
| 62 |
&ForOfStmt{}, |
| 63 |
&CaseClause{}, |
| 64 |
&SwitchStmt{}, |
| 65 |
&BranchStmt{}, |
| 66 |
&ReturnStmt{}, |
| 67 |
&WithStmt{}, |
| 68 |
&LabelledStmt{}, |
| 69 |
&ThrowStmt{}, |
| 70 |
&TryStmt{}, |
| 71 |
&DebuggerStmt{}, |
| 72 |
&Alias{}, |
| 73 |
&ImportStmt{}, |
| 74 |
&ExportStmt{}, |
| 75 |
&DirectivePrologueStmt{}, |
| 76 |
&PropertyName{}, |
| 77 |
&BindingArray{}, |
| 78 |
&BindingObjectItem{}, |
| 79 |
&BindingObject{}, |
| 80 |
&BindingElement{}, |
| 81 |
&VarDecl{}, |
| 82 |
&Params{}, |
| 83 |
&FuncDecl{}, |
| 84 |
&MethodDecl{}, |
| 85 |
&Field{}, |
| 86 |
&ClassElement{}, |
| 87 |
&ClassDecl{}, |
| 88 |
&LiteralExpr{}, |
| 89 |
&Element{}, |
| 90 |
&ArrayExpr{}, |
| 91 |
&Property{}, |
| 92 |
&ObjectExpr{}, |
| 93 |
&TemplatePart{}, |
| 94 |
&TemplateExpr{}, |
| 95 |
&GroupExpr{}, |
| 96 |
&IndexExpr{}, |
| 97 |
&DotExpr{}, |
| 98 |
&NewTargetExpr{}, |
| 99 |
&ImportMetaExpr{}, |
| 100 |
&Arg{}, |
| 101 |
&Args{}, |
| 102 |
&NewExpr{}, |
| 103 |
&CallExpr{}, |
| 104 |
&UnaryExpr{}, |
| 105 |
&BinaryExpr{}, |
| 106 |
&CondExpr{}, |
| 107 |
&YieldExpr{}, |
| 108 |
&ArrowFunc{}, |
| 109 |
} |
| 110 |
|
| 111 |
t.Run("TestWalkNilNode", func(t *testing.T) { |
| 112 |
for _, n := range nodes { |
| 113 |
Walk(&walker{}, n) |
| 114 |
} |
| 115 |
}) |
| 116 |
} |