emit.js 36 KB

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