65cb8c83c483a4c70b25c9d35c1991bffdfb95c41aaebc092b7ce0a6bc16137b0bb8b7afe0975a0fbe84505081875ccd7a6d860895352b2be59bbce7bfa25b 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. /**
  2. * Copyright (c) 2014, Facebook, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under the BSD-style license found in the
  6. * https://raw.github.com/facebook/regenerator/master/LICENSE file. An
  7. * additional grant of patent rights can be found in the PATENTS file in
  8. * the same directory.
  9. */
  10. "use strict";
  11. import assert from "assert";
  12. import * as t from "babel-types";
  13. import { hoist } from "./hoist";
  14. import { Emitter } from "./emit";
  15. import replaceShorthandObjectMethod from "./replaceShorthandObjectMethod";
  16. import * as util from "./util";
  17. exports.visitor = {
  18. Function: {
  19. exit: function(path, state) {
  20. let node = path.node;
  21. if (node.generator) {
  22. if (node.async) {
  23. // Async generator
  24. if (state.opts.asyncGenerators === false) return;
  25. } else {
  26. // Plain generator
  27. if (state.opts.generators === false) return;
  28. }
  29. } else if (node.async) {
  30. // Async function
  31. if (state.opts.async === false) return;
  32. } else {
  33. // Not a generator or async function.
  34. return;
  35. }
  36. // if this is an ObjectMethod, we need to convert it to an ObjectProperty
  37. path = replaceShorthandObjectMethod(path);
  38. node = path.node;
  39. let contextId = path.scope.generateUidIdentifier("context");
  40. let argsId = path.scope.generateUidIdentifier("args");
  41. path.ensureBlock();
  42. let bodyBlockPath = path.get("body");
  43. if (node.async) {
  44. bodyBlockPath.traverse(awaitVisitor);
  45. }
  46. bodyBlockPath.traverse(functionSentVisitor, {
  47. context: contextId
  48. });
  49. let outerBody = [];
  50. let innerBody = [];
  51. bodyBlockPath.get("body").forEach(function(childPath) {
  52. let node = childPath.node;
  53. if (t.isExpressionStatement(node) &&
  54. t.isStringLiteral(node.expression)) {
  55. // Babylon represents directives like "use strict" as elements
  56. // of a bodyBlockPath.node.directives array, but they could just
  57. // as easily be represented (by other parsers) as traditional
  58. // string-literal-valued expression statements, so we need to
  59. // handle that here. (#248)
  60. outerBody.push(node);
  61. } else if (node && node._blockHoist != null) {
  62. outerBody.push(node);
  63. } else {
  64. innerBody.push(node);
  65. }
  66. });
  67. if (outerBody.length > 0) {
  68. // Only replace the inner body if we actually hoisted any statements
  69. // to the outer body.
  70. bodyBlockPath.node.body = innerBody;
  71. }
  72. let outerFnExpr = getOuterFnExpr(path);
  73. // Note that getOuterFnExpr has the side-effect of ensuring that the
  74. // function has a name (so node.id will always be an Identifier), even
  75. // if a temporary name has to be synthesized.
  76. t.assertIdentifier(node.id);
  77. let innerFnId = t.identifier(node.id.name + "$");
  78. // Turn all declarations into vars, and replace the original
  79. // declarations with equivalent assignment expressions.
  80. let vars = hoist(path);
  81. let didRenameArguments = renameArguments(path, argsId);
  82. if (didRenameArguments) {
  83. vars = vars || t.variableDeclaration("var", []);
  84. const argumentIdentifier = t.identifier("arguments");
  85. // we need to do this as otherwise arguments in arrow functions gets hoisted
  86. argumentIdentifier._shadowedFunctionLiteral = path;
  87. vars.declarations.push(t.variableDeclarator(
  88. argsId, argumentIdentifier
  89. ));
  90. }
  91. let emitter = new Emitter(contextId);
  92. emitter.explode(path.get("body"));
  93. if (vars && vars.declarations.length > 0) {
  94. outerBody.push(vars);
  95. }
  96. let wrapArgs = [
  97. emitter.getContextFunction(innerFnId),
  98. // Async functions that are not generators don't care about the
  99. // outer function because they don't need it to be marked and don't
  100. // inherit from its .prototype.
  101. node.generator ? outerFnExpr : t.nullLiteral(),
  102. t.thisExpression()
  103. ];
  104. let tryLocsList = emitter.getTryLocsList();
  105. if (tryLocsList) {
  106. wrapArgs.push(tryLocsList);
  107. }
  108. let wrapCall = t.callExpression(
  109. util.runtimeProperty(node.async ? "async" : "wrap"),
  110. wrapArgs
  111. );
  112. outerBody.push(t.returnStatement(wrapCall));
  113. node.body = t.blockStatement(outerBody);
  114. const oldDirectives = bodyBlockPath.node.directives;
  115. if (oldDirectives) {
  116. // Babylon represents directives like "use strict" as elements of
  117. // a bodyBlockPath.node.directives array. (#248)
  118. node.body.directives = oldDirectives;
  119. }
  120. let wasGeneratorFunction = node.generator;
  121. if (wasGeneratorFunction) {
  122. node.generator = false;
  123. }
  124. if (node.async) {
  125. node.async = false;
  126. }
  127. if (wasGeneratorFunction && t.isExpression(node)) {
  128. util.replaceWithOrRemove(path, t.callExpression(util.runtimeProperty("mark"), [node]))
  129. path.addComment("leading", "#__PURE__");
  130. }
  131. // Generators are processed in 'exit' handlers so that regenerator only has to run on
  132. // an ES5 AST, but that means traversal will not pick up newly inserted references
  133. // to things like 'regeneratorRuntime'. To avoid this, we explicitly requeue.
  134. path.requeue();
  135. }
  136. }
  137. };
  138. // Given a NodePath for a Function, return an Expression node that can be
  139. // used to refer reliably to the function object from inside the function.
  140. // This expression is essentially a replacement for arguments.callee, with
  141. // the key advantage that it works in strict mode.
  142. function getOuterFnExpr(funPath) {
  143. let node = funPath.node;
  144. t.assertFunction(node);
  145. if (!node.id) {
  146. // Default-exported function declarations, and function expressions may not
  147. // have a name to reference, so we explicitly add one.
  148. node.id = funPath.scope.parent.generateUidIdentifier("callee");
  149. }
  150. if (node.generator && // Non-generator functions don't need to be marked.
  151. t.isFunctionDeclaration(node)) {
  152. // Return the identifier returned by runtime.mark(<node.id>).
  153. return getMarkedFunctionId(funPath);
  154. }
  155. return node.id;
  156. }
  157. const getMarkInfo = require("private").makeAccessor();
  158. function getMarkedFunctionId(funPath) {
  159. const node = funPath.node;
  160. t.assertIdentifier(node.id);
  161. const blockPath = funPath.findParent(function (path) {
  162. return path.isProgram() || path.isBlockStatement();
  163. });
  164. if (!blockPath) {
  165. return node.id;
  166. }
  167. const block = blockPath.node;
  168. assert.ok(Array.isArray(block.body));
  169. const info = getMarkInfo(block);
  170. if (!info.decl) {
  171. info.decl = t.variableDeclaration("var", []);
  172. blockPath.unshiftContainer("body", info.decl);
  173. info.declPath = blockPath.get("body.0");
  174. }
  175. assert.strictEqual(info.declPath.node, info.decl);
  176. // Get a new unique identifier for our marked variable.
  177. const markedId = blockPath.scope.generateUidIdentifier("marked");
  178. const markCallExp = t.callExpression(
  179. util.runtimeProperty("mark"),
  180. [node.id]
  181. );
  182. const index = info.decl.declarations.push(
  183. t.variableDeclarator(markedId, markCallExp)
  184. ) - 1;
  185. const markCallExpPath =
  186. info.declPath.get("declarations." + index + ".init");
  187. assert.strictEqual(markCallExpPath.node, markCallExp);
  188. markCallExpPath.addComment("leading", "#__PURE__");
  189. return markedId;
  190. }
  191. function renameArguments(funcPath, argsId) {
  192. let state = {
  193. didRenameArguments: false,
  194. argsId: argsId
  195. };
  196. funcPath.traverse(argumentsVisitor, state);
  197. // If the traversal replaced any arguments references, then we need to
  198. // alias the outer function's arguments binding (be it the implicit
  199. // arguments object or some other parameter or variable) to the variable
  200. // named by argsId.
  201. return state.didRenameArguments;
  202. }
  203. let argumentsVisitor = {
  204. "FunctionExpression|FunctionDeclaration": function(path) {
  205. path.skip();
  206. },
  207. Identifier: function(path, state) {
  208. if (path.node.name === "arguments" && util.isReference(path)) {
  209. util.replaceWithOrRemove(path, state.argsId);
  210. state.didRenameArguments = true;
  211. }
  212. }
  213. };
  214. let functionSentVisitor = {
  215. MetaProperty(path) {
  216. let { node } = path;
  217. if (node.meta.name === "function" && node.property.name === "sent") {
  218. util.replaceWithOrRemove(path, t.memberExpression(this.context, t.identifier("_sent")));
  219. }
  220. }
  221. };
  222. let awaitVisitor = {
  223. Function: function(path) {
  224. path.skip(); // Don't descend into nested function scopes.
  225. },
  226. AwaitExpression: function(path) {
  227. // Convert await expressions to yield expressions.
  228. let argument = path.node.argument;
  229. // Transforming `await x` to `yield regeneratorRuntime.awrap(x)`
  230. // causes the argument to be wrapped in such a way that the runtime
  231. // can distinguish between awaited and merely yielded values.
  232. util.replaceWithOrRemove(path, t.yieldExpression(
  233. t.callExpression(
  234. util.runtimeProperty("awrap"),
  235. [argument]
  236. ),
  237. false
  238. ));
  239. }
  240. };