emit.js 33 KB

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