emit.js 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308
  1. /**
  2. * Copyright (c) 2014-present, Facebook, Inc.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. */
  7. import assert from "assert";
  8. import * as leap from "./leap";
  9. import * as meta from "./meta";
  10. import * as util from "./util";
  11. let hasOwn = Object.prototype.hasOwnProperty;
  12. function Emitter(contextId) {
  13. assert.ok(this instanceof Emitter);
  14. util.getTypes().assertIdentifier(contextId);
  15. // Used to generate unique temporary names.
  16. this.nextTempId = 0;
  17. // In order to make sure the context object does not collide with
  18. // anything in the local scope, we might have to rename it, so we
  19. // refer to it symbolically instead of just assuming that it will be
  20. // called "context".
  21. this.contextId = contextId;
  22. // An append-only list of Statements that grows each time this.emit is
  23. // called.
  24. this.listing = [];
  25. // A sparse array whose keys correspond to locations in this.listing
  26. // that have been marked as branch/jump targets.
  27. this.marked = [true];
  28. this.insertedLocs = new Set();
  29. // The last location will be marked when this.getDispatchLoop is
  30. // called.
  31. this.finalLoc = this.loc();
  32. // A list of all leap.TryEntry statements emitted.
  33. this.tryEntries = [];
  34. // Each time we evaluate the body of a loop, we tell this.leapManager
  35. // to enter a nested loop context that determines the meaning of break
  36. // and continue statements therein.
  37. this.leapManager = new leap.LeapManager(this);
  38. }
  39. let Ep = Emitter.prototype;
  40. exports.Emitter = Emitter;
  41. // Offsets into this.listing that could be used as targets for branches or
  42. // jumps are represented as numeric Literal nodes. This representation has
  43. // the amazingly convenient benefit of allowing the exact value of the
  44. // location to be determined at any time, even after generating code that
  45. // refers to the location.
  46. // We use 'Number.MAX_VALUE' to mark uninitialized location. We can safely do
  47. // so because no code can realistically have about 1.8e+308 locations before
  48. // hitting memory limit of the machine it's running on. For comparison, the
  49. // estimated number of atoms in the observable universe is around 1e+80.
  50. const PENDING_LOCATION = Number.MAX_VALUE;
  51. Ep.loc = function() {
  52. const l = util.getTypes().numericLiteral(PENDING_LOCATION)
  53. this.insertedLocs.add(l);
  54. return l;
  55. }
  56. Ep.getInsertedLocs = function() {
  57. return this.insertedLocs;
  58. }
  59. Ep.getContextId = function() {
  60. return util.getTypes().clone(this.contextId);
  61. }
  62. // Sets the exact value of the given location to the offset of the next
  63. // Statement emitted.
  64. Ep.mark = function(loc) {
  65. util.getTypes().assertLiteral(loc);
  66. let index = this.listing.length;
  67. if (loc.value === PENDING_LOCATION) {
  68. loc.value = index;
  69. } else {
  70. // Locations can be marked redundantly, but their values cannot change
  71. // once set the first time.
  72. assert.strictEqual(loc.value, index);
  73. }
  74. this.marked[index] = true;
  75. return loc;
  76. };
  77. Ep.emit = function(node) {
  78. const t = util.getTypes();
  79. if (t.isExpression(node)) {
  80. node = t.expressionStatement(node);
  81. }
  82. t.assertStatement(node);
  83. this.listing.push(node);
  84. };
  85. // Shorthand for emitting assignment statements. This will come in handy
  86. // for assignments to temporary variables.
  87. Ep.emitAssign = function(lhs, rhs) {
  88. this.emit(this.assign(lhs, rhs));
  89. return lhs;
  90. };
  91. // Shorthand for an assignment statement.
  92. Ep.assign = function(lhs, rhs) {
  93. const t = util.getTypes();
  94. return t.expressionStatement(
  95. t.assignmentExpression("=", t.cloneDeep(lhs), rhs));
  96. };
  97. // Convenience function for generating expressions like context.next,
  98. // context.sent, and context.rval.
  99. Ep.contextProperty = function(name, computed) {
  100. const t = util.getTypes();
  101. return t.memberExpression(
  102. this.getContextId(),
  103. computed ? t.stringLiteral(name) : t.identifier(name),
  104. !!computed
  105. );
  106. };
  107. // Shorthand for setting context.rval and jumping to `context.stop()`.
  108. Ep.stop = function(rval) {
  109. if (rval) {
  110. this.setReturnValue(rval);
  111. }
  112. this.jump(this.finalLoc);
  113. };
  114. Ep.setReturnValue = function(valuePath) {
  115. util.getTypes().assertExpression(valuePath.value);
  116. this.emitAssign(
  117. this.contextProperty("rval"),
  118. this.explodeExpression(valuePath)
  119. );
  120. };
  121. Ep.clearPendingException = function(tryLoc, assignee) {
  122. const t = util.getTypes();
  123. t.assertLiteral(tryLoc);
  124. let catchCall = t.callExpression(
  125. this.contextProperty("catch", true),
  126. [t.clone(tryLoc)]
  127. );
  128. if (assignee) {
  129. this.emitAssign(assignee, catchCall);
  130. } else {
  131. this.emit(catchCall);
  132. }
  133. };
  134. // Emits code for an unconditional jump to the given location, even if the
  135. // exact value of the location is not yet known.
  136. Ep.jump = function(toLoc) {
  137. this.emitAssign(this.contextProperty("next"), toLoc);
  138. this.emit(util.getTypes().breakStatement());
  139. };
  140. // Conditional jump.
  141. Ep.jumpIf = function(test, toLoc) {
  142. const t = util.getTypes();
  143. t.assertExpression(test);
  144. t.assertLiteral(toLoc);
  145. this.emit(t.ifStatement(
  146. test,
  147. t.blockStatement([
  148. this.assign(this.contextProperty("next"), toLoc),
  149. t.breakStatement()
  150. ])
  151. ));
  152. };
  153. // Conditional jump, with the condition negated.
  154. Ep.jumpIfNot = function(test, toLoc) {
  155. const t = util.getTypes();
  156. t.assertExpression(test);
  157. t.assertLiteral(toLoc);
  158. let negatedTest;
  159. if (t.isUnaryExpression(test) &&
  160. test.operator === "!") {
  161. // Avoid double negation.
  162. negatedTest = test.argument;
  163. } else {
  164. negatedTest = t.unaryExpression("!", test);
  165. }
  166. this.emit(t.ifStatement(
  167. negatedTest,
  168. t.blockStatement([
  169. this.assign(this.contextProperty("next"), toLoc),
  170. t.breakStatement()
  171. ])
  172. ));
  173. };
  174. // Returns a unique MemberExpression that can be used to store and
  175. // retrieve temporary values. Since the object of the member expression is
  176. // the context object, which is presumed to coexist peacefully with all
  177. // other local variables, and since we just increment `nextTempId`
  178. // monotonically, uniqueness is assured.
  179. Ep.makeTempVar = function() {
  180. return this.contextProperty("t" + this.nextTempId++);
  181. };
  182. Ep.getContextFunction = function(id) {
  183. const t = util.getTypes();
  184. return t.functionExpression(
  185. id || null/*Anonymous*/,
  186. [this.getContextId()],
  187. t.blockStatement([this.getDispatchLoop()]),
  188. false, // Not a generator anymore!
  189. false // Nor an expression.
  190. );
  191. };
  192. // Turns this.listing into a loop of the form
  193. //
  194. // while (1) switch (context.next) {
  195. // case 0:
  196. // ...
  197. // case n:
  198. // return context.stop();
  199. // }
  200. //
  201. // Each marked location in this.listing will correspond to one generated
  202. // case statement.
  203. Ep.getDispatchLoop = function() {
  204. const self = this;
  205. const t = util.getTypes();
  206. let cases = [];
  207. let current;
  208. // If we encounter a break, continue, or return statement in a switch
  209. // case, we can skip the rest of the statements until the next case.
  210. let alreadyEnded = false;
  211. self.listing.forEach(function(stmt, i) {
  212. if (self.marked.hasOwnProperty(i)) {
  213. cases.push(t.switchCase(
  214. t.numericLiteral(i),
  215. current = []));
  216. alreadyEnded = false;
  217. }
  218. if (!alreadyEnded) {
  219. current.push(stmt);
  220. if (t.isCompletionStatement(stmt))
  221. alreadyEnded = true;
  222. }
  223. });
  224. // Now that we know how many statements there will be in this.listing,
  225. // we can finally resolve this.finalLoc.value.
  226. this.finalLoc.value = this.listing.length;
  227. cases.push(
  228. t.switchCase(this.finalLoc, [
  229. // Intentionally fall through to the "end" case...
  230. ]),
  231. // So that the runtime can jump to the final location without having
  232. // to know its offset, we provide the "end" case as a synonym.
  233. t.switchCase(t.stringLiteral("end"), [
  234. // This will check/clear both context.thrown and context.rval.
  235. t.returnStatement(
  236. t.callExpression(this.contextProperty("stop"), [])
  237. )
  238. ])
  239. );
  240. return t.whileStatement(
  241. t.numericLiteral(1),
  242. t.switchStatement(
  243. t.assignmentExpression(
  244. "=",
  245. this.contextProperty("prev"),
  246. this.contextProperty("next")
  247. ),
  248. cases
  249. )
  250. );
  251. };
  252. Ep.getTryLocsList = function() {
  253. if (this.tryEntries.length === 0) {
  254. // To avoid adding a needless [] to the majority of runtime.wrap
  255. // argument lists, force the caller to handle this case specially.
  256. return null;
  257. }
  258. const t = util.getTypes();
  259. let lastLocValue = 0;
  260. return t.arrayExpression(
  261. this.tryEntries.map(function(tryEntry) {
  262. let thisLocValue = tryEntry.firstLoc.value;
  263. assert.ok(thisLocValue >= lastLocValue, "try entries out of order");
  264. lastLocValue = thisLocValue;
  265. let ce = tryEntry.catchEntry;
  266. let fe = tryEntry.finallyEntry;
  267. let locs = [
  268. tryEntry.firstLoc,
  269. // The null here makes a hole in the array.
  270. ce ? ce.firstLoc : null
  271. ];
  272. if (fe) {
  273. locs[2] = fe.firstLoc;
  274. locs[3] = fe.afterLoc;
  275. }
  276. return t.arrayExpression(locs.map(loc => loc && t.clone(loc)));
  277. })
  278. );
  279. };
  280. // All side effects must be realized in order.
  281. // If any subexpression harbors a leap, all subexpressions must be
  282. // neutered of side effects.
  283. // No destructive modification of AST nodes.
  284. Ep.explode = function(path, ignoreResult) {
  285. const t = util.getTypes();
  286. let node = path.node;
  287. let self = this;
  288. t.assertNode(node);
  289. if (t.isDeclaration(node))
  290. throw getDeclError(node);
  291. if (t.isStatement(node))
  292. return self.explodeStatement(path);
  293. if (t.isExpression(node))
  294. return self.explodeExpression(path, ignoreResult);
  295. switch (node.type) {
  296. case "Program":
  297. return path.get("body").map(
  298. self.explodeStatement,
  299. self
  300. );
  301. case "VariableDeclarator":
  302. throw getDeclError(node);
  303. // These node types should be handled by their parent nodes
  304. // (ObjectExpression, SwitchStatement, and TryStatement, respectively).
  305. case "Property":
  306. case "SwitchCase":
  307. case "CatchClause":
  308. throw new Error(
  309. node.type + " nodes should be handled by their parents");
  310. default:
  311. throw new Error(
  312. "unknown Node of type " +
  313. JSON.stringify(node.type));
  314. }
  315. };
  316. function getDeclError(node) {
  317. return new Error(
  318. "all declarations should have been transformed into " +
  319. "assignments before the Exploder began its work: " +
  320. JSON.stringify(node));
  321. }
  322. Ep.explodeStatement = function(path, labelId) {
  323. const t = util.getTypes();
  324. let stmt = path.node;
  325. let self = this;
  326. let before, after, head;
  327. t.assertStatement(stmt);
  328. if (labelId) {
  329. t.assertIdentifier(labelId);
  330. } else {
  331. labelId = null;
  332. }
  333. // Explode BlockStatement nodes even if they do not contain a yield,
  334. // because we don't want or need the curly braces.
  335. if (t.isBlockStatement(stmt)) {
  336. path.get("body").forEach(function (path) {
  337. self.explodeStatement(path);
  338. });
  339. return;
  340. }
  341. if (!meta.containsLeap(stmt)) {
  342. // Technically we should be able to avoid emitting the statement
  343. // altogether if !meta.hasSideEffects(stmt), but that leads to
  344. // confusing generated code (for instance, `while (true) {}` just
  345. // disappears) and is probably a more appropriate job for a dedicated
  346. // dead code elimination pass.
  347. self.emit(stmt);
  348. return;
  349. }
  350. switch (stmt.type) {
  351. case "ExpressionStatement":
  352. self.explodeExpression(path.get("expression"), true);
  353. break;
  354. case "LabeledStatement":
  355. after = this.loc();
  356. // Did you know you can break from any labeled block statement or
  357. // control structure? Well, you can! Note: when a labeled loop is
  358. // encountered, the leap.LabeledEntry created here will immediately
  359. // enclose a leap.LoopEntry on the leap manager's stack, and both
  360. // entries will have the same label. Though this works just fine, it
  361. // may seem a bit redundant. In theory, we could check here to
  362. // determine if stmt knows how to handle its own label; for example,
  363. // stmt happens to be a WhileStatement and so we know it's going to
  364. // establish its own LoopEntry when we explode it (below). Then this
  365. // LabeledEntry would be unnecessary. Alternatively, we might be
  366. // tempted not to pass stmt.label down into self.explodeStatement,
  367. // because we've handled the label here, but that's a mistake because
  368. // labeled loops may contain labeled continue statements, which is not
  369. // something we can handle in this generic case. All in all, I think a
  370. // little redundancy greatly simplifies the logic of this case, since
  371. // it's clear that we handle all possible LabeledStatements correctly
  372. // here, regardless of whether they interact with the leap manager
  373. // themselves. Also remember that labels and break/continue-to-label
  374. // statements are rare, and all of this logic happens at transform
  375. // time, so it has no additional runtime cost.
  376. self.leapManager.withEntry(
  377. new leap.LabeledEntry(after, stmt.label),
  378. function() {
  379. self.explodeStatement(path.get("body"), stmt.label);
  380. }
  381. );
  382. self.mark(after);
  383. break;
  384. case "WhileStatement":
  385. before = this.loc();
  386. after = this.loc();
  387. self.mark(before);
  388. self.jumpIfNot(self.explodeExpression(path.get("test")), after);
  389. self.leapManager.withEntry(
  390. new leap.LoopEntry(after, before, labelId),
  391. function() { self.explodeStatement(path.get("body")); }
  392. );
  393. self.jump(before);
  394. self.mark(after);
  395. break;
  396. case "DoWhileStatement":
  397. let first = this.loc();
  398. let test = this.loc();
  399. after = this.loc();
  400. self.mark(first);
  401. self.leapManager.withEntry(
  402. new leap.LoopEntry(after, test, labelId),
  403. function() { self.explode(path.get("body")); }
  404. );
  405. self.mark(test);
  406. self.jumpIf(self.explodeExpression(path.get("test")), first);
  407. self.mark(after);
  408. break;
  409. case "ForStatement":
  410. head = this.loc();
  411. let update = this.loc();
  412. after = this.loc();
  413. if (stmt.init) {
  414. // We pass true here to indicate that if stmt.init is an expression
  415. // then we do not care about its result.
  416. self.explode(path.get("init"), true);
  417. }
  418. self.mark(head);
  419. if (stmt.test) {
  420. self.jumpIfNot(self.explodeExpression(path.get("test")), after);
  421. } else {
  422. // No test means continue unconditionally.
  423. }
  424. self.leapManager.withEntry(
  425. new leap.LoopEntry(after, update, labelId),
  426. function() { self.explodeStatement(path.get("body")); }
  427. );
  428. self.mark(update);
  429. if (stmt.update) {
  430. // We pass true here to indicate that if stmt.update is an
  431. // expression then we do not care about its result.
  432. self.explode(path.get("update"), true);
  433. }
  434. self.jump(head);
  435. self.mark(after);
  436. break;
  437. case "TypeCastExpression":
  438. return self.explodeExpression(path.get("expression"));
  439. case "ForInStatement":
  440. head = this.loc();
  441. after = this.loc();
  442. let keyIterNextFn = self.makeTempVar();
  443. self.emitAssign(
  444. keyIterNextFn,
  445. t.callExpression(
  446. util.runtimeProperty("keys"),
  447. [self.explodeExpression(path.get("right"))]
  448. )
  449. );
  450. self.mark(head);
  451. let keyInfoTmpVar = self.makeTempVar();
  452. self.jumpIf(
  453. t.memberExpression(
  454. t.assignmentExpression(
  455. "=",
  456. keyInfoTmpVar,
  457. t.callExpression(t.cloneDeep(keyIterNextFn), [])
  458. ),
  459. t.identifier("done"),
  460. false
  461. ),
  462. after
  463. );
  464. self.emitAssign(
  465. stmt.left,
  466. t.memberExpression(
  467. t.cloneDeep(keyInfoTmpVar),
  468. t.identifier("value"),
  469. false
  470. )
  471. );
  472. self.leapManager.withEntry(
  473. new leap.LoopEntry(after, head, labelId),
  474. function() { self.explodeStatement(path.get("body")); }
  475. );
  476. self.jump(head);
  477. self.mark(after);
  478. break;
  479. case "BreakStatement":
  480. self.emitAbruptCompletion({
  481. type: "break",
  482. target: self.leapManager.getBreakLoc(stmt.label)
  483. });
  484. break;
  485. case "ContinueStatement":
  486. self.emitAbruptCompletion({
  487. type: "continue",
  488. target: self.leapManager.getContinueLoc(stmt.label)
  489. });
  490. break;
  491. case "SwitchStatement":
  492. // Always save the discriminant into a temporary variable in case the
  493. // test expressions overwrite values like context.sent.
  494. let disc = self.emitAssign(
  495. self.makeTempVar(),
  496. self.explodeExpression(path.get("discriminant"))
  497. );
  498. after = this.loc();
  499. let defaultLoc = this.loc();
  500. let condition = defaultLoc;
  501. let caseLocs = [];
  502. // If there are no cases, .cases might be undefined.
  503. let cases = stmt.cases || [];
  504. for (let i = cases.length - 1; i >= 0; --i) {
  505. let c = cases[i];
  506. t.assertSwitchCase(c);
  507. if (c.test) {
  508. condition = t.conditionalExpression(
  509. t.binaryExpression("===", t.cloneDeep(disc), c.test),
  510. caseLocs[i] = this.loc(),
  511. condition
  512. );
  513. } else {
  514. caseLocs[i] = defaultLoc;
  515. }
  516. }
  517. let discriminant = path.get("discriminant");
  518. util.replaceWithOrRemove(discriminant, condition);
  519. self.jump(self.explodeExpression(discriminant));
  520. self.leapManager.withEntry(
  521. new leap.SwitchEntry(after),
  522. function() {
  523. path.get("cases").forEach(function(casePath) {
  524. let i = casePath.key;
  525. self.mark(caseLocs[i]);
  526. casePath.get("consequent").forEach(function (path) {
  527. self.explodeStatement(path);
  528. });
  529. });
  530. }
  531. );
  532. self.mark(after);
  533. if (defaultLoc.value === PENDING_LOCATION) {
  534. self.mark(defaultLoc);
  535. assert.strictEqual(after.value, defaultLoc.value);
  536. }
  537. break;
  538. case "IfStatement":
  539. let elseLoc = stmt.alternate && this.loc();
  540. after = this.loc();
  541. self.jumpIfNot(
  542. self.explodeExpression(path.get("test")),
  543. elseLoc || after
  544. );
  545. self.explodeStatement(path.get("consequent"));
  546. if (elseLoc) {
  547. self.jump(after);
  548. self.mark(elseLoc);
  549. self.explodeStatement(path.get("alternate"));
  550. }
  551. self.mark(after);
  552. break;
  553. case "ReturnStatement":
  554. self.emitAbruptCompletion({
  555. type: "return",
  556. value: self.explodeExpression(path.get("argument"))
  557. });
  558. break;
  559. case "WithStatement":
  560. throw new Error("WithStatement not supported in generator functions.");
  561. case "TryStatement":
  562. after = this.loc();
  563. let handler = stmt.handler;
  564. let catchLoc = handler && this.loc();
  565. let catchEntry = catchLoc && new leap.CatchEntry(
  566. catchLoc,
  567. handler.param
  568. );
  569. let finallyLoc = stmt.finalizer && this.loc();
  570. let finallyEntry = finallyLoc &&
  571. new leap.FinallyEntry(finallyLoc, after);
  572. let tryEntry = new leap.TryEntry(
  573. self.getUnmarkedCurrentLoc(),
  574. catchEntry,
  575. finallyEntry
  576. );
  577. self.tryEntries.push(tryEntry);
  578. self.updateContextPrevLoc(tryEntry.firstLoc);
  579. self.leapManager.withEntry(tryEntry, function() {
  580. self.explodeStatement(path.get("block"));
  581. if (catchLoc) {
  582. if (finallyLoc) {
  583. // If we have both a catch block and a finally block, then
  584. // because we emit the catch block first, we need to jump over
  585. // it to the finally block.
  586. self.jump(finallyLoc);
  587. } else {
  588. // If there is no finally block, then we need to jump over the
  589. // catch block to the fall-through location.
  590. self.jump(after);
  591. }
  592. self.updateContextPrevLoc(self.mark(catchLoc));
  593. let bodyPath = path.get("handler.body");
  594. let safeParam = self.makeTempVar();
  595. self.clearPendingException(tryEntry.firstLoc, safeParam);
  596. bodyPath.traverse(catchParamVisitor, {
  597. getSafeParam: () => t.cloneDeep(safeParam),
  598. catchParamName: handler.param.name
  599. });
  600. self.leapManager.withEntry(catchEntry, function() {
  601. self.explodeStatement(bodyPath);
  602. });
  603. }
  604. if (finallyLoc) {
  605. self.updateContextPrevLoc(self.mark(finallyLoc));
  606. self.leapManager.withEntry(finallyEntry, function() {
  607. self.explodeStatement(path.get("finalizer"));
  608. });
  609. self.emit(t.returnStatement(t.callExpression(
  610. self.contextProperty("finish"),
  611. [finallyEntry.firstLoc]
  612. )));
  613. }
  614. });
  615. self.mark(after);
  616. break;
  617. case "ThrowStatement":
  618. self.emit(t.throwStatement(
  619. self.explodeExpression(path.get("argument"))
  620. ));
  621. break;
  622. case "ClassDeclaration":
  623. self.emit(self.explodeClass(path));
  624. break;
  625. default:
  626. throw new Error(
  627. "unknown Statement of type " +
  628. JSON.stringify(stmt.type));
  629. }
  630. };
  631. let catchParamVisitor = {
  632. Identifier: function(path, state) {
  633. if (path.node.name === state.catchParamName && util.isReference(path)) {
  634. util.replaceWithOrRemove(path, state.getSafeParam());
  635. }
  636. },
  637. Scope: function(path, state) {
  638. if (path.scope.hasOwnBinding(state.catchParamName)) {
  639. // Don't descend into nested scopes that shadow the catch
  640. // parameter with their own declarations.
  641. path.skip();
  642. }
  643. }
  644. };
  645. Ep.emitAbruptCompletion = function(record) {
  646. if (!isValidCompletion(record)) {
  647. assert.ok(
  648. false,
  649. "invalid completion record: " +
  650. JSON.stringify(record)
  651. );
  652. }
  653. assert.notStrictEqual(
  654. record.type, "normal",
  655. "normal completions are not abrupt"
  656. );
  657. const t = util.getTypes();
  658. let abruptArgs = [t.stringLiteral(record.type)];
  659. if (record.type === "break" ||
  660. record.type === "continue") {
  661. t.assertLiteral(record.target);
  662. abruptArgs[1] = this.insertedLocs.has(record.target)
  663. ? record.target
  664. : t.cloneDeep(record.target);
  665. } else if (record.type === "return" ||
  666. record.type === "throw") {
  667. if (record.value) {
  668. t.assertExpression(record.value);
  669. abruptArgs[1] = this.insertedLocs.has(record.value)
  670. ? record.value
  671. : t.cloneDeep(record.value);
  672. }
  673. }
  674. this.emit(
  675. t.returnStatement(
  676. t.callExpression(
  677. this.contextProperty("abrupt"),
  678. abruptArgs
  679. )
  680. )
  681. );
  682. };
  683. function isValidCompletion(record) {
  684. let type = record.type;
  685. if (type === "normal") {
  686. return !hasOwn.call(record, "target");
  687. }
  688. if (type === "break" ||
  689. type === "continue") {
  690. return !hasOwn.call(record, "value")
  691. && util.getTypes().isLiteral(record.target);
  692. }
  693. if (type === "return" ||
  694. type === "throw") {
  695. return hasOwn.call(record, "value")
  696. && !hasOwn.call(record, "target");
  697. }
  698. return false;
  699. }
  700. // Not all offsets into emitter.listing are potential jump targets. For
  701. // example, execution typically falls into the beginning of a try block
  702. // without jumping directly there. This method returns the current offset
  703. // without marking it, so that a switch case will not necessarily be
  704. // generated for this offset (I say "not necessarily" because the same
  705. // location might end up being marked in the process of emitting other
  706. // statements). There's no logical harm in marking such locations as jump
  707. // targets, but minimizing the number of switch cases keeps the generated
  708. // code shorter.
  709. Ep.getUnmarkedCurrentLoc = function() {
  710. return util.getTypes().numericLiteral(this.listing.length);
  711. };
  712. // The context.prev property takes the value of context.next whenever we
  713. // evaluate the switch statement discriminant, which is generally good
  714. // enough for tracking the last location we jumped to, but sometimes
  715. // context.prev needs to be more precise, such as when we fall
  716. // successfully out of a try block and into a finally block without
  717. // jumping. This method exists to update context.prev to the freshest
  718. // available location. If we were implementing a full interpreter, we
  719. // would know the location of the current instruction with complete
  720. // precision at all times, but we don't have that luxury here, as it would
  721. // be costly and verbose to set context.prev before every statement.
  722. Ep.updateContextPrevLoc = function(loc) {
  723. const t = util.getTypes();
  724. if (loc) {
  725. t.assertLiteral(loc);
  726. if (loc.value === PENDING_LOCATION) {
  727. // If an uninitialized location literal was passed in, set its value
  728. // to the current this.listing.length.
  729. loc.value = this.listing.length;
  730. } else {
  731. // Otherwise assert that the location matches the current offset.
  732. assert.strictEqual(loc.value, this.listing.length);
  733. }
  734. } else {
  735. loc = this.getUnmarkedCurrentLoc();
  736. }
  737. // Make sure context.prev is up to date in case we fell into this try
  738. // statement without jumping to it. TODO Consider avoiding this
  739. // assignment when we know control must have jumped here.
  740. this.emitAssign(this.contextProperty("prev"), loc);
  741. };
  742. // In order to save the rest of explodeExpression from a combinatorial
  743. // trainwreck of special cases, explodeViaTempVar is responsible for
  744. // deciding when a subexpression needs to be "exploded," which is my
  745. // very technical term for emitting the subexpression as an assignment
  746. // to a temporary variable and the substituting the temporary variable
  747. // for the original subexpression. Think of exploded view diagrams, not
  748. // Michael Bay movies. The point of exploding subexpressions is to
  749. // control the precise order in which the generated code realizes the
  750. // side effects of those subexpressions.
  751. Ep.explodeViaTempVar = function(tempVar, childPath, hasLeapingChildren, ignoreChildResult) {
  752. assert.ok(
  753. !ignoreChildResult || !tempVar,
  754. "Ignoring the result of a child expression but forcing it to " +
  755. "be assigned to a temporary variable?"
  756. );
  757. const t = util.getTypes();
  758. let result = this.explodeExpression(childPath, ignoreChildResult);
  759. if (ignoreChildResult) {
  760. // Side effects already emitted above.
  761. } else if (tempVar || (hasLeapingChildren &&
  762. !t.isLiteral(result))) {
  763. // If tempVar was provided, then the result will always be assigned
  764. // to it, even if the result does not otherwise need to be assigned
  765. // to a temporary variable. When no tempVar is provided, we have
  766. // the flexibility to decide whether a temporary variable is really
  767. // necessary. Unfortunately, in general, a temporary variable is
  768. // required whenever any child contains a yield expression, since it
  769. // is difficult to prove (at all, let alone efficiently) whether
  770. // this result would evaluate to the same value before and after the
  771. // yield (see #206). One narrow case where we can prove it doesn't
  772. // matter (and thus we do not need a temporary variable) is when the
  773. // result in question is a Literal value.
  774. result = this.emitAssign(
  775. tempVar || this.makeTempVar(),
  776. result
  777. );
  778. }
  779. return result;
  780. };
  781. Ep.explodeExpression = function(path, ignoreResult) {
  782. const t = util.getTypes();
  783. let expr = path.node;
  784. if (expr) {
  785. t.assertExpression(expr);
  786. } else {
  787. return expr;
  788. }
  789. let self = this;
  790. let result; // Used optionally by several cases below.
  791. let after;
  792. function finish(expr) {
  793. t.assertExpression(expr);
  794. if (ignoreResult) {
  795. self.emit(expr);
  796. }
  797. return expr;
  798. }
  799. // If the expression does not contain a leap, then we either emit the
  800. // expression as a standalone statement or return it whole.
  801. if (!meta.containsLeap(expr)) {
  802. return finish(expr);
  803. }
  804. // If any child contains a leap (such as a yield or labeled continue or
  805. // break statement), then any sibling subexpressions will almost
  806. // certainly have to be exploded in order to maintain the order of their
  807. // side effects relative to the leaping child(ren).
  808. let hasLeapingChildren = meta.containsLeap.onlyChildren(expr);
  809. // If ignoreResult is true, then we must take full responsibility for
  810. // emitting the expression with all its side effects, and we should not
  811. // return a result.
  812. switch (expr.type) {
  813. case "MemberExpression":
  814. return finish(t.memberExpression(
  815. self.explodeExpression(path.get("object")),
  816. expr.computed
  817. ? self.explodeViaTempVar(null, path.get("property"), hasLeapingChildren)
  818. : expr.property,
  819. expr.computed
  820. ));
  821. case "CallExpression":
  822. let calleePath = path.get("callee");
  823. let argsPath = path.get("arguments");
  824. let newCallee;
  825. let newArgs;
  826. let hasLeapingArgs = argsPath.some(
  827. argPath => meta.containsLeap(argPath.node)
  828. );
  829. let injectFirstArg = null;
  830. if (t.isMemberExpression(calleePath.node)) {
  831. if (hasLeapingArgs) {
  832. // If the arguments of the CallExpression contained any yield
  833. // expressions, then we need to be sure to evaluate the callee
  834. // before evaluating the arguments, but if the callee was a member
  835. // expression, then we must be careful that the object of the
  836. // member expression still gets bound to `this` for the call.
  837. let newObject = self.explodeViaTempVar(
  838. // Assign the exploded callee.object expression to a temporary
  839. // variable so that we can use it twice without reevaluating it.
  840. self.makeTempVar(),
  841. calleePath.get("object"),
  842. hasLeapingChildren
  843. );
  844. let newProperty = calleePath.node.computed
  845. ? self.explodeViaTempVar(null, calleePath.get("property"), hasLeapingChildren)
  846. : calleePath.node.property;
  847. injectFirstArg = newObject;
  848. newCallee = t.memberExpression(
  849. t.memberExpression(
  850. t.cloneDeep(newObject),
  851. newProperty,
  852. calleePath.node.computed
  853. ),
  854. t.identifier("call"),
  855. false
  856. );
  857. } else {
  858. newCallee = self.explodeExpression(calleePath);
  859. }
  860. } else {
  861. newCallee = self.explodeViaTempVar(null, calleePath, hasLeapingChildren);
  862. if (t.isMemberExpression(newCallee)) {
  863. // If the callee was not previously a MemberExpression, then the
  864. // CallExpression was "unqualified," meaning its `this` object
  865. // should be the global object. If the exploded expression has
  866. // become a MemberExpression (e.g. a context property, probably a
  867. // temporary variable), then we need to force it to be unqualified
  868. // by using the (0, object.property)(...) trick; otherwise, it
  869. // will receive the object of the MemberExpression as its `this`
  870. // object.
  871. newCallee = t.sequenceExpression([
  872. t.numericLiteral(0),
  873. t.cloneDeep(newCallee)
  874. ]);
  875. }
  876. }
  877. if (hasLeapingArgs) {
  878. newArgs = argsPath.map(argPath => self.explodeViaTempVar(null, argPath, hasLeapingChildren));
  879. if (injectFirstArg) newArgs.unshift(injectFirstArg);
  880. newArgs = newArgs.map(arg => t.cloneDeep(arg));
  881. } else {
  882. newArgs = path.node.arguments;
  883. }
  884. return finish(t.callExpression(newCallee, newArgs));
  885. case "NewExpression":
  886. return finish(t.newExpression(
  887. self.explodeViaTempVar(null, path.get("callee"), hasLeapingChildren),
  888. path.get("arguments").map(function(argPath) {
  889. return self.explodeViaTempVar(null, argPath, hasLeapingChildren);
  890. })
  891. ));
  892. case "ObjectExpression":
  893. return finish(t.objectExpression(
  894. path.get("properties").map(function(propPath) {
  895. if (propPath.isObjectProperty()) {
  896. return t.objectProperty(
  897. propPath.node.key,
  898. self.explodeViaTempVar(null, propPath.get("value"), hasLeapingChildren),
  899. propPath.node.computed
  900. );
  901. } else {
  902. return propPath.node;
  903. }
  904. })
  905. ));
  906. case "ArrayExpression":
  907. return finish(t.arrayExpression(
  908. path.get("elements").map(function(elemPath) {
  909. if (!elemPath.node) {
  910. return null;
  911. } if (elemPath.isSpreadElement()) {
  912. return t.spreadElement(
  913. self.explodeViaTempVar(null, elemPath.get("argument"), hasLeapingChildren)
  914. );
  915. } else {
  916. return self.explodeViaTempVar(null, elemPath, hasLeapingChildren);
  917. }
  918. })
  919. ));
  920. case "SequenceExpression":
  921. let lastIndex = expr.expressions.length - 1;
  922. path.get("expressions").forEach(function(exprPath) {
  923. if (exprPath.key === lastIndex) {
  924. result = self.explodeExpression(exprPath, ignoreResult);
  925. } else {
  926. self.explodeExpression(exprPath, true);
  927. }
  928. });
  929. return result;
  930. case "LogicalExpression":
  931. after = this.loc();
  932. if (!ignoreResult) {
  933. result = self.makeTempVar();
  934. }
  935. let left = self.explodeViaTempVar(result, path.get("left"), hasLeapingChildren);
  936. if (expr.operator === "&&") {
  937. self.jumpIfNot(left, after);
  938. } else {
  939. assert.strictEqual(expr.operator, "||");
  940. self.jumpIf(left, after);
  941. }
  942. self.explodeViaTempVar(result, path.get("right"), hasLeapingChildren, ignoreResult);
  943. self.mark(after);
  944. return result;
  945. case "ConditionalExpression":
  946. let elseLoc = this.loc();
  947. after = this.loc();
  948. let test = self.explodeExpression(path.get("test"));
  949. self.jumpIfNot(test, elseLoc);
  950. if (!ignoreResult) {
  951. result = self.makeTempVar();
  952. }
  953. self.explodeViaTempVar(result, path.get("consequent"), hasLeapingChildren, ignoreResult);
  954. self.jump(after);
  955. self.mark(elseLoc);
  956. self.explodeViaTempVar(result, path.get("alternate"), hasLeapingChildren, ignoreResult);
  957. self.mark(after);
  958. return result;
  959. case "UnaryExpression":
  960. return finish(t.unaryExpression(
  961. expr.operator,
  962. // Can't (and don't need to) break up the syntax of the argument.
  963. // Think about delete a[b].
  964. self.explodeExpression(path.get("argument")),
  965. !!expr.prefix
  966. ));
  967. case "BinaryExpression":
  968. return finish(t.binaryExpression(
  969. expr.operator,
  970. self.explodeViaTempVar(null, path.get("left"), hasLeapingChildren),
  971. self.explodeViaTempVar(null, path.get("right"), hasLeapingChildren)
  972. ));
  973. case "AssignmentExpression":
  974. if (expr.operator === "=") {
  975. // If this is a simple assignment, the left hand side does not need
  976. // to be read before the right hand side is evaluated, so we can
  977. // avoid the more complicated logic below.
  978. return finish(t.assignmentExpression(
  979. expr.operator,
  980. self.explodeExpression(path.get("left")),
  981. self.explodeExpression(path.get("right"))
  982. ));
  983. }
  984. const lhs = self.explodeExpression(path.get("left"));
  985. const temp = self.emitAssign(self.makeTempVar(), lhs);
  986. // For example,
  987. //
  988. // x += yield y
  989. //
  990. // becomes
  991. //
  992. // context.t0 = x
  993. // x = context.t0 += yield y
  994. //
  995. // so that the left-hand side expression is read before the yield.
  996. // Fixes https://github.com/facebook/regenerator/issues/345.
  997. return finish(t.assignmentExpression(
  998. "=",
  999. t.cloneDeep(lhs),
  1000. t.assignmentExpression(
  1001. expr.operator,
  1002. t.cloneDeep(temp),
  1003. self.explodeExpression(path.get("right"))
  1004. )
  1005. ));
  1006. case "UpdateExpression":
  1007. return finish(t.updateExpression(
  1008. expr.operator,
  1009. self.explodeExpression(path.get("argument")),
  1010. expr.prefix
  1011. ));
  1012. case "YieldExpression":
  1013. after = this.loc();
  1014. let arg = expr.argument && self.explodeExpression(path.get("argument"));
  1015. if (arg && expr.delegate) {
  1016. let result = self.makeTempVar();
  1017. let ret = t.returnStatement(t.callExpression(
  1018. self.contextProperty("delegateYield"),
  1019. [
  1020. arg,
  1021. t.stringLiteral(result.property.name),
  1022. after
  1023. ]
  1024. ));
  1025. ret.loc = expr.loc;
  1026. self.emit(ret);
  1027. self.mark(after);
  1028. return result;
  1029. }
  1030. self.emitAssign(self.contextProperty("next"), after);
  1031. let ret = t.returnStatement(t.cloneDeep(arg) || null);
  1032. // Preserve the `yield` location so that source mappings for the statements
  1033. // link back to the yield properly.
  1034. ret.loc = expr.loc;
  1035. self.emit(ret);
  1036. self.mark(after);
  1037. return self.contextProperty("sent");
  1038. case "ClassExpression":
  1039. return finish(self.explodeClass(path));
  1040. default:
  1041. throw new Error(
  1042. "unknown Expression of type " +
  1043. JSON.stringify(expr.type));
  1044. }
  1045. };
  1046. Ep.explodeClass = function(path) {
  1047. const explodingChildren = [];
  1048. if (path.node.superClass) {
  1049. explodingChildren.push(path.get("superClass"));
  1050. }
  1051. path.get("body.body").forEach(member => {
  1052. if (member.node.computed) {
  1053. explodingChildren.push(member.get("key"));
  1054. }
  1055. });
  1056. const hasLeapingChildren = explodingChildren.some(
  1057. child => meta.containsLeap(child));
  1058. for (let i = 0; i < explodingChildren.length; i++) {
  1059. const child = explodingChildren[i];
  1060. const isLast = i === explodingChildren.length - 1;
  1061. if (isLast) {
  1062. child.replaceWith(this.explodeExpression(child));
  1063. } else {
  1064. child.replaceWith(this.explodeViaTempVar(null, child, hasLeapingChildren));
  1065. }
  1066. }
  1067. return path.node;
  1068. };