emit.js 36 KB

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