"use strict";
import assert from "assert";
import { hoist } from "./hoist";
import { Emitter } from "./emit";
import replaceShorthandObjectMethod from "./replaceShorthandObjectMethod";
import * as util from "./util";
exports.getVisitor = ({ types: t }) => ({
Method(path, state) {
let node = path.node;
if (!shouldRegenerate(node, state)) return;
const container = t.functionExpression(
null,
[],
t.cloneNode(node.body, false),
node.generator,
node.async,
);
path.get("body").set("body", [
t.returnStatement(
t.callExpression(container, []),
),
]);
node.async = false;
node.generator = false;
path
.get("body.body.0.argument.callee")
.unwrapFunctionEnvironment();
},
Function: {
exit: util.wrapWithTypes(t, function(path, state) {
let node = path.node;
if (!shouldRegenerate(node, state)) return;
path = replaceShorthandObjectMethod(path);
node = path.node;
let contextId = path.scope.generateUidIdentifier("context");
let argsId = path.scope.generateUidIdentifier("args");
path.ensureBlock();
let bodyBlockPath = path.get("body");
if (node.async) {
bodyBlockPath.traverse(awaitVisitor);
}
bodyBlockPath.traverse(functionSentVisitor, {
context: contextId
});
let outerBody = [];
let innerBody = [];
bodyBlockPath.get("body").forEach(function(childPath) {
let node = childPath.node;
if (t.isExpressionStatement(node) &&
t.isStringLiteral(node.expression)) {
outerBody.push(node);
} else if (node && node._blockHoist != null) {
outerBody.push(node);
} else {
innerBody.push(node);
}
});
if (outerBody.length > 0) {
bodyBlockPath.node.body = innerBody;
}
let outerFnExpr = getOuterFnExpr(path);
t.assertIdentifier(node.id);
let innerFnId = t.identifier(node.id.name + "$");
let vars = hoist(path);
let context = {
usesThis: false,
usesArguments: false,
getArgsId: () => t.clone(argsId),
};
path.traverse(argumentsThisVisitor, context);
if (context.usesArguments) {
vars = vars || t.variableDeclaration("var", []);
vars.declarations.push(t.variableDeclarator(
t.clone(argsId),
t.identifier("arguments"),
));
}
let emitter = new Emitter(contextId);
emitter.explode(path.get("body"));
if (vars && vars.declarations.length > 0) {
outerBody.push(vars);
}
let wrapArgs = [emitter.getContextFunction(innerFnId)];
let tryLocsList = emitter.getTryLocsList();
if (node.generator) {
wrapArgs.push(outerFnExpr);
} else if (context.usesThis || tryLocsList || node.async) {
wrapArgs.push(t.nullLiteral());
}
if (context.usesThis) {
wrapArgs.push(t.thisExpression());
} else if (tryLocsList || node.async) {
wrapArgs.push(t.nullLiteral());
}
if (tryLocsList) {
wrapArgs.push(tryLocsList);
} else if (node.async) {
wrapArgs.push(t.nullLiteral());
}
if (node.async) {
let currentScope = path.scope;
do {
if (currentScope.hasOwnBinding("Promise")) currentScope.rename("Promise");
} while (currentScope = currentScope.parent);
wrapArgs.push(t.identifier("Promise"));
}
let wrapCall = t.callExpression(
util.runtimeProperty(node.async ? "async" : "wrap"),
wrapArgs
);
outerBody.push(t.returnStatement(wrapCall));
node.body = t.blockStatement(outerBody);
path.get("body.body").forEach(p => p.scope.registerDeclaration(p));
const oldDirectives = bodyBlockPath.node.directives;
if (oldDirectives) {
node.body.directives = oldDirectives;
}
let wasGeneratorFunction = node.generator;
if (wasGeneratorFunction) {
node.generator = false;
}
if (node.async) {
node.async = false;
}
if (wasGeneratorFunction && t.isExpression(node)) {
util.replaceWithOrRemove(path, t.callExpression(util.runtimeProperty("mark"), [node]))
path.addComment("leading", "#__PURE__");
}
const insertedLocs = emitter.getInsertedLocs();
path.traverse({
NumericLiteral(path) {
if (!insertedLocs.has(path.node)) {
return;
}
path.replaceWith(t.numericLiteral(path.node.value));
},
})
path.requeue();
})
}
});
function shouldRegenerate(node, state) {
if (node.generator) {
if (node.async) {
return state.opts.asyncGenerators !== false;
} else {
return state.opts.generators !== false;
}
} else if (node.async) {
return state.opts.async !== false;
} else {
return false;
}
}
function getOuterFnExpr(funPath) {
const t = util.getTypes();
let node = funPath.node;
t.assertFunction(node);
if (!node.id) {
node.id = funPath.scope.parent.generateUidIdentifier("callee");
}
if (node.generator && t.isFunctionDeclaration(node)) {
return getMarkedFunctionId(funPath);
}
return t.clone(node.id);
}
const markInfo = new WeakMap();
function getMarkInfo(node) {
if (!markInfo.has(node)) {
markInfo.set(node, {});
}
return markInfo.get(node);
}
function getMarkedFunctionId(funPath) {
const t = util.getTypes();
const node = funPath.node;
t.assertIdentifier(node.id);
const blockPath = funPath.findParent(function (path) {
return path.isProgram() || path.isBlockStatement();
});
if (!blockPath) {
return node.id;
}
const block = blockPath.node;
assert.ok(Array.isArray(block.body));
const info = getMarkInfo(block);
if (!info.decl) {
info.decl = t.variableDeclaration("var", []);
blockPath.unshiftContainer("body", info.decl);
info.declPath = blockPath.get("body.0");
}
assert.strictEqual(info.declPath.node, info.decl);
const markedId = blockPath.scope.generateUidIdentifier("marked");
const markCallExp = t.callExpression(
util.runtimeProperty("mark"),
[t.clone(node.id)]
);
const index = info.decl.declarations.push(
t.variableDeclarator(markedId, markCallExp)
) - 1;
const markCallExpPath =
info.declPath.get("declarations." + index + ".init");
assert.strictEqual(markCallExpPath.node, markCallExp);
markCallExpPath.addComment("leading", "#__PURE__");
return t.clone(markedId);
}
let argumentsThisVisitor = {
"FunctionExpression|FunctionDeclaration|Method": function(path) {
path.skip();
},
Identifier: function(path, state) {
if (path.node.name === "arguments" && util.isReference(path)) {
util.replaceWithOrRemove(path, state.getArgsId());
state.usesArguments = true;
}
},
ThisExpression: function(path, state) {
state.usesThis = true;
}
};
let functionSentVisitor = {
MetaProperty(path) {
let { node } = path;
if (node.meta.name === "function" &&
node.property.name === "sent") {
const t = util.getTypes();
util.replaceWithOrRemove(
path,
t.memberExpression(
t.clone(this.context),
t.identifier("_sent")
)
);
}
}
};
let awaitVisitor = {
Function: function(path) {
path.skip(); },
AwaitExpression: function(path) {
const t = util.getTypes();
let argument = path.node.argument;
util.replaceWithOrRemove(path, t.yieldExpression(
t.callExpression(
util.runtimeProperty("awrap"),
[argument]
),
false
));
}
};