replacement.js 7.0 KB

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