rest.js 8.6 KB

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