visit.js 9.5 KB

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