babel-plugin-recursive-tail-calls
Version:
A babel plugin for performing tail call optimization in recursive functions.
35 lines (34 loc) • 1.09 kB
JavaScript
import { isRecCall } from "./utils.js";
/**
* Babel visitor to find tail recursion in `ReturnStatement`s.
* Descends down `LogicalExpression`s and `ConditionalExpression`s
* to find recursive calls in tail position.
* Sets `found` on state to `true` if recursion is found.
*/
export const tailRecursionFinder = {
enter(path) {
if (path.isCallExpression()) {
this.found = isRecCall(path, this.functionIdentifier);
if (this.found)
path.stop();
}
else if (path.isLogicalExpression())
path.skipKey("left");
else if (path.isConditionalExpression())
path.skipKey("test");
else
path.skip();
},
};
/**
* Use `tailRecursionFinder` to look for calls to `functionIdentifier` in `path`.
*/
export function findRecursion(path, functionIdentifier) {
const state = {
found: false,
functionIdentifier,
};
// traverse omits the current node, traverse parent instead
path.parentPath.traverse(tailRecursionFinder, state);
return state.found;
}