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.

291 lines
7.6 KiB

4 years ago
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = convertFunctionRest;
  6. var _core = require("@babel/core");
  7. const buildRest = (0, _core.template)(`
  8. for (var LEN = ARGUMENTS.length,
  9. ARRAY = new Array(ARRAY_LEN),
  10. KEY = START;
  11. KEY < LEN;
  12. KEY++) {
  13. ARRAY[ARRAY_KEY] = ARGUMENTS[KEY];
  14. }
  15. `);
  16. const restIndex = (0, _core.template)(`
  17. (INDEX < OFFSET || ARGUMENTS.length <= INDEX) ? undefined : ARGUMENTS[INDEX]
  18. `);
  19. const restIndexImpure = (0, _core.template)(`
  20. REF = INDEX, (REF < OFFSET || ARGUMENTS.length <= REF) ? undefined : ARGUMENTS[REF]
  21. `);
  22. const restLength = (0, _core.template)(`
  23. ARGUMENTS.length <= OFFSET ? 0 : ARGUMENTS.length - OFFSET
  24. `);
  25. function referencesRest(path, state) {
  26. if (path.node.name === state.name) {
  27. return path.scope.bindingIdentifierEquals(state.name, state.outerBinding);
  28. }
  29. return false;
  30. }
  31. const memberExpressionOptimisationVisitor = {
  32. Scope(path, state) {
  33. if (!path.scope.bindingIdentifierEquals(state.name, state.outerBinding)) {
  34. path.skip();
  35. }
  36. },
  37. Flow(path) {
  38. if (path.isTypeCastExpression()) return;
  39. path.skip();
  40. },
  41. Function(path, state) {
  42. const oldNoOptimise = state.noOptimise;
  43. state.noOptimise = true;
  44. path.traverse(memberExpressionOptimisationVisitor, state);
  45. state.noOptimise = oldNoOptimise;
  46. path.skip();
  47. },
  48. ReferencedIdentifier(path, state) {
  49. const {
  50. node
  51. } = path;
  52. if (node.name === "arguments") {
  53. state.deopted = true;
  54. }
  55. if (!referencesRest(path, state)) return;
  56. if (state.noOptimise) {
  57. state.deopted = true;
  58. } else {
  59. const {
  60. parentPath
  61. } = path;
  62. if (parentPath.listKey === "params" && parentPath.key < state.offset) {
  63. return;
  64. }
  65. if (parentPath.isMemberExpression({
  66. object: node
  67. })) {
  68. const grandparentPath = parentPath.parentPath;
  69. const argsOptEligible = !state.deopted && !(grandparentPath.isAssignmentExpression() && parentPath.node === grandparentPath.node.left || grandparentPath.isLVal() || grandparentPath.isForXStatement() || grandparentPath.isUpdateExpression() || grandparentPath.isUnaryExpression({
  70. operator: "delete"
  71. }) || (grandparentPath.isCallExpression() || grandparentPath.isNewExpression()) && parentPath.node === grandparentPath.node.callee);
  72. if (argsOptEligible) {
  73. if (parentPath.node.computed) {
  74. if (parentPath.get("property").isBaseType("number")) {
  75. state.candidates.push({
  76. cause: "indexGetter",
  77. path
  78. });
  79. return;
  80. }
  81. } else if (parentPath.node.property.name === "length") {
  82. state.candidates.push({
  83. cause: "lengthGetter",
  84. path
  85. });
  86. return;
  87. }
  88. }
  89. }
  90. if (state.offset === 0 && parentPath.isSpreadElement()) {
  91. const call = parentPath.parentPath;
  92. if (call.isCallExpression() && call.node.arguments.length === 1) {
  93. state.candidates.push({
  94. cause: "argSpread",
  95. path
  96. });
  97. return;
  98. }
  99. }
  100. state.references.push(path);
  101. }
  102. },
  103. BindingIdentifier(path, state) {
  104. if (referencesRest(path, state)) {
  105. state.deopted = true;
  106. }
  107. }
  108. };
  109. function hasRest(node) {
  110. const length = node.params.length;
  111. return length > 0 && _core.types.isRestElement(node.params[length - 1]);
  112. }
  113. function optimiseIndexGetter(path, argsId, offset) {
  114. const offsetLiteral = _core.types.numericLiteral(offset);
  115. let index;
  116. if (_core.types.isNumericLiteral(path.parent.property)) {
  117. index = _core.types.numericLiteral(path.parent.property.value + offset);
  118. } else if (offset === 0) {
  119. index = path.parent.property;
  120. } else {
  121. index = _core.types.binaryExpression("+", path.parent.property, _core.types.cloneNode(offsetLiteral));
  122. }
  123. const {
  124. scope
  125. } = path;
  126. if (!scope.isPure(index)) {
  127. const temp = scope.generateUidIdentifierBasedOnNode(index);
  128. scope.push({
  129. id: temp,
  130. kind: "var"
  131. });
  132. path.parentPath.replaceWith(restIndexImpure({
  133. ARGUMENTS: argsId,
  134. OFFSET: offsetLiteral,
  135. INDEX: index,
  136. REF: _core.types.cloneNode(temp)
  137. }));
  138. } else {
  139. const parentPath = path.parentPath;
  140. parentPath.replaceWith(restIndex({
  141. ARGUMENTS: argsId,
  142. OFFSET: offsetLiteral,
  143. INDEX: index
  144. }));
  145. const offsetTestPath = parentPath.get("test").get("left");
  146. const valRes = offsetTestPath.evaluate();
  147. if (valRes.confident) {
  148. if (valRes.value === true) {
  149. parentPath.replaceWith(parentPath.scope.buildUndefinedNode());
  150. } else {
  151. parentPath.get("test").replaceWith(parentPath.get("test").get("right"));
  152. }
  153. }
  154. }
  155. }
  156. function optimiseLengthGetter(path, argsId, offset) {
  157. if (offset) {
  158. path.parentPath.replaceWith(restLength({
  159. ARGUMENTS: argsId,
  160. OFFSET: _core.types.numericLiteral(offset)
  161. }));
  162. } else {
  163. path.replaceWith(argsId);
  164. }
  165. }
  166. function convertFunctionRest(path) {
  167. const {
  168. node,
  169. scope
  170. } = path;
  171. if (!hasRest(node)) return false;
  172. let rest = node.params.pop().argument;
  173. const argsId = _core.types.identifier("arguments");
  174. if (_core.types.isPattern(rest)) {
  175. const pattern = rest;
  176. rest = scope.generateUidIdentifier("ref");
  177. const declar = _core.types.variableDeclaration("let", [_core.types.variableDeclarator(pattern, rest)]);
  178. node.body.body.unshift(declar);
  179. }
  180. const state = {
  181. references: [],
  182. offset: node.params.length,
  183. argumentsNode: argsId,
  184. outerBinding: scope.getBindingIdentifier(rest.name),
  185. candidates: [],
  186. name: rest.name,
  187. deopted: false
  188. };
  189. path.traverse(memberExpressionOptimisationVisitor, state);
  190. if (!state.deopted && !state.references.length) {
  191. for (const {
  192. path,
  193. cause
  194. } of state.candidates) {
  195. const clonedArgsId = _core.types.cloneNode(argsId);
  196. switch (cause) {
  197. case "indexGetter":
  198. optimiseIndexGetter(path, clonedArgsId, state.offset);
  199. break;
  200. case "lengthGetter":
  201. optimiseLengthGetter(path, clonedArgsId, state.offset);
  202. break;
  203. default:
  204. path.replaceWith(clonedArgsId);
  205. }
  206. }
  207. return true;
  208. }
  209. state.references = state.references.concat(state.candidates.map(({
  210. path
  211. }) => path));
  212. const start = _core.types.numericLiteral(node.params.length);
  213. const key = scope.generateUidIdentifier("key");
  214. const len = scope.generateUidIdentifier("len");
  215. let arrKey, arrLen;
  216. if (node.params.length) {
  217. arrKey = _core.types.binaryExpression("-", _core.types.cloneNode(key), _core.types.cloneNode(start));
  218. arrLen = _core.types.conditionalExpression(_core.types.binaryExpression(">", _core.types.cloneNode(len), _core.types.cloneNode(start)), _core.types.binaryExpression("-", _core.types.cloneNode(len), _core.types.cloneNode(start)), _core.types.numericLiteral(0));
  219. } else {
  220. arrKey = _core.types.identifier(key.name);
  221. arrLen = _core.types.identifier(len.name);
  222. }
  223. const loop = buildRest({
  224. ARGUMENTS: argsId,
  225. ARRAY_KEY: arrKey,
  226. ARRAY_LEN: arrLen,
  227. START: start,
  228. ARRAY: rest,
  229. KEY: key,
  230. LEN: len
  231. });
  232. if (state.deopted) {
  233. node.body.body.unshift(loop);
  234. } else {
  235. let target = path.getEarliestCommonAncestorFrom(state.references).getStatementParent();
  236. target.findParent(path => {
  237. if (path.isLoop()) {
  238. target = path;
  239. } else {
  240. return path.isFunction();
  241. }
  242. });
  243. target.insertBefore(loop);
  244. }
  245. return true;
  246. }