emit.js 37 KB

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