Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: ignore IIFE's in the no-loop-func rule #17528

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
33 changes: 32 additions & 1 deletion docs/src/rules/no-loop-func.md
Expand Up @@ -34,7 +34,7 @@ In this case, each function created within the loop returns a different number a

This error is raised to highlight a piece of code that may not work as you expect it to and could also indicate a misunderstanding of how the language works. Your code may run without any problems if you do not fix this error, but in some situations it could behave unexpectedly.

This rule disallows any function within a loop that contains unsafe references (e.g. to modified variables from the outer scope).
This rule disallows any function within a loop that contains unsafe references (e.g. to modified variables from the outer scope). This rule ignores IIFEs but not async or generator functions.
snitin315 marked this conversation as resolved.
Show resolved Hide resolved

Examples of **incorrect** code for this rule:

Expand Down Expand Up @@ -76,6 +76,25 @@ for (let i = 0; i < 10; ++i) {
setTimeout(() => console.log(foo));
}
foo = 100;

var arr = [];

for (var i = 0; i < 5; i++) {
arr.push((f => f)(() => i));
}

for (var i = 0; i < 5; i++) {
arr.push((() => {
return () => i;
})());
}

for (var i = 0; i < 5; i++) {
(function fun () {
if (arr.includes(fun)) return i;
else arr.push(fun);
})();
}
snitin315 marked this conversation as resolved.
Show resolved Hide resolved
```

:::
Expand Down Expand Up @@ -110,6 +129,18 @@ for (let i=10; i; i--) {
a();
}
//... no modifications of foo after this loop ...

var arr = [];

for (var i = 0; i < 5; i++) {
arr.push((f => f)((() => i)()));
}

for (var i = 0; i < 5; i++) {
arr.push((() => {
return (() => i)();
})());
}
```

:::
70 changes: 64 additions & 6 deletions lib/rules/no-loop-func.js
Expand Up @@ -9,10 +9,19 @@
// Helpers
//------------------------------------------------------------------------------

/**
* Identifies is a node is a FunctionExpression which is part of an IIFE
* @param {ASTNode} node Node to test
* @returns {boolean} True if it's an IIFE
*/
function isIIFE(node) {
return (node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") && node.parent && node.parent.type === "CallExpression" && node.parent.callee === node;
}

/**
* Gets the containing loop node of a specified node.
*
* We don't need to check nested functions, so this ignores those.
* We don't need to check nested functions, so this ignores those, with the exception of IIFE.
* `Scope.through` contains references of nested functions.
* @param {ASTNode} node An AST node to get.
* @returns {ASTNode|null} The containing loop node of the specified node, or
Expand Down Expand Up @@ -48,9 +57,12 @@ function getContainingLoopNode(node) {
case "FunctionExpression":
case "FunctionDeclaration":

// We don't need to check nested functions.
return null;
// We need to check nested functions only in case of IIFE.
if (isIIFE(node)) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if (isIIFE(node)) {
if (isIIFE(parent)) {

break;
}

return null;
default:
break;
}
Expand Down Expand Up @@ -144,6 +156,7 @@ function isSafe(loopNode, reference) {
return Boolean(variable) && variable.references.every(isSafeReference);
}


//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
Expand Down Expand Up @@ -186,13 +199,58 @@ module.exports = {
}

const references = sourceCode.getScope(node).through;
const unsafeRefs = references.filter(r => r.resolved && !isSafe(loopNode, r)).map(r => r.identifier.name);
const unsafeRefs = references.filter(r => r.resolved && !isSafe(loopNode, r));
const unsafeRefsName = unsafeRefs.map(r => r.identifier.name);
snitin315 marked this conversation as resolved.
Show resolved Hide resolved

// Check if the function is not asynchronous or a generator function
if (!(node.async || node.generator)) {
snitin315 marked this conversation as resolved.
Show resolved Hide resolved
const isFunctionExpression = node.type === "FunctionExpression";

if (isIIFE(node)) {

// Check if the function is referenced elsewhere in the code
const isFunctionReferenced = isFunctionExpression && node.id ? references.some(r => r.identifier.name === node.id.name) : false;
snitin315 marked this conversation as resolved.
Show resolved Hide resolved

// Check if there are unsafe references used within non-immediately-invoked nested functions
const unsafeRefsInNonIIFE = unsafeRefs.filter(r => {
let refScope = r.from.variableScope;

if (node === refScope.block) {
return !isIIFE(refScope.block);
}

while (node !== refScope.block) {
if (!isIIFE(refScope.block)) {
return true;
}
refScope = refScope.upper.variableScope;
}
snitin315 marked this conversation as resolved.
Show resolved Hide resolved

return false;
});

const unsafeRefsInNonIIFEName = unsafeRefsInNonIIFE.map(r => r.identifier.name);

if (!isFunctionReferenced && unsafeRefsInNonIIFEName.length === 0) {
return;
}

if (unsafeRefsInNonIIFEName.length > 0) {
context.report({
node,
messageId: "unsafeRefs",
data: { varNames: `'${unsafeRefsInNonIIFEName.join("', '")}'` }
});
return;
}
}
}
Comment on lines +206 to +247
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is no need to check inner functions because they'll be checked separately.


if (unsafeRefs.length > 0) {
if (unsafeRefsName.length > 0) {
context.report({
node,
messageId: "unsafeRefs",
data: { varNames: `'${unsafeRefs.join("', '")}'` }
data: { varNames: `'${unsafeRefsName.join("', '")}'` }
});
}
}
Expand Down