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