visit.js 12 KB

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