replacement.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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 =
  48. this.container[this.key] = null;
  49. const paths = this.insertAfter(nodes);
  50. if (this.node) {
  51. this.requeue();
  52. } else {
  53. this.remove();
  54. }
  55. return paths;
  56. }
  57. function replaceWithSourceString(replacement) {
  58. this.resync();
  59. let ast;
  60. try {
  61. replacement = `(${replacement})`;
  62. ast = (0, _parser.parse)(replacement);
  63. } catch (err) {
  64. const loc = err.loc;
  65. if (loc) {
  66. err.message += " - make sure this is an expression.\n" + (0, _codeFrame.codeFrameColumns)(replacement, {
  67. start: {
  68. line: loc.line,
  69. column: loc.column + 1
  70. }
  71. });
  72. err.code = "BABEL_REPLACE_SOURCE_ERROR";
  73. }
  74. throw err;
  75. }
  76. const expressionAST = ast.program.body[0].expression;
  77. _index.default.removeProperties(expressionAST);
  78. return this.replaceWith(expressionAST);
  79. }
  80. function replaceWith(replacementPath) {
  81. this.resync();
  82. if (this.removed) {
  83. throw new Error("You can't replace this node, we've already removed it");
  84. }
  85. let replacement = replacementPath instanceof _index2.default ? replacementPath.node : replacementPath;
  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 =
  137. this.container[this.key] = node;
  138. }
  139. function replaceExpressionWithStatements(nodes) {
  140. this.resync();
  141. const nodesAsSequenceExpression = toSequenceExpression(nodes, this.scope);
  142. if (nodesAsSequenceExpression) {
  143. return this.replaceWith(nodesAsSequenceExpression)[0].get("expressions");
  144. }
  145. const functionParent = this.getFunctionParent();
  146. const isParentAsync = functionParent == null ? void 0 : functionParent.is("async");
  147. const isParentGenerator = functionParent == null ? void 0 : functionParent.is("generator");
  148. const container = arrowFunctionExpression([], blockStatement(nodes));
  149. this.replaceWith(callExpression(container, []));
  150. const callee = this.get("callee");
  151. (0, _helperHoistVariables.default)(callee.get("body"), id => {
  152. this.scope.push({
  153. id
  154. });
  155. }, "var");
  156. const completionRecords = this.get("callee").getCompletionRecords();
  157. for (const path of completionRecords) {
  158. if (!path.isExpressionStatement()) continue;
  159. const loop = path.findParent(path => path.isLoop());
  160. if (loop) {
  161. let uid = loop.getData("expressionReplacementReturnUid");
  162. if (!uid) {
  163. uid = callee.scope.generateDeclaredUidIdentifier("ret");
  164. callee.get("body").pushContainer("body", returnStatement(cloneNode(uid)));
  165. loop.setData("expressionReplacementReturnUid", uid);
  166. } else {
  167. uid = identifier(uid.name);
  168. }
  169. path.get("expression").replaceWith(assignmentExpression("=", cloneNode(uid), path.node.expression));
  170. } else {
  171. path.replaceWith(returnStatement(path.node.expression));
  172. }
  173. }
  174. callee.arrowFunctionToExpression();
  175. const newCallee = callee;
  176. const needToAwaitFunction = isParentAsync && _index.default.hasType(this.get("callee.body").node, "AwaitExpression", FUNCTION_TYPES);
  177. const needToYieldFunction = isParentGenerator && _index.default.hasType(this.get("callee.body").node, "YieldExpression", FUNCTION_TYPES);
  178. if (needToAwaitFunction) {
  179. newCallee.set("async", true);
  180. if (!needToYieldFunction) {
  181. this.replaceWith(awaitExpression(this.node));
  182. }
  183. }
  184. if (needToYieldFunction) {
  185. newCallee.set("generator", true);
  186. this.replaceWith(yieldExpression(this.node, true));
  187. }
  188. return newCallee.get("body.body");
  189. }
  190. function replaceInline(nodes) {
  191. this.resync();
  192. if (Array.isArray(nodes)) {
  193. if (Array.isArray(this.container)) {
  194. nodes = this._verifyNodeList(nodes);
  195. const paths = this._containerInsertAfter(nodes);
  196. this.remove();
  197. return paths;
  198. } else {
  199. return this.replaceWithMultiple(nodes);
  200. }
  201. } else {
  202. return this.replaceWith(nodes);
  203. }
  204. }
  205. //# sourceMappingURL=replacement.js.map