ts-simple-ast
Version:
TypeScript compiler wrapper for AST navigation and code generation.
50 lines (48 loc) • 2.48 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("./../../../utils");
const StraightReplacementNodeHandler_1 = require("./StraightReplacementNodeHandler");
/**
* Parent handler used to unwrap the
*/
class UnwrapParentHandler {
constructor(compilerFactory, childIndex) {
this.compilerFactory = compilerFactory;
this.childIndex = childIndex;
this.straightReplacementNodeHandler = new StraightReplacementNodeHandler_1.StraightReplacementNodeHandler(compilerFactory);
}
handleNode(currentNode, newNode) {
const currentNodeChildren = new utils_1.AdvancedIterator(currentNode.getChildrenIterator());
const newNodeChildren = new utils_1.AdvancedIterator(newNode.getChildrenIterator());
let index = 0;
// replace normally until reaching the first child
while (!currentNodeChildren.done && !newNodeChildren.done && index++ < this.childIndex)
this.straightReplacementNodeHandler.handleNode(currentNodeChildren.next(), newNodeChildren.next());
// the child syntax list's children should map to the newNodes next children
const currentChild = currentNodeChildren.next();
const childSyntaxList = currentChild.getChildSyntaxListOrThrow();
for (const child of childSyntaxList.getChildren()) {
this.straightReplacementNodeHandler.handleNode(child, newNodeChildren.next());
}
// destroy all the current child's children except for the children of its child syntax list
disposeNodes(currentChild);
function disposeNodes(node) {
if (node === childSyntaxList) {
node.disposeOnlyThis();
return;
}
for (const child of node.getChildren())
disposeNodes(child);
node.disposeOnlyThis();
}
// handle the rest
while (!currentNodeChildren.done)
this.straightReplacementNodeHandler.handleNode(currentNodeChildren.next(), newNodeChildren.next());
// ensure the new children iterator is done too
if (!newNodeChildren.done)
throw new Error("Error replacing tree: Should not have more children left over."); // todo: better error message
this.compilerFactory.replaceCompilerNode(currentNode, newNode.compilerNode);
}
}
exports.UnwrapParentHandler = UnwrapParentHandler;
//# sourceMappingURL=UnwrapParentHandler.js.map