You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

243 lines
7.3 KiB

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