Skip to content

Commit d823384

Browse files
committed
Added an utility that allows walking depth-first easily.
For example: w.with_walkers({ "function": function() { var node = w.dive(this); // apply other_walkers to subnodes var transformed_node = further_transform(node); return transformed_node; }, ... // other_walkers here }, ...); (fixes #213)
1 parent d891e2d commit d823384

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

lib/process.js

+12
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,17 @@ function ast_walker() {
223223
}
224224
};
225225

226+
function dive(ast) {
227+
if (ast == null)
228+
return null;
229+
try {
230+
stack.push(ast);
231+
return walkers[ast[0]].apply(ast, ast.slice(1));
232+
} finally {
233+
stack.pop();
234+
}
235+
};
236+
226237
function with_walkers(walkers, cont){
227238
var save = {}, i;
228239
for (i in walkers) if (HOP(walkers, i)) {
@@ -239,6 +250,7 @@ function ast_walker() {
239250

240251
return {
241252
walk: walk,
253+
dive: dive,
242254
with_walkers: with_walkers,
243255
parent: function() {
244256
return stack[stack.length - 2]; // last one is current node

tmp/test.js

+14
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,20 @@ var ast = jsp.parse(code);
1111

1212
ast = pro.ast_lift_variables(ast);
1313

14+
var w = pro.ast_walker();
15+
ast = w.with_walkers({
16+
"function": function() {
17+
var node = w.dive(this); // walk depth first
18+
console.log(pro.gen_code(node, { beautify: true }));
19+
return node;
20+
},
21+
"name": function(name) {
22+
return [ this[0], "X" ];
23+
}
24+
}, function(){
25+
return w.walk(ast);
26+
});
27+
1428
console.log(pro.gen_code(ast, {
1529
beautify: true
1630
}));

0 commit comments

Comments
 (0)