From 42faa17b1c93f801b14bea2840d1d528e25c7211 Mon Sep 17 00:00:00 2001 From: Matt Wilkinson Date: Tue, 18 Jul 2023 13:46:20 +0100 Subject: [PATCH] fix: Update no-loop-func to not overlap with no-undef (#17358) --- lib/rules/no-loop-func.js | 2 +- tests/lib/rules/no-loop-func.js | 54 ++++++++++++++++++++++++++++----- 2 files changed, 47 insertions(+), 9 deletions(-) diff --git a/lib/rules/no-loop-func.js b/lib/rules/no-loop-func.js index e1d65fdc92c..48312fbf58a 100644 --- a/lib/rules/no-loop-func.js +++ b/lib/rules/no-loop-func.js @@ -186,7 +186,7 @@ module.exports = { } const references = sourceCode.getScope(node).through; - const unsafeRefs = references.filter(r => !isSafe(loopNode, r)).map(r => r.identifier.name); + const unsafeRefs = references.filter(r => r.resolved && !isSafe(loopNode, r)).map(r => r.identifier.name); if (unsafeRefs.length > 0) { context.report({ diff --git a/tests/lib/rules/no-loop-func.js b/tests/lib/rules/no-loop-func.js index ba161ec49d6..f1311000f91 100644 --- a/tests/lib/rules/no-loop-func.js +++ b/tests/lib/rules/no-loop-func.js @@ -111,7 +111,53 @@ ruleTester.run("no-loop-func", rule, { "let a;" ].join("\n"), parserOptions: { ecmaVersion: 6 } + }, + + /* + * These loops _look_ like they might be unsafe, but because i is undeclared, they're fine + * at least as far as this rule is concerned - the loop doesn't declare/generate the variable. + */ + "while(i) { (function() { i; }) }", + "do { (function() { i; }) } while (i)", + + /** + * These loops _look_ like they might be unsafe, but because i is declared outside the loop + * and is not updated in or after the loop, they're fine as far as this rule is concerned. + * The variable that's captured is just the one variable shared by all the loops, but that's + * explicitly expected in these cases. + */ + "var i; while(i) { (function() { i; }) }", + "var i; do { (function() { i; }) } while (i)", + + /** + * These loops use an undeclared variable, and so shouldn't be flagged by this rule, + * they'll be picked up by no-undef. + */ + { + code: "for (var i=0; i x != undeclared)) { } }", + parserOptions: { ecmaVersion: 6 } } + ], invalid: [ { @@ -152,14 +198,6 @@ ruleTester.run("no-loop-func", rule, { code: "for (var i=0; i