index.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881
  1. import { declare } from "@babel/helper-plugin-utils";
  2. import type NodePath from "@babel/traverse";
  3. import type Scope from "@babel/traverse";
  4. import { visitor as tdzVisitor } from "./tdz";
  5. import values from "lodash/values";
  6. import extend from "lodash/extend";
  7. import { traverse, template, types as t } from "@babel/core";
  8. const DONE = new WeakSet();
  9. export default declare((api, opts) => {
  10. api.assertVersion(7);
  11. const { throwIfClosureRequired = false, tdz: tdzEnabled = false } = opts;
  12. if (typeof throwIfClosureRequired !== "boolean") {
  13. throw new Error(`.throwIfClosureRequired must be a boolean, or undefined`);
  14. }
  15. if (typeof tdzEnabled !== "boolean") {
  16. throw new Error(`.throwIfClosureRequired must be a boolean, or undefined`);
  17. }
  18. return {
  19. visitor: {
  20. VariableDeclaration(path) {
  21. const { node, parent, scope } = path;
  22. if (!isBlockScoped(node)) return;
  23. convertBlockScopedToVar(path, null, parent, scope, true);
  24. if (node._tdzThis) {
  25. const nodes = [node];
  26. for (let i = 0; i < node.declarations.length; i++) {
  27. const decl = node.declarations[i];
  28. if (decl.init) {
  29. const assign = t.assignmentExpression("=", decl.id, decl.init);
  30. assign._ignoreBlockScopingTDZ = true;
  31. nodes.push(t.expressionStatement(assign));
  32. }
  33. decl.init = this.addHelper("temporalUndefined");
  34. }
  35. node._blockHoist = 2;
  36. if (path.isCompletionRecord()) {
  37. // ensure we don't break completion record semantics by returning
  38. // the initialiser of the last declarator
  39. nodes.push(t.expressionStatement(scope.buildUndefinedNode()));
  40. }
  41. path.replaceWithMultiple(nodes);
  42. }
  43. },
  44. Loop(path, state) {
  45. const { parent, scope } = path;
  46. path.ensureBlock();
  47. const blockScoping = new BlockScoping(
  48. path,
  49. path.get("body"),
  50. parent,
  51. scope,
  52. throwIfClosureRequired,
  53. tdzEnabled,
  54. state,
  55. );
  56. const replace = blockScoping.run();
  57. if (replace) path.replaceWith(replace);
  58. },
  59. CatchClause(path, state) {
  60. const { parent, scope } = path;
  61. const blockScoping = new BlockScoping(
  62. null,
  63. path.get("body"),
  64. parent,
  65. scope,
  66. throwIfClosureRequired,
  67. tdzEnabled,
  68. state,
  69. );
  70. blockScoping.run();
  71. },
  72. "BlockStatement|SwitchStatement|Program"(path, state) {
  73. if (!ignoreBlock(path)) {
  74. const blockScoping = new BlockScoping(
  75. null,
  76. path,
  77. path.parent,
  78. path.scope,
  79. throwIfClosureRequired,
  80. tdzEnabled,
  81. state,
  82. );
  83. blockScoping.run();
  84. }
  85. },
  86. },
  87. };
  88. });
  89. function ignoreBlock(path) {
  90. return t.isLoop(path.parent) || t.isCatchClause(path.parent);
  91. }
  92. const buildRetCheck = template(`
  93. if (typeof RETURN === "object") return RETURN.v;
  94. `);
  95. function isBlockScoped(node) {
  96. if (!t.isVariableDeclaration(node)) return false;
  97. if (node[t.BLOCK_SCOPED_SYMBOL]) return true;
  98. if (node.kind !== "let" && node.kind !== "const") return false;
  99. return true;
  100. }
  101. /**
  102. * If there is a loop ancestor closer than the closest function, we
  103. * consider ourselves to be in a loop.
  104. */
  105. function isInLoop(path) {
  106. const loopOrFunctionParent = path.find(
  107. path => path.isLoop() || path.isFunction(),
  108. );
  109. return loopOrFunctionParent && loopOrFunctionParent.isLoop();
  110. }
  111. function convertBlockScopedToVar(
  112. path,
  113. node,
  114. parent,
  115. scope,
  116. moveBindingsToParent = false,
  117. ) {
  118. if (!node) {
  119. node = path.node;
  120. }
  121. // https://github.com/babel/babel/issues/255
  122. if (isInLoop(path) && !t.isFor(parent)) {
  123. for (let i = 0; i < node.declarations.length; i++) {
  124. const declar = node.declarations[i];
  125. declar.init = declar.init || scope.buildUndefinedNode();
  126. }
  127. }
  128. node[t.BLOCK_SCOPED_SYMBOL] = true;
  129. node.kind = "var";
  130. // Move bindings from current block scope to function scope.
  131. if (moveBindingsToParent) {
  132. const parentScope = scope.getFunctionParent() || scope.getProgramParent();
  133. const ids = path.getBindingIdentifiers();
  134. for (const name in ids) {
  135. const binding = scope.getOwnBinding(name);
  136. if (binding) binding.kind = "var";
  137. scope.moveBindingTo(name, parentScope);
  138. }
  139. }
  140. }
  141. function isVar(node) {
  142. return t.isVariableDeclaration(node, { kind: "var" }) && !isBlockScoped(node);
  143. }
  144. const letReferenceBlockVisitor = traverse.visitors.merge([
  145. {
  146. Loop: {
  147. enter(path, state) {
  148. state.loopDepth++;
  149. },
  150. exit(path, state) {
  151. state.loopDepth--;
  152. },
  153. },
  154. Function(path, state) {
  155. // References to block-scoped variables only require added closures if it's
  156. // possible for the code to run more than once -- otherwise it is safe to
  157. // simply rename the variables.
  158. if (state.loopDepth > 0) {
  159. path.traverse(letReferenceFunctionVisitor, state);
  160. }
  161. return path.skip();
  162. },
  163. },
  164. tdzVisitor,
  165. ]);
  166. const letReferenceFunctionVisitor = traverse.visitors.merge([
  167. {
  168. ReferencedIdentifier(path, state) {
  169. const ref = state.letReferences[path.node.name];
  170. // not a part of our scope
  171. if (!ref) return;
  172. // this scope has a variable with the same name so it couldn't belong
  173. // to our let scope
  174. const localBinding = path.scope.getBindingIdentifier(path.node.name);
  175. if (localBinding && localBinding !== ref) return;
  176. state.closurify = true;
  177. },
  178. },
  179. tdzVisitor,
  180. ]);
  181. const hoistVarDeclarationsVisitor = {
  182. enter(path, self) {
  183. const { node, parent } = path;
  184. if (path.isForStatement()) {
  185. if (isVar(node.init, node)) {
  186. const nodes = self.pushDeclar(node.init);
  187. if (nodes.length === 1) {
  188. node.init = nodes[0];
  189. } else {
  190. node.init = t.sequenceExpression(nodes);
  191. }
  192. }
  193. } else if (path.isFor()) {
  194. if (isVar(node.left, node)) {
  195. self.pushDeclar(node.left);
  196. node.left = node.left.declarations[0].id;
  197. }
  198. } else if (isVar(node, parent)) {
  199. path.replaceWithMultiple(
  200. self.pushDeclar(node).map(expr => t.expressionStatement(expr)),
  201. );
  202. } else if (path.isFunction()) {
  203. return path.skip();
  204. }
  205. },
  206. };
  207. const loopLabelVisitor = {
  208. LabeledStatement({ node }, state) {
  209. state.innerLabels.push(node.label.name);
  210. },
  211. };
  212. const continuationVisitor = {
  213. enter(path, state) {
  214. if (path.isAssignmentExpression() || path.isUpdateExpression()) {
  215. const bindings = path.getBindingIdentifiers();
  216. for (const name in bindings) {
  217. if (
  218. state.outsideReferences[name] !==
  219. path.scope.getBindingIdentifier(name)
  220. ) {
  221. continue;
  222. }
  223. state.reassignments[name] = true;
  224. }
  225. } else if (path.isReturnStatement()) {
  226. state.returnStatements.push(path);
  227. }
  228. },
  229. };
  230. function loopNodeTo(node) {
  231. if (t.isBreakStatement(node)) {
  232. return "break";
  233. } else if (t.isContinueStatement(node)) {
  234. return "continue";
  235. }
  236. }
  237. const loopVisitor = {
  238. Loop(path, state) {
  239. const oldIgnoreLabeless = state.ignoreLabeless;
  240. state.ignoreLabeless = true;
  241. path.traverse(loopVisitor, state);
  242. state.ignoreLabeless = oldIgnoreLabeless;
  243. path.skip();
  244. },
  245. Function(path) {
  246. path.skip();
  247. },
  248. SwitchCase(path, state) {
  249. const oldInSwitchCase = state.inSwitchCase;
  250. state.inSwitchCase = true;
  251. path.traverse(loopVisitor, state);
  252. state.inSwitchCase = oldInSwitchCase;
  253. path.skip();
  254. },
  255. "BreakStatement|ContinueStatement|ReturnStatement"(path, state) {
  256. const { node, parent, scope } = path;
  257. if (node[this.LOOP_IGNORE]) return;
  258. let replace;
  259. let loopText = loopNodeTo(node);
  260. if (loopText) {
  261. if (node.label) {
  262. // we shouldn't be transforming this because it exists somewhere inside
  263. if (state.innerLabels.indexOf(node.label.name) >= 0) {
  264. return;
  265. }
  266. loopText = `${loopText}|${node.label.name}`;
  267. } else {
  268. // we shouldn't be transforming these statements because
  269. // they don't refer to the actual loop we're scopifying
  270. if (state.ignoreLabeless) return;
  271. // break statements mean something different in this context
  272. if (t.isBreakStatement(node) && t.isSwitchCase(parent)) return;
  273. }
  274. state.hasBreakContinue = true;
  275. state.map[loopText] = node;
  276. replace = t.stringLiteral(loopText);
  277. }
  278. if (path.isReturnStatement()) {
  279. state.hasReturn = true;
  280. replace = t.objectExpression([
  281. t.objectProperty(
  282. t.identifier("v"),
  283. node.argument || scope.buildUndefinedNode(),
  284. ),
  285. ]);
  286. }
  287. if (replace) {
  288. replace = t.returnStatement(replace);
  289. replace[this.LOOP_IGNORE] = true;
  290. path.skip();
  291. path.replaceWith(t.inherits(replace, node));
  292. }
  293. },
  294. };
  295. class BlockScoping {
  296. constructor(
  297. loopPath?: NodePath,
  298. blockPath: NodePath,
  299. parent: Object,
  300. scope: Scope,
  301. throwIfClosureRequired: boolean,
  302. tdzEnabled: boolean,
  303. state: Object,
  304. ) {
  305. this.parent = parent;
  306. this.scope = scope;
  307. this.state = state;
  308. this.throwIfClosureRequired = throwIfClosureRequired;
  309. this.tdzEnabled = tdzEnabled;
  310. this.blockPath = blockPath;
  311. this.block = blockPath.node;
  312. this.outsideLetReferences = Object.create(null);
  313. this.hasLetReferences = false;
  314. this.letReferences = Object.create(null);
  315. this.body = [];
  316. if (loopPath) {
  317. this.loopParent = loopPath.parent;
  318. this.loopLabel =
  319. t.isLabeledStatement(this.loopParent) && this.loopParent.label;
  320. this.loopPath = loopPath;
  321. this.loop = loopPath.node;
  322. }
  323. }
  324. /**
  325. * Start the ball rolling.
  326. */
  327. run() {
  328. const block = this.block;
  329. if (DONE.has(block)) return;
  330. DONE.add(block);
  331. const needsClosure = this.getLetReferences();
  332. this.checkConstants();
  333. // this is a block within a `Function/Program` so we can safely leave it be
  334. if (t.isFunction(this.parent) || t.isProgram(this.block)) {
  335. this.updateScopeInfo();
  336. return;
  337. }
  338. // we can skip everything
  339. if (!this.hasLetReferences) return;
  340. if (needsClosure) {
  341. this.wrapClosure();
  342. } else {
  343. this.remap();
  344. }
  345. this.updateScopeInfo(needsClosure);
  346. if (this.loopLabel && !t.isLabeledStatement(this.loopParent)) {
  347. return t.labeledStatement(this.loopLabel, this.loop);
  348. }
  349. }
  350. checkConstants() {
  351. const scope = this.scope;
  352. const state = this.state;
  353. for (const name in scope.bindings) {
  354. const binding = scope.bindings[name];
  355. if (binding.kind !== "const") continue;
  356. for (const violation of (binding.constantViolations: Array)) {
  357. const readOnlyError = state.addHelper("readOnlyError");
  358. const throwNode = t.callExpression(readOnlyError, [
  359. t.stringLiteral(name),
  360. ]);
  361. if (violation.isAssignmentExpression()) {
  362. violation
  363. .get("right")
  364. .replaceWith(
  365. t.sequenceExpression([throwNode, violation.get("right").node]),
  366. );
  367. } else if (violation.isUpdateExpression()) {
  368. violation.replaceWith(
  369. t.sequenceExpression([throwNode, violation.node]),
  370. );
  371. } else if (violation.isForXStatement()) {
  372. violation.ensureBlock();
  373. violation.node.body.body.unshift(t.expressionStatement(throwNode));
  374. }
  375. }
  376. }
  377. }
  378. updateScopeInfo(wrappedInClosure) {
  379. const scope = this.scope;
  380. const parentScope = scope.getFunctionParent() || scope.getProgramParent();
  381. const letRefs = this.letReferences;
  382. for (const key in letRefs) {
  383. const ref = letRefs[key];
  384. const binding = scope.getBinding(ref.name);
  385. if (!binding) continue;
  386. if (binding.kind === "let" || binding.kind === "const") {
  387. binding.kind = "var";
  388. if (wrappedInClosure) {
  389. scope.removeBinding(ref.name);
  390. } else {
  391. scope.moveBindingTo(ref.name, parentScope);
  392. }
  393. }
  394. }
  395. }
  396. remap() {
  397. const letRefs = this.letReferences;
  398. const scope = this.scope;
  399. // alright, so since we aren't wrapping this block in a closure
  400. // we have to check if any of our let variables collide with
  401. // those in upper scopes and then if they do, generate a uid
  402. // for them and replace all references with it
  403. for (const key in letRefs) {
  404. // just an Identifier node we collected in `getLetReferences`
  405. // this is the defining identifier of a declaration
  406. const ref = letRefs[key];
  407. // todo: could skip this if the colliding binding is in another function
  408. if (scope.parentHasBinding(key) || scope.hasGlobal(key)) {
  409. // The same identifier might have been bound separately in the block scope and
  410. // the enclosing scope (e.g. loop or catch statement), so we should handle both
  411. // individually
  412. if (scope.hasOwnBinding(key)) {
  413. scope.rename(ref.name);
  414. }
  415. if (this.blockPath.scope.hasOwnBinding(key)) {
  416. this.blockPath.scope.rename(ref.name);
  417. }
  418. }
  419. }
  420. }
  421. wrapClosure() {
  422. if (this.throwIfClosureRequired) {
  423. throw this.blockPath.buildCodeFrameError(
  424. "Compiling let/const in this block would add a closure " +
  425. "(throwIfClosureRequired).",
  426. );
  427. }
  428. const block = this.block;
  429. const outsideRefs = this.outsideLetReferences;
  430. // remap loop heads with colliding variables
  431. if (this.loop) {
  432. for (const name in outsideRefs) {
  433. const id = outsideRefs[name];
  434. if (
  435. this.scope.hasGlobal(id.name) ||
  436. this.scope.parentHasBinding(id.name)
  437. ) {
  438. delete outsideRefs[id.name];
  439. delete this.letReferences[id.name];
  440. this.scope.rename(id.name);
  441. this.letReferences[id.name] = id;
  442. outsideRefs[id.name] = id;
  443. }
  444. }
  445. }
  446. // if we're inside of a for loop then we search to see if there are any
  447. // `break`s, `continue`s, `return`s etc
  448. this.has = this.checkLoop();
  449. // hoist let references to retain scope
  450. this.hoistVarDeclarations();
  451. // turn outsideLetReferences into an array
  452. const args = values(outsideRefs).map(id => t.cloneNode(id));
  453. const params = args.map(id => t.cloneNode(id));
  454. const isSwitch = this.blockPath.isSwitchStatement();
  455. // build the closure that we're going to wrap the block with, possible wrapping switch(){}
  456. const fn = t.functionExpression(
  457. null,
  458. params,
  459. t.blockStatement(isSwitch ? [block] : block.body),
  460. );
  461. // continuation
  462. this.addContinuations(fn);
  463. let call = t.callExpression(t.nullLiteral(), args);
  464. let basePath = ".callee";
  465. // handle generators
  466. const hasYield = traverse.hasType(
  467. fn.body,
  468. "YieldExpression",
  469. t.FUNCTION_TYPES,
  470. );
  471. if (hasYield) {
  472. fn.generator = true;
  473. call = t.yieldExpression(call, true);
  474. basePath = ".argument" + basePath;
  475. }
  476. // handlers async functions
  477. const hasAsync = traverse.hasType(
  478. fn.body,
  479. "AwaitExpression",
  480. t.FUNCTION_TYPES,
  481. );
  482. if (hasAsync) {
  483. fn.async = true;
  484. call = t.awaitExpression(call);
  485. basePath = ".argument" + basePath;
  486. }
  487. let placeholderPath;
  488. let index;
  489. if (this.has.hasReturn || this.has.hasBreakContinue) {
  490. const ret = this.scope.generateUid("ret");
  491. this.body.push(
  492. t.variableDeclaration("var", [
  493. t.variableDeclarator(t.identifier(ret), call),
  494. ]),
  495. );
  496. placeholderPath = "declarations.0.init" + basePath;
  497. index = this.body.length - 1;
  498. this.buildHas(ret);
  499. } else {
  500. this.body.push(t.expressionStatement(call));
  501. placeholderPath = "expression" + basePath;
  502. index = this.body.length - 1;
  503. }
  504. let callPath;
  505. // replace the current block body with the one we're going to build
  506. if (isSwitch) {
  507. const { parentPath, listKey, key } = this.blockPath;
  508. this.blockPath.replaceWithMultiple(this.body);
  509. callPath = parentPath.get(listKey)[key + index];
  510. } else {
  511. block.body = this.body;
  512. callPath = this.blockPath.get("body")[index];
  513. }
  514. const placeholder = callPath.get(placeholderPath);
  515. let fnPath;
  516. if (this.loop) {
  517. const loopId = this.scope.generateUid("loop");
  518. const p = this.loopPath.insertBefore(
  519. t.variableDeclaration("var", [
  520. t.variableDeclarator(t.identifier(loopId), fn),
  521. ]),
  522. );
  523. placeholder.replaceWith(t.identifier(loopId));
  524. fnPath = p[0].get("declarations.0.init");
  525. } else {
  526. placeholder.replaceWith(fn);
  527. fnPath = placeholder;
  528. }
  529. // Ensure "this", "arguments", and "super" continue to work in the wrapped function.
  530. fnPath.unwrapFunctionEnvironment();
  531. }
  532. /**
  533. * If any of the outer let variables are reassigned then we need to rename them in
  534. * the closure so we can get direct access to the outer variable to continue the
  535. * iteration with bindings based on each iteration.
  536. *
  537. * Reference: https://github.com/babel/babel/issues/1078
  538. */
  539. addContinuations(fn) {
  540. const state = {
  541. reassignments: {},
  542. returnStatements: [],
  543. outsideReferences: this.outsideLetReferences,
  544. };
  545. this.scope.traverse(fn, continuationVisitor, state);
  546. for (let i = 0; i < fn.params.length; i++) {
  547. const param = fn.params[i];
  548. if (!state.reassignments[param.name]) continue;
  549. const paramName = param.name;
  550. const newParamName = this.scope.generateUid(param.name);
  551. fn.params[i] = t.identifier(newParamName);
  552. this.scope.rename(paramName, newParamName, fn);
  553. state.returnStatements.forEach(returnStatement => {
  554. returnStatement.insertBefore(
  555. t.expressionStatement(
  556. t.assignmentExpression(
  557. "=",
  558. t.identifier(paramName),
  559. t.identifier(newParamName),
  560. ),
  561. ),
  562. );
  563. });
  564. // assign outer reference as it's been modified internally and needs to be retained
  565. fn.body.body.push(
  566. t.expressionStatement(
  567. t.assignmentExpression(
  568. "=",
  569. t.identifier(paramName),
  570. t.identifier(newParamName),
  571. ),
  572. ),
  573. );
  574. }
  575. }
  576. getLetReferences() {
  577. const block = this.block;
  578. let declarators = [];
  579. if (this.loop) {
  580. const init = this.loop.left || this.loop.init;
  581. if (isBlockScoped(init)) {
  582. declarators.push(init);
  583. extend(this.outsideLetReferences, t.getBindingIdentifiers(init));
  584. }
  585. }
  586. const addDeclarationsFromChild = (path, node) => {
  587. node = node || path.node;
  588. if (
  589. t.isClassDeclaration(node) ||
  590. t.isFunctionDeclaration(node) ||
  591. isBlockScoped(node)
  592. ) {
  593. if (isBlockScoped(node)) {
  594. convertBlockScopedToVar(path, node, block, this.scope);
  595. }
  596. declarators = declarators.concat(node.declarations || node);
  597. }
  598. if (t.isLabeledStatement(node)) {
  599. addDeclarationsFromChild(path.get("body"), node.body);
  600. }
  601. };
  602. //
  603. if (block.body) {
  604. const declarPaths = this.blockPath.get("body");
  605. for (let i = 0; i < block.body.length; i++) {
  606. addDeclarationsFromChild(declarPaths[i]);
  607. }
  608. }
  609. if (block.cases) {
  610. const declarPaths = this.blockPath.get("cases");
  611. for (let i = 0; i < block.cases.length; i++) {
  612. const consequents = block.cases[i].consequent;
  613. for (let j = 0; j < consequents.length; j++) {
  614. const declar = consequents[j];
  615. addDeclarationsFromChild(declarPaths[i], declar);
  616. }
  617. }
  618. }
  619. //
  620. for (let i = 0; i < declarators.length; i++) {
  621. const declar = declarators[i];
  622. // Passing true as the third argument causes t.getBindingIdentifiers
  623. // to return only the *outer* binding identifiers of this
  624. // declaration, rather than (for example) mistakenly including the
  625. // parameters of a function declaration. Fixes #4880.
  626. const keys = t.getBindingIdentifiers(declar, false, true);
  627. extend(this.letReferences, keys);
  628. this.hasLetReferences = true;
  629. }
  630. // no let references so we can just quit
  631. if (!this.hasLetReferences) return;
  632. const state = {
  633. letReferences: this.letReferences,
  634. closurify: false,
  635. loopDepth: 0,
  636. tdzEnabled: this.tdzEnabled,
  637. addHelper: name => this.addHelper(name),
  638. };
  639. if (isInLoop(this.blockPath)) {
  640. state.loopDepth++;
  641. }
  642. // traverse through this block, stopping on functions and checking if they
  643. // contain any local let references
  644. this.blockPath.traverse(letReferenceBlockVisitor, state);
  645. return state.closurify;
  646. }
  647. /**
  648. * If we're inside of a loop then traverse it and check if it has one of
  649. * the following node types `ReturnStatement`, `BreakStatement`,
  650. * `ContinueStatement` and replace it with a return value that we can track
  651. * later on.
  652. */
  653. checkLoop(): Object {
  654. const state = {
  655. hasBreakContinue: false,
  656. ignoreLabeless: false,
  657. inSwitchCase: false,
  658. innerLabels: [],
  659. hasReturn: false,
  660. isLoop: !!this.loop,
  661. map: {},
  662. LOOP_IGNORE: Symbol(),
  663. };
  664. this.blockPath.traverse(loopLabelVisitor, state);
  665. this.blockPath.traverse(loopVisitor, state);
  666. return state;
  667. }
  668. /**
  669. * Hoist all let declarations in this block to before it so they retain scope
  670. * once we wrap everything in a closure.
  671. */
  672. hoistVarDeclarations() {
  673. this.blockPath.traverse(hoistVarDeclarationsVisitor, this);
  674. }
  675. /**
  676. * Turn a `VariableDeclaration` into an array of `AssignmentExpressions` with
  677. * their declarations hoisted to before the closure wrapper.
  678. */
  679. pushDeclar(node: { type: "VariableDeclaration" }): Array<Object> {
  680. const declars = [];
  681. const names = t.getBindingIdentifiers(node);
  682. for (const name in names) {
  683. declars.push(t.variableDeclarator(names[name]));
  684. }
  685. this.body.push(t.variableDeclaration(node.kind, declars));
  686. const replace = [];
  687. for (let i = 0; i < node.declarations.length; i++) {
  688. const declar = node.declarations[i];
  689. if (!declar.init) continue;
  690. const expr = t.assignmentExpression(
  691. "=",
  692. t.cloneNode(declar.id),
  693. t.cloneNode(declar.init),
  694. );
  695. replace.push(t.inherits(expr, declar));
  696. }
  697. return replace;
  698. }
  699. buildHas(ret: string) {
  700. const body = this.body;
  701. let retCheck;
  702. const has = this.has;
  703. const cases = [];
  704. if (has.hasReturn) {
  705. // typeof ret === "object"
  706. retCheck = buildRetCheck({
  707. RETURN: t.identifier(ret),
  708. });
  709. }
  710. if (has.hasBreakContinue) {
  711. for (const key in has.map) {
  712. cases.push(t.switchCase(t.stringLiteral(key), [has.map[key]]));
  713. }
  714. if (has.hasReturn) {
  715. cases.push(t.switchCase(null, [retCheck]));
  716. }
  717. if (cases.length === 1) {
  718. const single = cases[0];
  719. body.push(
  720. t.ifStatement(
  721. t.binaryExpression("===", t.identifier(ret), single.test),
  722. single.consequent[0],
  723. ),
  724. );
  725. } else {
  726. if (this.loop) {
  727. // https://github.com/babel/babel/issues/998
  728. for (let i = 0; i < cases.length; i++) {
  729. const caseConsequent = cases[i].consequent[0];
  730. if (t.isBreakStatement(caseConsequent) && !caseConsequent.label) {
  731. if (!this.loopLabel) {
  732. this.loopLabel = this.scope.generateUidIdentifier("loop");
  733. }
  734. caseConsequent.label = t.cloneNode(this.loopLabel);
  735. }
  736. }
  737. }
  738. body.push(t.switchStatement(t.identifier(ret), cases));
  739. }
  740. } else {
  741. if (has.hasReturn) {
  742. body.push(retCheck);
  743. }
  744. }
  745. }
  746. }