visit.js 11 KB

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