rest.js 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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 getParamsCount(node) {
  110. let count = node.params.length;
  111. if (count > 0 && _core.types.isIdentifier(node.params[0], {
  112. name: "this"
  113. })) {
  114. count -= 1;
  115. }
  116. return count;
  117. }
  118. function hasRest(node) {
  119. const length = node.params.length;
  120. return length > 0 && _core.types.isRestElement(node.params[length - 1]);
  121. }
  122. function optimiseIndexGetter(path, argsId, offset) {
  123. const offsetLiteral = _core.types.numericLiteral(offset);
  124. let index;
  125. if (_core.types.isNumericLiteral(path.parent.property)) {
  126. index = _core.types.numericLiteral(path.parent.property.value + offset);
  127. } else if (offset === 0) {
  128. index = path.parent.property;
  129. } else {
  130. index = _core.types.binaryExpression("+", path.parent.property, _core.types.cloneNode(offsetLiteral));
  131. }
  132. const {
  133. scope
  134. } = path;
  135. if (!scope.isPure(index)) {
  136. const temp = scope.generateUidIdentifierBasedOnNode(index);
  137. scope.push({
  138. id: temp,
  139. kind: "var"
  140. });
  141. path.parentPath.replaceWith(restIndexImpure({
  142. ARGUMENTS: argsId,
  143. OFFSET: offsetLiteral,
  144. INDEX: index,
  145. REF: _core.types.cloneNode(temp)
  146. }));
  147. } else {
  148. const parentPath = path.parentPath;
  149. parentPath.replaceWith(restIndex({
  150. ARGUMENTS: argsId,
  151. OFFSET: offsetLiteral,
  152. INDEX: index
  153. }));
  154. const offsetTestPath = parentPath.get("test").get("left");
  155. const valRes = offsetTestPath.evaluate();
  156. if (valRes.confident) {
  157. if (valRes.value === true) {
  158. parentPath.replaceWith(parentPath.scope.buildUndefinedNode());
  159. } else {
  160. parentPath.get("test").replaceWith(parentPath.get("test").get("right"));
  161. }
  162. }
  163. }
  164. }
  165. function optimiseLengthGetter(path, argsId, offset) {
  166. if (offset) {
  167. path.parentPath.replaceWith(restLength({
  168. ARGUMENTS: argsId,
  169. OFFSET: _core.types.numericLiteral(offset)
  170. }));
  171. } else {
  172. path.replaceWith(argsId);
  173. }
  174. }
  175. function convertFunctionRest(path) {
  176. const {
  177. node,
  178. scope
  179. } = path;
  180. if (!hasRest(node)) return false;
  181. let rest = node.params.pop().argument;
  182. if (rest.name === "arguments") scope.rename(rest.name);
  183. const argsId = _core.types.identifier("arguments");
  184. if (_core.types.isPattern(rest)) {
  185. const pattern = rest;
  186. rest = scope.generateUidIdentifier("ref");
  187. const declar = _core.types.variableDeclaration("let", [_core.types.variableDeclarator(pattern, rest)]);
  188. node.body.body.unshift(declar);
  189. }
  190. const paramsCount = getParamsCount(node);
  191. const state = {
  192. references: [],
  193. offset: paramsCount,
  194. argumentsNode: argsId,
  195. outerBinding: scope.getBindingIdentifier(rest.name),
  196. candidates: [],
  197. name: rest.name,
  198. deopted: false
  199. };
  200. path.traverse(memberExpressionOptimisationVisitor, state);
  201. if (!state.deopted && !state.references.length) {
  202. for (const {
  203. path,
  204. cause
  205. } of state.candidates) {
  206. const clonedArgsId = _core.types.cloneNode(argsId);
  207. switch (cause) {
  208. case "indexGetter":
  209. optimiseIndexGetter(path, clonedArgsId, state.offset);
  210. break;
  211. case "lengthGetter":
  212. optimiseLengthGetter(path, clonedArgsId, state.offset);
  213. break;
  214. default:
  215. path.replaceWith(clonedArgsId);
  216. }
  217. }
  218. return true;
  219. }
  220. state.references.push(...state.candidates.map(({
  221. path
  222. }) => path));
  223. const start = _core.types.numericLiteral(paramsCount);
  224. const key = scope.generateUidIdentifier("key");
  225. const len = scope.generateUidIdentifier("len");
  226. let arrKey, arrLen;
  227. if (paramsCount) {
  228. arrKey = _core.types.binaryExpression("-", _core.types.cloneNode(key), _core.types.cloneNode(start));
  229. 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));
  230. } else {
  231. arrKey = _core.types.identifier(key.name);
  232. arrLen = _core.types.identifier(len.name);
  233. }
  234. const loop = buildRest({
  235. ARGUMENTS: argsId,
  236. ARRAY_KEY: arrKey,
  237. ARRAY_LEN: arrLen,
  238. START: start,
  239. ARRAY: rest,
  240. KEY: key,
  241. LEN: len
  242. });
  243. if (state.deopted) {
  244. node.body.body.unshift(loop);
  245. } else {
  246. let target = path.getEarliestCommonAncestorFrom(state.references).getStatementParent();
  247. target.findParent(path => {
  248. if (path.isLoop()) {
  249. target = path;
  250. } else {
  251. return path.isFunction();
  252. }
  253. });
  254. target.insertBefore(loop);
  255. }
  256. return true;
  257. }