From f9cfb38ef10b94f539ae47f00b36210f70cc90cd Mon Sep 17 00:00:00 2001 From: Toru Nagashima Date: Thu, 9 May 2019 06:31:58 +0900 Subject: [PATCH] Fix: ignore return statements in dead code (fixes #11647) --- lib/rules/no-useless-return.js | 9 ++++++++- tests/lib/rules/no-useless-return.js | 17 ++++++++++++----- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/lib/rules/no-useless-return.js b/lib/rules/no-useless-return.js index bb11b4b3619..2ac7112872d 100644 --- a/lib/rules/no-useless-return.js +++ b/lib/rules/no-useless-return.js @@ -255,7 +255,14 @@ module.exports = { if (node.argument) { markReturnStatementsOnCurrentSegmentsAsUsed(); } - if (node.argument || astUtils.isInLoop(node) || isInFinally(node)) { + if ( + node.argument || + astUtils.isInLoop(node) || + isInFinally(node) || + + // Ignore `return` statements in unreachable places (https://github.com/eslint/eslint/issues/11647). + !scopeInfo.codePath.currentSegments.some(s => s.reachable) + ) { return; } diff --git a/tests/lib/rules/no-useless-return.js b/tests/lib/rules/no-useless-return.js index 56ad245c2c9..669d245241f 100644 --- a/tests/lib/rules/no-useless-return.js +++ b/tests/lib/rules/no-useless-return.js @@ -165,6 +165,17 @@ ruleTester.run("no-useless-return", rule, { throw new Error('foo'); while (false); } catch (err) {} + `, + + // https://github.com/eslint/eslint/issues/11647 + ` + function foo(arg) { + throw new Error("Debugging..."); + if (!arg) { + return; + } + console.log(arg); + } ` ], @@ -418,11 +429,7 @@ ruleTester.run("no-useless-return", rule, { }, { code: "function foo() { return; return; }", - output: "function foo() { return; }", // Other case is fixed in the second pass. - errors: [ - { message: "Unnecessary return statement.", type: "ReturnStatement" }, - { message: "Unnecessary return statement.", type: "ReturnStatement" } - ] + output: "function foo() { return; }" } ].map(invalidCase => Object.assign({ errors: [{ message: "Unnecessary return statement.", type: "ReturnStatement" }] }, invalidCase)) });