EnhancedSwitchMigrationInspection: suppress, when used value from another branch

This commit is contained in:
Roman.Ivanov
2018-11-28 11:29:01 +07:00
parent 59cc6f0cbe
commit 7ff46eaca8
2 changed files with 32 additions and 0 deletions
@@ -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<SwitchExpressionBranch> 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 {
@@ -0,0 +1,17 @@
// "Replace with enhanced 'switch' statement" "false"
import java.util.*;
class SwitchExpressionMigration {
private static String m(int n) {
switch<caret> (n) {
case 1:
int x = 0;
System.out.println("a");
break;
case 2:
x = 3;
System.out.println(x);
break;
}
}
}