From 7ff46eaca87ee3ed56e19c0bcce861f264ac864a Mon Sep 17 00:00:00 2001 From: "Roman.Ivanov" Date: Wed, 28 Nov 2018 11:28:05 +0700 Subject: [PATCH] EnhancedSwitchMigrationInspection: suppress, when used value from another branch --- .../EnhancedSwitchMigrationInspection.java | 15 +++++++++++++++ ...beforeSwitchStatementsDuplicatingBranch.java | 17 +++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 java/java-tests/testData/inspection/switchExpressionMigration/beforeSwitchStatementsDuplicatingBranch.java diff --git a/java/java-impl/src/com/intellij/codeInspection/EnhancedSwitchMigrationInspection.java b/java/java-impl/src/com/intellij/codeInspection/EnhancedSwitchMigrationInspection.java index a80b001f65cf..75f01c078499 100644 --- a/java/java-impl/src/com/intellij/codeInspection/EnhancedSwitchMigrationInspection.java +++ b/java/java-impl/src/com/intellij/codeInspection/EnhancedSwitchMigrationInspection.java @@ -442,6 +442,15 @@ public class EnhancedSwitchMigrationInspection extends AbstractBaseJavaLocalInsp for (SwitchBranch branch : branches) { if (branch.myIsFallthrough) return null; } + for (SwitchBranch branch : branches) { + boolean allBranchRefsWillBeValid = StreamEx.of(branch.myStatements) + .flatMap((PsiElement stmt) -> StreamEx.ofTree(stmt, el -> StreamEx.of(el.getChildren()))) + .select(PsiReferenceExpression.class) + .map(PsiReference::resolve) + .select(PsiLocalVariable.class) + .allMatch(variable -> isInBranchOrOutside(switchStmt, branch, variable)); + if (!allBranchRefsWillBeValid) return null; + } List switchRules = new ArrayList<>(); for (SwitchBranch branch : branches) { PsiStatement[] statements = branch.getStatements(); @@ -449,6 +458,12 @@ public class EnhancedSwitchMigrationInspection extends AbstractBaseJavaLocalInsp } return new SwitchStatementReplacer(switchStmt, expression, switchRules); } + + private static boolean isInBranchOrOutside(@NotNull PsiSwitchStatement switchStmt, + SwitchBranch branch, PsiLocalVariable variable) { + return !PsiTreeUtil.isAncestor(switchStmt, variable, false) + || StreamEx.of(branch.myStatements).anyMatch(stmt -> PsiTreeUtil.isAncestor(stmt, variable, false)); + } } private static class SwitchStatementBranch implements SwitchRuleResult { diff --git a/java/java-tests/testData/inspection/switchExpressionMigration/beforeSwitchStatementsDuplicatingBranch.java b/java/java-tests/testData/inspection/switchExpressionMigration/beforeSwitchStatementsDuplicatingBranch.java new file mode 100644 index 000000000000..e8ec0fa6c958 --- /dev/null +++ b/java/java-tests/testData/inspection/switchExpressionMigration/beforeSwitchStatementsDuplicatingBranch.java @@ -0,0 +1,17 @@ +// "Replace with enhanced 'switch' statement" "false" +import java.util.*; + +class SwitchExpressionMigration { + private static String m(int n) { + switch (n) { + case 1: + int x = 0; + System.out.println("a"); + break; + case 2: + x = 3; + System.out.println(x); + break; + } + } +} \ No newline at end of file