rest.js 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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. const argsId = _core.types.identifier("arguments");
  183. if (_core.types.isPattern(rest)) {
  184. const pattern = rest;
  185. rest = scope.generateUidIdentifier("ref");
  186. const declar = _core.types.variableDeclaration("let", [_core.types.variableDeclarator(pattern, rest)]);
  187. node.body.body.unshift(declar);
  188. }
  189. const paramsCount = getParamsCount(node);
  190. const state = {
  191. references: [],
  192. offset: paramsCount,
  193. argumentsNode: argsId,
  194. outerBinding: scope.getBindingIdentifier(rest.name),
  195. candidates: [],
  196. name: rest.name,
  197. deopted: false
  198. };
  199. path.traverse(memberExpressionOptimisationVisitor, state);
  200. if (!state.deopted && !state.references.length) {
  201. for (const {
  202. path,
  203. cause
  204. } of state.candidates) {
  205. const clonedArgsId = _core.types.cloneNode(argsId);
  206. switch (cause) {
  207. case "indexGetter":
  208. optimiseIndexGetter(path, clonedArgsId, state.offset);
  209. break;
  210. case "lengthGetter":
  211. optimiseLengthGetter(path, clonedArgsId, state.offset);
  212. break;
  213. default:
  214. path.replaceWith(clonedArgsId);
  215. }
  216. }
  217. return true;
  218. }
  219. state.references = state.references.concat(state.candidates.map(({
  220. path
  221. }) => path));
  222. const start = _core.types.numericLiteral(paramsCount);
  223. const key = scope.generateUidIdentifier("key");
  224. const len = scope.generateUidIdentifier("len");
  225. let arrKey, arrLen;
  226. if (paramsCount) {
  227. arrKey = _core.types.binaryExpression("-", _core.types.cloneNode(key), _core.types.cloneNode(start));
  228. 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));
  229. } else {
  230. arrKey = _core.types.identifier(key.name);
  231. arrLen = _core.types.identifier(len.name);
  232. }
  233. const loop = buildRest({
  234. ARGUMENTS: argsId,
  235. ARRAY_KEY: arrKey,
  236. ARRAY_LEN: arrLen,
  237. START: start,
  238. ARRAY: rest,
  239. KEY: key,
  240. LEN: len
  241. });
  242. if (state.deopted) {
  243. node.body.body.unshift(loop);
  244. } else {
  245. let target = path.getEarliestCommonAncestorFrom(state.references).getStatementParent();
  246. target.findParent(path => {
  247. if (path.isLoop()) {
  248. target = path;
  249. } else {
  250. return path.isFunction();
  251. }
  252. });
  253. target.insertBefore(loop);
  254. }
  255. return true;
  256. }