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.

401 lines
13 KiB

4 years ago
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. var _helperPluginUtils = require("@babel/helper-plugin-utils");
  7. var _pluginSyntaxObjectRestSpread = _interopRequireDefault(require("@babel/plugin-syntax-object-rest-spread"));
  8. var _core = require("@babel/core");
  9. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  10. const ZERO_REFS = (() => {
  11. const node = _core.types.identifier("a");
  12. const property = _core.types.objectProperty(_core.types.identifier("key"), node);
  13. const pattern = _core.types.objectPattern([property]);
  14. return _core.types.isReferenced(node, property, pattern) ? 1 : 0;
  15. })();
  16. var _default = (0, _helperPluginUtils.declare)((api, opts) => {
  17. api.assertVersion(7);
  18. const {
  19. useBuiltIns = false,
  20. loose = false
  21. } = opts;
  22. if (typeof loose !== "boolean") {
  23. throw new Error(".loose must be a boolean, or undefined");
  24. }
  25. function getExtendsHelper(file) {
  26. return useBuiltIns ? _core.types.memberExpression(_core.types.identifier("Object"), _core.types.identifier("assign")) : file.addHelper("extends");
  27. }
  28. function hasRestElement(path) {
  29. let foundRestElement = false;
  30. visitRestElements(path, restElement => {
  31. foundRestElement = true;
  32. restElement.stop();
  33. });
  34. return foundRestElement;
  35. }
  36. function hasObjectPatternRestElement(path) {
  37. let foundRestElement = false;
  38. visitRestElements(path, restElement => {
  39. if (restElement.parentPath.isObjectPattern()) {
  40. foundRestElement = true;
  41. restElement.stop();
  42. }
  43. });
  44. return foundRestElement;
  45. }
  46. function visitRestElements(path, visitor) {
  47. path.traverse({
  48. Expression(path) {
  49. const parentType = path.parent.type;
  50. if (parentType === "AssignmentPattern" && path.key === "right" || parentType === "ObjectProperty" && path.parent.computed && path.key === "key") {
  51. path.skip();
  52. }
  53. },
  54. RestElement: visitor
  55. });
  56. }
  57. function hasSpread(node) {
  58. for (const prop of node.properties) {
  59. if (_core.types.isSpreadElement(prop)) {
  60. return true;
  61. }
  62. }
  63. return false;
  64. }
  65. function extractNormalizedKeys(path) {
  66. const props = path.node.properties;
  67. const keys = [];
  68. let allLiteral = true;
  69. for (const prop of props) {
  70. if (_core.types.isIdentifier(prop.key) && !prop.computed) {
  71. keys.push(_core.types.stringLiteral(prop.key.name));
  72. } else if (_core.types.isTemplateLiteral(prop.key)) {
  73. keys.push(_core.types.cloneNode(prop.key));
  74. } else if (_core.types.isLiteral(prop.key)) {
  75. keys.push(_core.types.stringLiteral(String(prop.key.value)));
  76. } else {
  77. keys.push(_core.types.cloneNode(prop.key));
  78. allLiteral = false;
  79. }
  80. }
  81. return {
  82. keys,
  83. allLiteral
  84. };
  85. }
  86. function replaceImpureComputedKeys(path) {
  87. const impureComputedPropertyDeclarators = [];
  88. for (const propPath of path.get("properties")) {
  89. const key = propPath.get("key");
  90. if (propPath.node.computed && !key.isPure()) {
  91. const name = path.scope.generateUidBasedOnNode(key.node);
  92. const declarator = _core.types.variableDeclarator(_core.types.identifier(name), key.node);
  93. impureComputedPropertyDeclarators.push(declarator);
  94. key.replaceWith(_core.types.identifier(name));
  95. }
  96. }
  97. return impureComputedPropertyDeclarators;
  98. }
  99. function removeUnusedExcludedKeys(path) {
  100. const bindings = path.getOuterBindingIdentifierPaths();
  101. Object.keys(bindings).forEach(bindingName => {
  102. const bindingParentPath = bindings[bindingName].parentPath;
  103. if (path.scope.getBinding(bindingName).references > ZERO_REFS || !bindingParentPath.isObjectProperty()) {
  104. return;
  105. }
  106. bindingParentPath.remove();
  107. });
  108. }
  109. function createObjectSpread(path, file, objRef) {
  110. const props = path.get("properties");
  111. const last = props[props.length - 1];
  112. _core.types.assertRestElement(last.node);
  113. const restElement = _core.types.cloneNode(last.node);
  114. last.remove();
  115. const impureComputedPropertyDeclarators = replaceImpureComputedKeys(path);
  116. const {
  117. keys,
  118. allLiteral
  119. } = extractNormalizedKeys(path);
  120. if (keys.length === 0) {
  121. return [impureComputedPropertyDeclarators, restElement.argument, _core.types.callExpression(getExtendsHelper(file), [_core.types.objectExpression([]), _core.types.cloneNode(objRef)])];
  122. }
  123. let keyExpression;
  124. if (!allLiteral) {
  125. keyExpression = _core.types.callExpression(_core.types.memberExpression(_core.types.arrayExpression(keys), _core.types.identifier("map")), [file.addHelper("toPropertyKey")]);
  126. } else {
  127. keyExpression = _core.types.arrayExpression(keys);
  128. }
  129. return [impureComputedPropertyDeclarators, restElement.argument, _core.types.callExpression(file.addHelper(`objectWithoutProperties${loose ? "Loose" : ""}`), [_core.types.cloneNode(objRef), keyExpression])];
  130. }
  131. function replaceRestElement(parentPath, paramPath) {
  132. if (paramPath.isAssignmentPattern()) {
  133. replaceRestElement(parentPath, paramPath.get("left"));
  134. return;
  135. }
  136. if (paramPath.isArrayPattern() && hasRestElement(paramPath)) {
  137. const elements = paramPath.get("elements");
  138. for (let i = 0; i < elements.length; i++) {
  139. replaceRestElement(parentPath, elements[i]);
  140. }
  141. }
  142. if (paramPath.isObjectPattern() && hasRestElement(paramPath)) {
  143. const uid = parentPath.scope.generateUidIdentifier("ref");
  144. const declar = _core.types.variableDeclaration("let", [_core.types.variableDeclarator(paramPath.node, uid)]);
  145. parentPath.ensureBlock();
  146. parentPath.get("body").unshiftContainer("body", declar);
  147. paramPath.replaceWith(_core.types.cloneNode(uid));
  148. }
  149. }
  150. return {
  151. name: "proposal-object-rest-spread",
  152. inherits: _pluginSyntaxObjectRestSpread.default,
  153. visitor: {
  154. Function(path) {
  155. const params = path.get("params");
  156. for (let i = params.length - 1; i >= 0; i--) {
  157. replaceRestElement(params[i].parentPath, params[i]);
  158. }
  159. },
  160. VariableDeclarator(path, file) {
  161. if (!path.get("id").isObjectPattern()) {
  162. return;
  163. }
  164. let insertionPath = path;
  165. const originalPath = path;
  166. visitRestElements(path.get("id"), path => {
  167. if (!path.parentPath.isObjectPattern()) {
  168. return;
  169. }
  170. if (originalPath.node.id.properties.length > 1 && !_core.types.isIdentifier(originalPath.node.init)) {
  171. const initRef = path.scope.generateUidIdentifierBasedOnNode(originalPath.node.init, "ref");
  172. originalPath.insertBefore(_core.types.variableDeclarator(initRef, originalPath.node.init));
  173. originalPath.replaceWith(_core.types.variableDeclarator(originalPath.node.id, _core.types.cloneNode(initRef)));
  174. return;
  175. }
  176. let ref = originalPath.node.init;
  177. const refPropertyPath = [];
  178. let kind;
  179. path.findParent(path => {
  180. if (path.isObjectProperty()) {
  181. refPropertyPath.unshift(path.node.key.name);
  182. } else if (path.isVariableDeclarator()) {
  183. kind = path.parentPath.node.kind;
  184. return true;
  185. }
  186. });
  187. if (refPropertyPath.length) {
  188. refPropertyPath.forEach(prop => {
  189. ref = _core.types.memberExpression(ref, _core.types.identifier(prop));
  190. });
  191. }
  192. const objectPatternPath = path.findParent(path => path.isObjectPattern());
  193. const [impureComputedPropertyDeclarators, argument, callExpression] = createObjectSpread(objectPatternPath, file, ref);
  194. if (loose) {
  195. removeUnusedExcludedKeys(objectPatternPath);
  196. }
  197. _core.types.assertIdentifier(argument);
  198. insertionPath.insertBefore(impureComputedPropertyDeclarators);
  199. insertionPath.insertAfter(_core.types.variableDeclarator(argument, callExpression));
  200. insertionPath = insertionPath.getSibling(insertionPath.key + 1);
  201. path.scope.registerBinding(kind, insertionPath);
  202. if (objectPatternPath.node.properties.length === 0) {
  203. objectPatternPath.findParent(path => path.isObjectProperty() || path.isVariableDeclarator()).remove();
  204. }
  205. });
  206. },
  207. ExportNamedDeclaration(path) {
  208. const declaration = path.get("declaration");
  209. if (!declaration.isVariableDeclaration()) return;
  210. const hasRest = declaration.get("declarations").some(path => hasRestElement(path.get("id")));
  211. if (!hasRest) return;
  212. const specifiers = [];
  213. for (const name of Object.keys(path.getOuterBindingIdentifiers(path))) {
  214. specifiers.push(_core.types.exportSpecifier(_core.types.identifier(name), _core.types.identifier(name)));
  215. }
  216. path.replaceWith(declaration.node);
  217. path.insertAfter(_core.types.exportNamedDeclaration(null, specifiers));
  218. },
  219. CatchClause(path) {
  220. const paramPath = path.get("param");
  221. replaceRestElement(paramPath.parentPath, paramPath);
  222. },
  223. AssignmentExpression(path, file) {
  224. const leftPath = path.get("left");
  225. if (leftPath.isObjectPattern() && hasRestElement(leftPath)) {
  226. const nodes = [];
  227. const refName = path.scope.generateUidBasedOnNode(path.node.right, "ref");
  228. nodes.push(_core.types.variableDeclaration("var", [_core.types.variableDeclarator(_core.types.identifier(refName), path.node.right)]));
  229. const [impureComputedPropertyDeclarators, argument, callExpression] = createObjectSpread(leftPath, file, _core.types.identifier(refName));
  230. if (impureComputedPropertyDeclarators.length > 0) {
  231. nodes.push(_core.types.variableDeclaration("var", impureComputedPropertyDeclarators));
  232. }
  233. const nodeWithoutSpread = _core.types.cloneNode(path.node);
  234. nodeWithoutSpread.right = _core.types.identifier(refName);
  235. nodes.push(_core.types.expressionStatement(nodeWithoutSpread));
  236. nodes.push(_core.types.toStatement(_core.types.assignmentExpression("=", argument, callExpression)));
  237. nodes.push(_core.types.expressionStatement(_core.types.identifier(refName)));
  238. path.replaceWithMultiple(nodes);
  239. }
  240. },
  241. ForXStatement(path) {
  242. const {
  243. node,
  244. scope
  245. } = path;
  246. const leftPath = path.get("left");
  247. const left = node.left;
  248. if (!hasObjectPatternRestElement(leftPath)) {
  249. return;
  250. }
  251. if (!_core.types.isVariableDeclaration(left)) {
  252. const temp = scope.generateUidIdentifier("ref");
  253. node.left = _core.types.variableDeclaration("var", [_core.types.variableDeclarator(temp)]);
  254. path.ensureBlock();
  255. if (node.body.body.length === 0 && path.isCompletionRecord()) {
  256. node.body.body.unshift(_core.types.expressionStatement(scope.buildUndefinedNode()));
  257. }
  258. node.body.body.unshift(_core.types.expressionStatement(_core.types.assignmentExpression("=", left, _core.types.cloneNode(temp))));
  259. } else {
  260. const pattern = left.declarations[0].id;
  261. const key = scope.generateUidIdentifier("ref");
  262. node.left = _core.types.variableDeclaration(left.kind, [_core.types.variableDeclarator(key, null)]);
  263. path.ensureBlock();
  264. node.body.body.unshift(_core.types.variableDeclaration(node.left.kind, [_core.types.variableDeclarator(pattern, _core.types.cloneNode(key))]));
  265. }
  266. },
  267. ArrayPattern(path) {
  268. const objectPatterns = [];
  269. visitRestElements(path, path => {
  270. if (!path.parentPath.isObjectPattern()) {
  271. return;
  272. }
  273. const objectPattern = path.parentPath;
  274. const uid = path.scope.generateUidIdentifier("ref");
  275. objectPatterns.push(_core.types.variableDeclarator(objectPattern.node, uid));
  276. objectPattern.replaceWith(_core.types.cloneNode(uid));
  277. path.skip();
  278. });
  279. if (objectPatterns.length > 0) {
  280. const statementPath = path.getStatementParent();
  281. statementPath.insertAfter(_core.types.variableDeclaration(statementPath.node.kind || "var", objectPatterns));
  282. }
  283. },
  284. ObjectExpression(path, file) {
  285. if (!hasSpread(path.node)) return;
  286. const args = [];
  287. let props = [];
  288. function push() {
  289. args.push(_core.types.objectExpression(props));
  290. props = [];
  291. }
  292. for (const prop of path.node.properties) {
  293. if (_core.types.isSpreadElement(prop)) {
  294. push();
  295. args.push(prop.argument);
  296. } else {
  297. props.push(prop);
  298. }
  299. }
  300. if (props.length) {
  301. push();
  302. }
  303. let helper;
  304. if (loose) {
  305. helper = getExtendsHelper(file);
  306. } else {
  307. try {
  308. helper = file.addHelper("objectSpread2");
  309. } catch (_unused) {
  310. this.file.declarations["objectSpread2"] = null;
  311. helper = file.addHelper("objectSpread");
  312. }
  313. }
  314. path.replaceWith(_core.types.callExpression(helper, args));
  315. }
  316. }
  317. };
  318. });
  319. exports.default = _default;