estraverse icon indicating copy to clipboard operation
estraverse copied to clipboard

Traverse down to new nodes in .replace()

Open rstacruz opened this issue 11 years ago • 2 comments

When using estraverse.replace(), and I want to make new nodes, what's the best way to traverse down those new nodes?

For instance:

estraverse.replace(tree, {
  enter: function (node, parent) {
    if (/* something */) {
      var newStatement = { type: 'FunctionDeclaration', body: /* ... */ };
      parent.body.push(newStatement);
     // ...recurse into newStatement
    }
  }
});

...currently, I'm just invoking estraverse.replace(newroot, { ... }) again with the same enter/exits, but I was wondering if there would be strange side effects to this of if there would be better ways.

rstacruz avatar Sep 02 '14 05:09 rstacruz

I don't think you should modify parent from child's traversal. Better to do if (...) from your parent BlockStatement, in that case you will definitely have no side effects + will get traversal over new nodes for free.

RReverser avatar Oct 17 '14 10:10 RReverser

I have a similar problem, I do replace on a node (in leave), but want to do a traversal on the replacement node too.

I tried pushing back to worklist and leavelist, but I am getting problems with escope then.

exander77 avatar May 20 '16 14:05 exander77