replacement.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports._replaceWith = _replaceWith;
  6. exports.replaceExpressionWithStatements = replaceExpressionWithStatements;
  7. exports.replaceInline = replaceInline;
  8. exports.replaceWith = replaceWith;
  9. exports.replaceWithMultiple = replaceWithMultiple;
  10. exports.replaceWithSourceString = replaceWithSourceString;
  11. var _codeFrame = require("@babel/code-frame");
  12. var _index = require("../index.js");
  13. var _index2 = require("./index.js");
  14. var _cache = require("../cache.js");
  15. var _parser = require("@babel/parser");
  16. var _t = require("@babel/types");
  17. var _helperHoistVariables = require("@babel/helper-hoist-variables");
  18. const {
  19. FUNCTION_TYPES,
  20. arrowFunctionExpression,
  21. assignmentExpression,
  22. awaitExpression,
  23. blockStatement,
  24. callExpression,
  25. cloneNode,
  26. expressionStatement,
  27. identifier,
  28. inheritLeadingComments,
  29. inheritTrailingComments,
  30. inheritsComments,
  31. isExpression,
  32. isProgram,
  33. isStatement,
  34. removeComments,
  35. returnStatement,
  36. toSequenceExpression,
  37. validate,
  38. yieldExpression
  39. } = _t;
  40. function replaceWithMultiple(nodes) {
  41. var _getCachedPaths;
  42. this.resync();
  43. nodes = this._verifyNodeList(nodes);
  44. inheritLeadingComments(nodes[0], this.node);
  45. inheritTrailingComments(nodes[nodes.length - 1], this.node);
  46. (_getCachedPaths = (0, _cache.getCachedPaths)(this.hub, this.parent)) == null ? void 0 : _getCachedPaths.delete(this.node);
  47. this.node = this.container[this.key] = null;
  48. const paths = this.insertAfter(nodes);
  49. if (this.node) {
  50. this.requeue();
  51. } else {
  52. this.remove();
  53. }
  54. return paths;
  55. }
  56. function replaceWithSourceString(replacement) {
  57. this.resync();
  58. let ast;
  59. try {
  60. replacement = `(${replacement})`;
  61. ast = (0, _parser.parse)(replacement);
  62. } catch (err) {
  63. const loc = err.loc;
  64. if (loc) {
  65. err.message += " - make sure this is an expression.\n" + (0, _codeFrame.codeFrameColumns)(replacement, {
  66. start: {
  67. line: loc.line,
  68. column: loc.column + 1
  69. }
  70. });
  71. err.code = "BABEL_REPLACE_SOURCE_ERROR";
  72. }
  73. throw err;
  74. }
  75. const expressionAST = ast.program.body[0].expression;
  76. _index.default.removeProperties(expressionAST);
  77. return this.replaceWith(expressionAST);
  78. }
  79. function replaceWith(replacementPath) {
  80. this.resync();
  81. if (this.removed) {
  82. throw new Error("You can't replace this node, we've already removed it");
  83. }
  84. let replacement = replacementPath instanceof _index2.default ? replacementPath.node : replacementPath;
  85. if (!replacement) {
  86. throw new Error("You passed `path.replaceWith()` a falsy node, use `path.remove()` instead");
  87. }
  88. if (this.node === replacement) {
  89. return [this];
  90. }
  91. if (this.isProgram() && !isProgram(replacement)) {
  92. throw new Error("You can only replace a Program root node with another Program node");
  93. }
  94. if (Array.isArray(replacement)) {
  95. throw new Error("Don't use `path.replaceWith()` with an array of nodes, use `path.replaceWithMultiple()`");
  96. }
  97. if (typeof replacement === "string") {
  98. throw new Error("Don't use `path.replaceWith()` with a source string, use `path.replaceWithSourceString()`");
  99. }
  100. let nodePath = "";
  101. if (this.isNodeType("Statement") && isExpression(replacement)) {
  102. if (!this.canHaveVariableDeclarationOrExpression() && !this.canSwapBetweenExpressionAndStatement(replacement) && !this.parentPath.isExportDefaultDeclaration()) {
  103. replacement = expressionStatement(replacement);
  104. nodePath = "expression";
  105. }
  106. }
  107. if (this.isNodeType("Expression") && isStatement(replacement)) {
  108. if (!this.canHaveVariableDeclarationOrExpression() && !this.canSwapBetweenExpressionAndStatement(replacement)) {
  109. return this.replaceExpressionWithStatements([replacement]);
  110. }
  111. }
  112. const oldNode = this.node;
  113. if (oldNode) {
  114. inheritsComments(replacement, oldNode);
  115. removeComments(oldNode);
  116. }
  117. this._replaceWith(replacement);
  118. this.type = replacement.type;
  119. this.setScope();
  120. this.requeue();
  121. return [nodePath ? this.get(nodePath) : this];
  122. }
  123. function _replaceWith(node) {
  124. var _getCachedPaths2;
  125. if (!this.container) {
  126. throw new ReferenceError("Container is falsy");
  127. }
  128. if (this.inList) {
  129. validate(this.parent, this.key, [node]);
  130. } else {
  131. validate(this.parent, this.key, node);
  132. }
  133. this.debug(`Replace with ${node == null ? void 0 : node.type}`);
  134. (_getCachedPaths2 = (0, _cache.getCachedPaths)(this.hub, this.parent)) == null ? void 0 : _getCachedPaths2.set(node, this).delete(this.node);
  135. this.node = this.container[this.key] = node;
  136. }
  137. function replaceExpressionWithStatements(nodes) {
  138. this.resync();
  139. const nodesAsSequenceExpression = toSequenceExpression(nodes, this.scope);
  140. if (nodesAsSequenceExpression) {
  141. return this.replaceWith(nodesAsSequenceExpression)[0].get("expressions");
  142. }
  143. const functionParent = this.getFunctionParent();
  144. const isParentAsync = functionParent == null ? void 0 : functionParent.is("async");
  145. const isParentGenerator = functionParent == null ? void 0 : functionParent.is("generator");
  146. const container = arrowFunctionExpression([], blockStatement(nodes));
  147. this.replaceWith(callExpression(container, []));
  148. const callee = this.get("callee");
  149. (0, _helperHoistVariables.default)(callee.get("body"), id => {
  150. this.scope.push({
  151. id
  152. });
  153. }, "var");
  154. const completionRecords = this.get("callee").getCompletionRecords();
  155. for (const path of completionRecords) {
  156. if (!path.isExpressionStatement()) continue;
  157. const loop = path.findParent(path => path.isLoop());
  158. if (loop) {
  159. let uid = loop.getData("expressionReplacementReturnUid");
  160. if (!uid) {
  161. uid = callee.scope.generateDeclaredUidIdentifier("ret");
  162. callee.get("body").pushContainer("body", returnStatement(cloneNode(uid)));
  163. loop.setData("expressionReplacementReturnUid", uid);
  164. } else {
  165. uid = identifier(uid.name);
  166. }
  167. path.get("expression").replaceWith(assignmentExpression("=", cloneNode(uid), path.node.expression));
  168. } else {
  169. path.replaceWith(returnStatement(path.node.expression));
  170. }
  171. }
  172. callee.arrowFunctionToExpression();
  173. const newCallee = callee;
  174. const needToAwaitFunction = isParentAsync && _index.default.hasType(this.get("callee.body").node, "AwaitExpression", FUNCTION_TYPES);
  175. const needToYieldFunction = isParentGenerator && _index.default.hasType(this.get("callee.body").node, "YieldExpression", FUNCTION_TYPES);
  176. if (needToAwaitFunction) {
  177. newCallee.set("async", true);
  178. if (!needToYieldFunction) {
  179. this.replaceWith(awaitExpression(this.node));
  180. }
  181. }
  182. if (needToYieldFunction) {
  183. newCallee.set("generator", true);
  184. this.replaceWith(yieldExpression(this.node, true));
  185. }
  186. return newCallee.get("body.body");
  187. }
  188. function replaceInline(nodes) {
  189. this.resync();
  190. if (Array.isArray(nodes)) {
  191. if (Array.isArray(this.container)) {
  192. nodes = this._verifyNodeList(nodes);
  193. const paths = this._containerInsertAfter(nodes);
  194. this.remove();
  195. return paths;
  196. } else {
  197. return this.replaceWithMultiple(nodes);
  198. }
  199. } else {
  200. return this.replaceWith(nodes);
  201. }
  202. }
  203. //# sourceMappingURL=replacement.js.map