You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

308 lines
11 KiB

4 years ago
  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 _assert = _interopRequireDefault(require("assert"));
  9. var _hoist = require("./hoist");
  10. var _emit = require("./emit");
  11. var _replaceShorthandObjectMethod = _interopRequireDefault(require("./replaceShorthandObjectMethod"));
  12. var util = _interopRequireWildcard(require("./util"));
  13. var _private = require("private");
  14. 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)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } }
  15. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  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. var argumentIdentifier = t.identifier("arguments"); // we need to do this as otherwise arguments in arrow functions gets hoisted
  85. argumentIdentifier._shadowedFunctionLiteral = path;
  86. vars.declarations.push(t.variableDeclarator(t.clone(argsId), argumentIdentifier));
  87. }
  88. var emitter = new _emit.Emitter(contextId);
  89. emitter.explode(path.get("body"));
  90. if (vars && vars.declarations.length > 0) {
  91. outerBody.push(vars);
  92. }
  93. var wrapArgs = [emitter.getContextFunction(innerFnId)];
  94. var tryLocsList = emitter.getTryLocsList();
  95. if (node.generator) {
  96. wrapArgs.push(outerFnExpr);
  97. } else if (context.usesThis || tryLocsList) {
  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. wrapArgs.push(t.nullLiteral());
  102. }
  103. if (context.usesThis) {
  104. wrapArgs.push(t.thisExpression());
  105. } else if (tryLocsList) {
  106. wrapArgs.push(t.nullLiteral());
  107. }
  108. if (tryLocsList) {
  109. wrapArgs.push(tryLocsList);
  110. }
  111. var wrapCall = t.callExpression(util.runtimeProperty(node.async ? "async" : "wrap"), wrapArgs);
  112. outerBody.push(t.returnStatement(wrapCall));
  113. node.body = t.blockStatement(outerBody); // We injected a few new variable declarations (for every hoisted var),
  114. // so we need to add them to the scope.
  115. path.get("body.body").forEach(function (p) {
  116. return p.scope.registerDeclaration(p);
  117. });
  118. var oldDirectives = bodyBlockPath.node.directives;
  119. if (oldDirectives) {
  120. // Babylon represents directives like "use strict" as elements of
  121. // a bodyBlockPath.node.directives array. (#248)
  122. node.body.directives = oldDirectives;
  123. }
  124. var wasGeneratorFunction = node.generator;
  125. if (wasGeneratorFunction) {
  126. node.generator = false;
  127. }
  128. if (node.async) {
  129. node.async = false;
  130. }
  131. if (wasGeneratorFunction && t.isExpression(node)) {
  132. util.replaceWithOrRemove(path, t.callExpression(util.runtimeProperty("mark"), [node]));
  133. path.addComment("leading", "#__PURE__");
  134. }
  135. var insertedLocs = emitter.getInsertedLocs();
  136. path.traverse({
  137. NumericLiteral: function NumericLiteral(path) {
  138. if (!insertedLocs.has(path.node)) {
  139. return;
  140. }
  141. path.replaceWith(t.numericLiteral(path.node.value));
  142. }
  143. }); // Generators are processed in 'exit' handlers so that regenerator only has to run on
  144. // an ES5 AST, but that means traversal will not pick up newly inserted references
  145. // to things like 'regeneratorRuntime'. To avoid this, we explicitly requeue.
  146. path.requeue();
  147. })
  148. }
  149. };
  150. }; // Check if a node should be transformed by regenerator
  151. function shouldRegenerate(node, state) {
  152. if (node.generator) {
  153. if (node.async) {
  154. // Async generator
  155. return state.opts.asyncGenerators !== false;
  156. } else {
  157. // Plain generator
  158. return state.opts.generators !== false;
  159. }
  160. } else if (node.async) {
  161. // Async function
  162. return state.opts.async !== false;
  163. } else {
  164. // Not a generator or async function.
  165. return false;
  166. }
  167. } // Given a NodePath for a Function, return an Expression node that can be
  168. // used to refer reliably to the function object from inside the function.
  169. // This expression is essentially a replacement for arguments.callee, with
  170. // the key advantage that it works in strict mode.
  171. function getOuterFnExpr(funPath) {
  172. var t = util.getTypes();
  173. var node = funPath.node;
  174. t.assertFunction(node);
  175. if (!node.id) {
  176. // Default-exported function declarations, and function expressions may not
  177. // have a name to reference, so we explicitly add one.
  178. node.id = funPath.scope.parent.generateUidIdentifier("callee");
  179. }
  180. if (node.generator && // Non-generator functions don't need to be marked.
  181. t.isFunctionDeclaration(node)) {
  182. // Return the identifier returned by runtime.mark(<node.id>).
  183. return getMarkedFunctionId(funPath);
  184. }
  185. return t.clone(node.id);
  186. }
  187. var getMarkInfo = (0, _private.makeAccessor)();
  188. function getMarkedFunctionId(funPath) {
  189. var t = util.getTypes();
  190. var node = funPath.node;
  191. t.assertIdentifier(node.id);
  192. var blockPath = funPath.findParent(function (path) {
  193. return path.isProgram() || path.isBlockStatement();
  194. });
  195. if (!blockPath) {
  196. return node.id;
  197. }
  198. var block = blockPath.node;
  199. _assert["default"].ok(Array.isArray(block.body));
  200. var info = getMarkInfo(block);
  201. if (!info.decl) {
  202. info.decl = t.variableDeclaration("var", []);
  203. blockPath.unshiftContainer("body", info.decl);
  204. info.declPath = blockPath.get("body.0");
  205. }
  206. _assert["default"].strictEqual(info.declPath.node, info.decl); // Get a new unique identifier for our marked variable.
  207. var markedId = blockPath.scope.generateUidIdentifier("marked");
  208. var markCallExp = t.callExpression(util.runtimeProperty("mark"), [t.clone(node.id)]);
  209. var index = info.decl.declarations.push(t.variableDeclarator(markedId, markCallExp)) - 1;
  210. var markCallExpPath = info.declPath.get("declarations." + index + ".init");
  211. _assert["default"].strictEqual(markCallExpPath.node, markCallExp);
  212. markCallExpPath.addComment("leading", "#__PURE__");
  213. return t.clone(markedId);
  214. }
  215. var argumentsThisVisitor = {
  216. "FunctionExpression|FunctionDeclaration|Method": function FunctionExpressionFunctionDeclarationMethod(path) {
  217. path.skip();
  218. },
  219. Identifier: function Identifier(path, state) {
  220. if (path.node.name === "arguments" && util.isReference(path)) {
  221. util.replaceWithOrRemove(path, state.getArgsId());
  222. state.usesArguments = true;
  223. }
  224. },
  225. ThisExpression: function ThisExpression(path, state) {
  226. state.usesThis = true;
  227. }
  228. };
  229. var functionSentVisitor = {
  230. MetaProperty: function MetaProperty(path) {
  231. var node = path.node;
  232. if (node.meta.name === "function" && node.property.name === "sent") {
  233. var t = util.getTypes();
  234. util.replaceWithOrRemove(path, t.memberExpression(t.clone(this.context), t.identifier("_sent")));
  235. }
  236. }
  237. };
  238. var awaitVisitor = {
  239. Function: function Function(path) {
  240. path.skip(); // Don't descend into nested function scopes.
  241. },
  242. AwaitExpression: function AwaitExpression(path) {
  243. var t = util.getTypes(); // Convert await expressions to yield expressions.
  244. var argument = path.node.argument; // Transforming `await x` to `yield regeneratorRuntime.awrap(x)`
  245. // causes the argument to be wrapped in such a way that the runtime
  246. // can distinguish between awaited and merely yielded values.
  247. util.replaceWithOrRemove(path, t.yieldExpression(t.callExpression(util.runtimeProperty("awrap"), [argument]), false));
  248. }
  249. };