You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

947 lines
34 KiB

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