kevinushey / sourcetools

Tools for reading, tokenizing, and parsing R code.
MIT License
77 stars 3 forks source link

refactoring support #8

Open kevinushey opened 8 years ago

kevinushey commented 8 years ago

Thinking out loud:

  1. Need a function that returns a set of 'actions'; ie, mutations to the document that need to be made. These will effectively be replacements of a certain range, e.g. to rename an identifier, or to move a comment (delete code in one range, add in other range). Should ensure these are non-overlapping, and returned in reverse order so it's easy to apply sequentially.
  2. Use something like a visitor pattern to generate actions.

Pseudo-code that would be nice to write:

// get AST
std::string code("x <- x + 1");
auto AST = parse(code);

// prepare refactor
std::vector<Visitor> visitors;
std::vector<Action> actions;

// add a visitor that renames 'foo' to 'bar'
visitors.push_back([](const Node& node, std::vector<Action>* pActions) {
    if (node.token.contentsEqual("foo")) {
        pActions->push_back(token.range(), "bar");
    }
});

// apply visitors
apply(AST, visitors, &actions);

// do something with resulting actions
return actions;