rest.js 8.6 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. var _shadowUtils = require("./shadow-utils");
  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 && !(
  71. grandparentPath.isAssignmentExpression() && parentPath.node === grandparentPath.node.left ||
  72. grandparentPath.isLVal() ||
  73. grandparentPath.isForXStatement() ||
  74. grandparentPath.isUpdateExpression() ||
  75. grandparentPath.isUnaryExpression({
  76. operator: "delete"
  77. }) ||
  78. (grandparentPath.isCallExpression() || grandparentPath.isNewExpression()) && parentPath.node === grandparentPath.node.callee);
  79. if (argsOptEligible) {
  80. if (parentPath.node.computed) {
  81. if (parentPath.get("property").isBaseType("number")) {
  82. state.candidates.push({
  83. cause: "indexGetter",
  84. path
  85. });
  86. return;
  87. }
  88. } else if (
  89. parentPath.node.property.name === "length") {
  90. state.candidates.push({
  91. cause: "lengthGetter",
  92. path
  93. });
  94. return;
  95. }
  96. }
  97. }
  98. if (state.offset === 0 && parentPath.isSpreadElement()) {
  99. const call = parentPath.parentPath;
  100. if (call.isCallExpression() && call.node.arguments.length === 1) {
  101. state.candidates.push({
  102. cause: "argSpread",
  103. path
  104. });
  105. return;
  106. }
  107. }
  108. state.references.push(path);
  109. }
  110. },
  111. BindingIdentifier(path, state) {
  112. if (referencesRest(path, state)) {
  113. state.deopted = true;
  114. }
  115. }
  116. };
  117. function getParamsCount(node) {
  118. let count = node.params.length;
  119. if (count > 0 && _core.types.isIdentifier(node.params[0], {
  120. name: "this"
  121. })) {
  122. count -= 1;
  123. }
  124. return count;
  125. }
  126. function hasRest(node) {
  127. const length = node.params.length;
  128. return length > 0 && _core.types.isRestElement(node.params[length - 1]);
  129. }
  130. function optimiseIndexGetter(path, argsId, offset) {
  131. const offsetLiteral = _core.types.numericLiteral(offset);
  132. let index;
  133. const parent = path.parent;
  134. if (_core.types.isNumericLiteral(parent.property)) {
  135. index = _core.types.numericLiteral(parent.property.value + offset);
  136. } else if (offset === 0) {
  137. index = parent.property;
  138. } else {
  139. index = _core.types.binaryExpression("+", parent.property, _core.types.cloneNode(offsetLiteral));
  140. }
  141. const {
  142. scope,
  143. parentPath
  144. } = path;
  145. if (!scope.isPure(index)) {
  146. const temp = scope.generateUidIdentifierBasedOnNode(index);
  147. scope.push({
  148. id: temp,
  149. kind: "var"
  150. });
  151. parentPath.replaceWith(restIndexImpure({
  152. ARGUMENTS: argsId,
  153. OFFSET: offsetLiteral,
  154. INDEX: index,
  155. REF: _core.types.cloneNode(temp)
  156. }));
  157. } else {
  158. parentPath.replaceWith(restIndex({
  159. ARGUMENTS: argsId,
  160. OFFSET: offsetLiteral,
  161. INDEX: index
  162. }));
  163. const replacedParentPath = parentPath;
  164. const offsetTestPath = replacedParentPath.get("test");
  165. const valRes = offsetTestPath.get("left").evaluate();
  166. if (valRes.confident) {
  167. if (valRes.value === true) {
  168. replacedParentPath.replaceWith(scope.buildUndefinedNode());
  169. } else {
  170. offsetTestPath.replaceWith(offsetTestPath.get("right"));
  171. }
  172. }
  173. }
  174. }
  175. function optimiseLengthGetter(path, argsId, offset) {
  176. if (offset) {
  177. path.parentPath.replaceWith(restLength({
  178. ARGUMENTS: argsId,
  179. OFFSET: _core.types.numericLiteral(offset)
  180. }));
  181. } else {
  182. path.replaceWith(argsId);
  183. }
  184. }
  185. function convertFunctionRest(path) {
  186. const {
  187. node,
  188. scope
  189. } = path;
  190. if (!hasRest(node)) return false;
  191. const restPath = path.get(`params.${node.params.length - 1}.argument`);
  192. if (!restPath.isIdentifier()) {
  193. const shadowedParams = new Set();
  194. (0, _shadowUtils.collectShadowedParamsNames)(restPath, path.scope, shadowedParams);
  195. let needsIIFE = shadowedParams.size > 0;
  196. if (!needsIIFE) {
  197. const state = {
  198. needsOuterBinding: false,
  199. scope
  200. };
  201. restPath.traverse(_shadowUtils.iifeVisitor, state);
  202. needsIIFE = state.needsOuterBinding;
  203. }
  204. if (needsIIFE) {
  205. path.ensureBlock();
  206. path.set("body", _core.types.blockStatement([(0, _shadowUtils.buildScopeIIFE)(shadowedParams, path.node.body)]));
  207. }
  208. }
  209. let rest = restPath.node;
  210. node.params.pop();
  211. if (_core.types.isPattern(rest)) {
  212. const pattern = rest;
  213. rest = scope.generateUidIdentifier("ref");
  214. const declar = _core.types.variableDeclaration("let", [_core.types.variableDeclarator(pattern, rest)]);
  215. path.ensureBlock();
  216. node.body.body.unshift(declar);
  217. } else if (rest.name === "arguments") {
  218. scope.rename(rest.name);
  219. }
  220. const argsId = _core.types.identifier("arguments");
  221. const paramsCount = getParamsCount(node);
  222. const state = {
  223. references: [],
  224. offset: paramsCount,
  225. argumentsNode: argsId,
  226. outerBinding: scope.getBindingIdentifier(rest.name),
  227. candidates: [],
  228. name: rest.name,
  229. deopted: false
  230. };
  231. path.traverse(memberExpressionOptimisationVisitor, state);
  232. if (!state.deopted && !state.references.length) {
  233. for (const {
  234. path,
  235. cause
  236. } of state.candidates) {
  237. const clonedArgsId = _core.types.cloneNode(argsId);
  238. switch (cause) {
  239. case "indexGetter":
  240. optimiseIndexGetter(path, clonedArgsId, state.offset);
  241. break;
  242. case "lengthGetter":
  243. optimiseLengthGetter(path, clonedArgsId, state.offset);
  244. break;
  245. default:
  246. path.replaceWith(clonedArgsId);
  247. }
  248. }
  249. return true;
  250. }
  251. state.references.push(...state.candidates.map(({
  252. path
  253. }) => path));
  254. const start = _core.types.numericLiteral(paramsCount);
  255. const key = scope.generateUidIdentifier("key");
  256. const len = scope.generateUidIdentifier("len");
  257. let arrKey, arrLen;
  258. if (paramsCount) {
  259. arrKey = _core.types.binaryExpression("-", _core.types.cloneNode(key), _core.types.cloneNode(start));
  260. 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));
  261. } else {
  262. arrKey = _core.types.identifier(key.name);
  263. arrLen = _core.types.identifier(len.name);
  264. }
  265. const loop = buildRest({
  266. ARGUMENTS: argsId,
  267. ARRAY_KEY: arrKey,
  268. ARRAY_LEN: arrLen,
  269. START: start,
  270. ARRAY: rest,
  271. KEY: key,
  272. LEN: len
  273. });
  274. if (state.deopted) {
  275. node.body.body.unshift(loop);
  276. } else {
  277. let target = path.getEarliestCommonAncestorFrom(state.references).getStatementParent();
  278. target.findParent(path => {
  279. if (path.isLoop()) {
  280. target = path;
  281. } else {
  282. return path.isFunction();
  283. }
  284. });
  285. target.insertBefore(loop);
  286. }
  287. return true;
  288. }
  289. //# sourceMappingURL=rest.js.map