millermedeiros / rocambole-token

Helpers for rocambole AST token manipulation
5 stars 1 forks source link

`remove()` doesn't seem to work on `node`es #2

Closed sindresorhus closed 10 years ago

sindresorhus commented 10 years ago

I tried this:

var rocambole = require('rocambole');
var token = require('rocambole-token');

console.log(rocambole.moonwalk(rocambole.parse('function foo(){debugger;}'), function (node) {
    if (node.type === 'DebuggerStatement') {
        token.remove(node);
    }
}).toString());

//=> function foo(){debugger;}

I would have expected it to remove the debugger statement.

However, this seems to work:

var rocambole = require('rocambole');
var token = require('rocambole-token');

console.log(rocambole.moonwalk(rocambole.parse('function foo(){debugger;}'), function (node) {
    if (node.type === 'DebuggerStatement') {
        var currentToken = node.startToken;

        while (currentToken !== node.endToken.next) {
            token.remove(currentToken);
            currentToken = currentToken.next;
        }
    }
}).toString());

//=> function foo(){}

But manual labor isn't fun.

millermedeiros commented 10 years ago

the remove() on rocambole-token only removes tokens. the rocambole-node module will have methods for manipulating the AST itself but it still doesn't have a remove method.

a simple way to remove all the tokens from a node is to: token.eachInBetween(node.startToken, node.endToken, token.remove)

millermedeiros commented 10 years ago

another way would be to remove the links like:

function removeNodeContent(node){
  var prev = node.startToken.prev;
  var next = node.endToken.next;
  node.startToken = prev;
  prev.next = next;
  next.prev = prev;
  node.endToken = next;
}

that way the ast.toString would not include any content from the node (even tho it would still be part of the AST).