visit.js 12 KB

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