forbid function declarations that reference block scoped variables

This commit is contained in:
Sebastian McKenzie
2014-10-17 21:19:51 +11:00
parent aeac003dc8
commit 0188556b36
3 changed files with 16 additions and 13 deletions

View File

@@ -26,8 +26,10 @@ exports.VariableDeclaration = function (node, parent, file) {
if (util.isReferenced(node, parent)) return id;
};
var isProgram = parent.type === "Program";
var replace = function (node, parent) {
if (_.contains(traverse.FUNCTION_TYPES, node.type)) {
if (!isProgram && _.contains(traverse.FUNCTION_TYPES, node.type)) {
var letReferences = [];
traverse(node, function (node, parent) {
@@ -37,21 +39,12 @@ exports.VariableDeclaration = function (node, parent, file) {
});
if (letReferences.length) {
var callNode = function () {
if (node.type === "FunctionDeclaration") {
throw new Error("`FunctionDeclaration`s that use `let` and `constant` references aren't allowed outside of the root scope");
} else {
return b.callExpression(b.functionExpression(null, letReferences, b.blockStatement([
b.returnStatement(node)
])), letReferences);
};
if (node.type === "FunctionDeclaration") {
util.ensureExpressionType(node);
var declar = b.variableDeclaration("var", [
b.variableDeclarator(node.id, callNode())
]);
declar._blockHoist = true;
return declar;
} else {
return callNode();
}
} else {
return false;