UNPKG

ts-simple-ast

Version:

TypeScript compiler wrapper for AST navigation and code generation.

58 lines (56 loc) 2.35 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const ts = require("typescript"); const errors = require("./../../errors"); const nodeHandlers_1 = require("./nodeHandlers"); /** * Replaces with tree that creates a syntax list. */ function replaceTreeCreatingSyntaxList(opts) { const { parent, replacementSourceFile, insertPos } = opts; replaceTree({ parent, childCount: 1, replacementSourceFile, isFirstChild: (currentNode, newNode) => newNode.getKind() === ts.SyntaxKind.SyntaxList && insertPos <= newNode.getStart() }); } exports.replaceTreeCreatingSyntaxList = replaceTreeCreatingSyntaxList; /** * Replaces with tree based on the child index from the parent. */ function replaceTreeWithChildIndex(opts) { const { replacementSourceFile, parent, childIndex, childCount, replacingNodes } = opts; const parentChildren = parent.getChildren(); errors.throwIfOutOfRange(childIndex, [0, parentChildren.length], "opts.childIndex"); if (childCount < 0) errors.throwIfOutOfRange(childCount, [childIndex - parentChildren.length, 0], "opts.childCount"); let i = 0; const isFirstChild = () => i++ === childIndex; replaceTree({ replacementSourceFile, parent, isFirstChild, childCount, replacingNodes }); } exports.replaceTreeWithChildIndex = replaceTreeWithChildIndex; /** * Replaces the tree with a new one. */ function replaceTree(opts) { const { replacementSourceFile, parent: changingParent, isFirstChild, childCount } = opts; const sourceFile = changingParent.getSourceFile(); const compilerFactory = sourceFile.global.compilerFactory; const replacingNodes = opts.replacingNodes == null ? undefined : [...opts.replacingNodes]; const parentHandler = new nodeHandlers_1.DefaultParentHandler(compilerFactory, { childCount, isFirstChild, replacingNodes }); if (changingParent === sourceFile) parentHandler.handleNode(sourceFile, replacementSourceFile); else { const parentFinderReplacement = new nodeHandlers_1.ParentFinderReplacementNodeHandler(compilerFactory, parentHandler, changingParent); parentFinderReplacement.handleNode(sourceFile, replacementSourceFile); } } exports.replaceTree = replaceTree; //# sourceMappingURL=replaceTree.js.map