loop.js 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.getLoopBodyBindings = getLoopBodyBindings;
  6. exports.getUsageInBody = getUsageInBody;
  7. exports.isVarInLoopHead = isVarInLoopHead;
  8. exports.wrapLoopBody = wrapLoopBody;
  9. var _core = require("@babel/core");
  10. const collectLoopBodyBindingsVisitor = {
  11. "Expression|Declaration|Loop"(path) {
  12. path.skip();
  13. },
  14. Scope(path, state) {
  15. if (path.isFunctionParent()) path.skip();
  16. const {
  17. bindings
  18. } = path.scope;
  19. for (const name of Object.keys(bindings)) {
  20. const binding = bindings[name];
  21. if (binding.kind === "let" || binding.kind === "const" || binding.kind === "hoisted") {
  22. state.blockScoped.push(binding);
  23. }
  24. }
  25. }
  26. };
  27. function getLoopBodyBindings(loopPath) {
  28. const state = {
  29. blockScoped: []
  30. };
  31. loopPath.traverse(collectLoopBodyBindingsVisitor, state);
  32. return state.blockScoped;
  33. }
  34. function getUsageInBody(binding, loopPath) {
  35. const seen = new WeakSet();
  36. let capturedInClosure = false;
  37. const constantViolations = filterMap(binding.constantViolations, path => {
  38. const {
  39. inBody,
  40. inClosure
  41. } = relativeLoopLocation(path, loopPath);
  42. if (!inBody) return null;
  43. capturedInClosure || (capturedInClosure = inClosure);
  44. const id = path.isUpdateExpression() ? path.get("argument") : path.isAssignmentExpression() ? path.get("left") : null;
  45. if (id) seen.add(id.node);
  46. return id;
  47. });
  48. const references = filterMap(binding.referencePaths, path => {
  49. if (seen.has(path.node)) return null;
  50. const {
  51. inBody,
  52. inClosure
  53. } = relativeLoopLocation(path, loopPath);
  54. if (!inBody) return null;
  55. capturedInClosure || (capturedInClosure = inClosure);
  56. return path;
  57. });
  58. return {
  59. capturedInClosure,
  60. hasConstantViolations: constantViolations.length > 0,
  61. usages: references.concat(constantViolations)
  62. };
  63. }
  64. function relativeLoopLocation(path, loopPath) {
  65. const bodyPath = loopPath.get("body");
  66. let inClosure = false;
  67. for (let currPath = path; currPath; currPath = currPath.parentPath) {
  68. if (currPath.isFunction() || currPath.isClass()) inClosure = true;
  69. if (currPath === bodyPath) {
  70. return {
  71. inBody: true,
  72. inClosure
  73. };
  74. } else if (currPath === loopPath) {
  75. return {
  76. inBody: false,
  77. inClosure
  78. };
  79. }
  80. }
  81. throw new Error("Internal Babel error: path is not in loop. Please report this as a bug.");
  82. }
  83. const collectCompletionsAndVarsVisitor = {
  84. Function(path) {
  85. path.skip();
  86. },
  87. LabeledStatement: {
  88. enter({
  89. node
  90. }, state) {
  91. state.labelsStack.push(node.label.name);
  92. },
  93. exit({
  94. node
  95. }, state) {
  96. const popped = state.labelsStack.pop();
  97. if (popped !== node.label.name) {
  98. throw new Error("Assertion failure. Please report this bug to Babel.");
  99. }
  100. }
  101. },
  102. Loop: {
  103. enter(_, state) {
  104. state.labellessContinueTargets++;
  105. state.labellessBreakTargets++;
  106. },
  107. exit(_, state) {
  108. state.labellessContinueTargets--;
  109. state.labellessBreakTargets--;
  110. }
  111. },
  112. SwitchStatement: {
  113. enter(_, state) {
  114. state.labellessBreakTargets++;
  115. },
  116. exit(_, state) {
  117. state.labellessBreakTargets--;
  118. }
  119. },
  120. "BreakStatement|ContinueStatement"(path, state) {
  121. const {
  122. label
  123. } = path.node;
  124. if (label) {
  125. if (state.labelsStack.includes(label.name)) return;
  126. } else if (path.isBreakStatement() ? state.labellessBreakTargets > 0 : state.labellessContinueTargets > 0) {
  127. return;
  128. }
  129. state.breaksContinues.push(path);
  130. },
  131. ReturnStatement(path, state) {
  132. state.returns.push(path);
  133. },
  134. VariableDeclaration(path, state) {
  135. if (path.parent === state.loopNode && isVarInLoopHead(path)) return;
  136. if (path.node.kind === "var") state.vars.push(path);
  137. }
  138. };
  139. function wrapLoopBody(loopPath, captured, updatedBindingsUsages) {
  140. const loopNode = loopPath.node;
  141. const state = {
  142. breaksContinues: [],
  143. returns: [],
  144. labelsStack: [],
  145. labellessBreakTargets: 0,
  146. labellessContinueTargets: 0,
  147. vars: [],
  148. loopNode
  149. };
  150. loopPath.traverse(collectCompletionsAndVarsVisitor, state);
  151. const callArgs = [];
  152. const closureParams = [];
  153. const updater = [];
  154. for (const [name, updatedUsage] of updatedBindingsUsages) {
  155. callArgs.push(_core.types.identifier(name));
  156. const innerName = loopPath.scope.generateUid(name);
  157. closureParams.push(_core.types.identifier(innerName));
  158. updater.push(_core.types.assignmentExpression("=", _core.types.identifier(name), _core.types.identifier(innerName)));
  159. for (const path of updatedUsage) path.replaceWith(_core.types.identifier(innerName));
  160. }
  161. for (const name of captured) {
  162. if (updatedBindingsUsages.has(name)) continue;
  163. callArgs.push(_core.types.identifier(name));
  164. closureParams.push(_core.types.identifier(name));
  165. }
  166. const id = loopPath.scope.generateUid("loop");
  167. const fn = _core.types.functionExpression(null, closureParams, _core.types.toBlock(loopNode.body));
  168. let call = _core.types.callExpression(_core.types.identifier(id), callArgs);
  169. const fnParent = loopPath.findParent(p => p.isFunction());
  170. if (fnParent) {
  171. const {
  172. async,
  173. generator
  174. } = fnParent.node;
  175. fn.async = async;
  176. fn.generator = generator;
  177. if (generator) call = _core.types.yieldExpression(call, true);else if (async) call = _core.types.awaitExpression(call);
  178. }
  179. const updaterNode = updater.length > 0 ? _core.types.expressionStatement(_core.types.sequenceExpression(updater)) : null;
  180. if (updaterNode) fn.body.body.push(updaterNode);
  181. const [varPath] = loopPath.insertBefore(_core.types.variableDeclaration("var", [_core.types.variableDeclarator(_core.types.identifier(id), fn)]));
  182. const bodyStmts = [];
  183. const varNames = [];
  184. for (const varPath of state.vars) {
  185. const assign = [];
  186. for (const decl of varPath.node.declarations) {
  187. varNames.push(...Object.keys(_core.types.getBindingIdentifiers(decl.id)));
  188. if (decl.init) {
  189. assign.push(_core.types.assignmentExpression("=", decl.id, decl.init));
  190. }
  191. }
  192. if (assign.length > 0) {
  193. let replacement = assign.length === 1 ? assign[0] : _core.types.sequenceExpression(assign);
  194. if (!_core.types.isForStatement(varPath.parent, {
  195. init: varPath.node
  196. }) && !_core.types.isForXStatement(varPath.parent, {
  197. left: varPath.node
  198. })) {
  199. replacement = _core.types.expressionStatement(replacement);
  200. }
  201. varPath.replaceWith(replacement);
  202. } else {
  203. varPath.remove();
  204. }
  205. }
  206. if (varNames.length) {
  207. varPath.pushContainer("declarations", varNames.map(name => _core.types.variableDeclarator(_core.types.identifier(name))));
  208. }
  209. const labelNum = state.breaksContinues.length;
  210. const returnNum = state.returns.length;
  211. if (labelNum + returnNum === 0) {
  212. bodyStmts.push(_core.types.expressionStatement(call));
  213. } else if (labelNum === 1 && returnNum === 0) {
  214. for (const path of state.breaksContinues) {
  215. const {
  216. node
  217. } = path;
  218. const {
  219. type,
  220. label
  221. } = node;
  222. let name = type === "BreakStatement" ? "break" : "continue";
  223. if (label) name += " " + label.name;
  224. path.replaceWith(_core.types.addComment(_core.types.returnStatement(_core.types.numericLiteral(1)), "trailing", " " + name, true));
  225. if (updaterNode) path.insertBefore(_core.types.cloneNode(updaterNode));
  226. bodyStmts.push(_core.template.statement.ast`
  227. if (${call}) ${node}
  228. `);
  229. }
  230. } else {
  231. const completionId = loopPath.scope.generateUid("ret");
  232. if (varPath.isVariableDeclaration()) {
  233. varPath.pushContainer("declarations", [_core.types.variableDeclarator(_core.types.identifier(completionId))]);
  234. bodyStmts.push(_core.types.expressionStatement(_core.types.assignmentExpression("=", _core.types.identifier(completionId), call)));
  235. } else {
  236. bodyStmts.push(_core.types.variableDeclaration("var", [_core.types.variableDeclarator(_core.types.identifier(completionId), call)]));
  237. }
  238. const injected = [];
  239. for (const path of state.breaksContinues) {
  240. const {
  241. node
  242. } = path;
  243. const {
  244. type,
  245. label
  246. } = node;
  247. let name = type === "BreakStatement" ? "break" : "continue";
  248. if (label) name += " " + label.name;
  249. let i = injected.indexOf(name);
  250. const hasInjected = i !== -1;
  251. if (!hasInjected) {
  252. injected.push(name);
  253. i = injected.length - 1;
  254. }
  255. path.replaceWith(_core.types.addComment(_core.types.returnStatement(_core.types.numericLiteral(i)), "trailing", " " + name, true));
  256. if (updaterNode) path.insertBefore(_core.types.cloneNode(updaterNode));
  257. if (hasInjected) continue;
  258. bodyStmts.push(_core.template.statement.ast`
  259. if (${_core.types.identifier(completionId)} === ${_core.types.numericLiteral(i)}) ${node}
  260. `);
  261. }
  262. if (returnNum) {
  263. for (const path of state.returns) {
  264. const arg = path.node.argument || path.scope.buildUndefinedNode();
  265. path.replaceWith(_core.template.statement.ast`
  266. return { v: ${arg} };
  267. `);
  268. }
  269. bodyStmts.push(_core.template.statement.ast`
  270. if (${_core.types.identifier(completionId)}) return ${_core.types.identifier(completionId)}.v;
  271. `);
  272. }
  273. }
  274. loopNode.body = _core.types.blockStatement(bodyStmts);
  275. return varPath;
  276. }
  277. function isVarInLoopHead(path) {
  278. if (_core.types.isForStatement(path.parent)) return path.key === "init";
  279. if (_core.types.isForXStatement(path.parent)) return path.key === "left";
  280. return false;
  281. }
  282. function filterMap(list, fn) {
  283. const result = [];
  284. for (const item of list) {
  285. const mapped = fn(item);
  286. if (mapped) result.push(mapped);
  287. }
  288. return result;
  289. }
  290. //# sourceMappingURL=loop.js.map