replacement.js 6.9 KB

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