IDEA-209745 Extracting variable from enhanced switch expression creates red code

This commit is contained in:
Tagir Valeev
2019-04-04 13:31:52 +07:00
parent bdcdc4379e
commit d5bc6f4ba7
6 changed files with 52 additions and 6 deletions

View File

@@ -260,6 +260,14 @@ class VariableExtractor {
private static PsiElement correctAnchor(PsiExpression expr,
@NotNull PsiElement anchor,
PsiExpression[] occurrences) {
if (anchor instanceof PsiSwitchLabelStatementBase) {
PsiSwitchBlock block = ((PsiSwitchLabelStatementBase)anchor).getEnclosingSwitchBlock();
if (block == null) return anchor;
anchor = block;
if (anchor instanceof PsiExpression) {
expr = (PsiExpression)anchor;
}
}
PsiExpression firstOccurrence = StreamEx.of(occurrences).append(expr)
.minBy(e -> e.getTextRange().getStartOffset()).orElse(null);
if (anchor instanceof PsiWhileStatement) {
@@ -295,12 +303,6 @@ class VariableExtractor {
if (anchor.getParent() instanceof PsiSwitchLabeledRuleStatement) {
return ExpressionUtils.getTopLevelExpression(expr);
}
if (anchor instanceof PsiSwitchLabelStatement) {
PsiSwitchBlock block = ((PsiSwitchLabelStatement)anchor).getEnclosingSwitchBlock();
if (block instanceof PsiSwitchStatement) {
return block;
}
}
if (RefactoringUtil.isLoopOrIf(anchor.getParent())) return anchor;
PsiElement child = locateAnchor(anchor);
if (IntroduceVariableBase.isFinalVariableOnLHS(expr)) {

View File

@@ -0,0 +1,10 @@
class A {
private void A() {
final int i = 2;
System.out.println(switch (1) {
case 1 -> 5;
case i -> 7;
default -> 9;
});
}
}

View File

@@ -0,0 +1,9 @@
class A {
private void A() {
System.out.println(switch (1) {
case 1 -> 5;
case <selection>2</selection> -> 7;
default -> 9;
});
}
}

View File

@@ -0,0 +1,9 @@
class A {
private void A() {
final int i = 2;
switch (1) {
case 1 -> System.out.println(1);
case i -> System.out.println(3);
}
}
}

View File

@@ -0,0 +1,8 @@
class A {
private void A() {
switch (1) {
case 1 -> System.out.println(1);
case <selection>2</selection> -> System.out.println(3);
}
}
}

View File

@@ -226,6 +226,14 @@ public class IntroduceVariableTest extends LightCodeInsightTestCase {
doTest(new IntroduceVariableHandler());
}
public void testCaseLabelRuleSingle() {
doTest(new IntroduceVariableHandler());
}
public void testCaseLabelRuleExpression() {
doTest(new IntroduceVariableHandler());
}
public void testCaseLabelEnum() {
try {
doTest(new MockIntroduceVariableHandler("temp", true, false, false, ""));