ts-simple-ast
Version:
TypeScript compiler wrapper for AST navigation and code generation.
61 lines (59 loc) • 2.74 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("./../../../utils");
const StraightReplacementNodeHandler_1 = require("./StraightReplacementNodeHandler");
/**
* Handler for deailing with a parent that is going to have a child replaced.
*/
class DefaultParentHandler {
constructor(compilerFactory, opts) {
this.compilerFactory = compilerFactory;
this.straightReplacementNodeHandler = new StraightReplacementNodeHandler_1.StraightReplacementNodeHandler(compilerFactory);
this.childCount = opts.childCount;
this.isFirstChild = opts.isFirstChild;
this.replacingNodes = opts.replacingNodes;
}
handleNode(currentNode, newNode) {
const currentNodeChildren = new utils_1.AdvancedIterator(currentNode.getChildrenIterator());
const newNodeChildren = new utils_1.AdvancedIterator(newNode.getChildrenIterator());
let count = this.childCount;
// get the first child
while (!currentNodeChildren.done && !newNodeChildren.done && !this.isFirstChild(currentNodeChildren.peek, newNodeChildren.peek))
this.straightReplacementNodeHandler.handleNode(currentNodeChildren.next(), newNodeChildren.next());
// try replacing any nodes
while (!currentNodeChildren.done && this.tryReplaceNode(currentNodeChildren.peek))
currentNodeChildren.next();
// add or remove the items
if (count > 0) {
while (count > 0) {
newNodeChildren.next().setSourceFile(currentNode.sourceFile);
count--;
}
}
else if (count < 0) {
while (count < 0) {
currentNodeChildren.next().dispose();
count++;
}
}
// 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);
}
tryReplaceNode(currentNode) {
if (this.replacingNodes == null || this.replacingNodes.length === 0)
return false;
const index = this.replacingNodes.indexOf(currentNode);
if (index === -1)
return false;
this.replacingNodes.splice(index, 1);
currentNode.dispose();
return true;
}
}
exports.DefaultParentHandler = DefaultParentHandler;
//# sourceMappingURL=DefaultParentHandler.js.map