switch expressions: ensure code block around extracted variable (IDEA-202630)

This commit is contained in:
Anna.Kozlova
2018-11-21 18:51:47 +01:00
parent 5f04c66a42
commit 2e30e0c457
5 changed files with 38 additions and 0 deletions
@@ -120,6 +120,12 @@ class VariableExtractor {
if (myAnchor instanceof PsiExpression) {
myAnchor = RefactoringUtil.getParentStatement(RefactoringUtil.ensureCodeBlock(((PsiExpression)myAnchor)), false);
}
else if (myAnchor instanceof PsiSwitchLabeledRuleStatement) {
PsiStatement body = ((PsiSwitchLabeledRuleStatement)myAnchor).getBody();
if (body instanceof PsiExpressionStatement) {
myAnchor = RefactoringUtil.getParentStatement(RefactoringUtil.ensureCodeBlock(((PsiExpressionStatement)body).getExpression()), false);
}
}
}
private void highlight(PsiVariable var) {
@@ -81,6 +81,17 @@ class EnsureCodeBlockImpl {
if (parent instanceof PsiReturnStatement && condition != null) {
return replace(expression, parent, (oldParent, copy) -> splitReturn((PsiReturnStatement)oldParent, condition, operand));
}
if (parent instanceof PsiSwitchLabeledRuleStatement) {
PsiStatement body = ((PsiSwitchLabeledRuleStatement)parent).getBody();
if (body instanceof PsiExpressionStatement) {
PsiExpression resultExpression = ((PsiExpressionStatement)body).getExpression();
return replace(expression, body, (old, copy) -> {
PsiBlockStatement block = (PsiBlockStatement)old.replace(factory.createStatementFromText("{break a;}", resultExpression));
PsiExpression copyExpression = ((PsiBreakStatement)block.getCodeBlock().getStatements()[0]).getExpression();
return Objects.requireNonNull(copyExpression).replace(((PsiExpressionStatement)copy).getExpression());
});
}
}
return expression;
}
@@ -0,0 +1,10 @@
class MyTest {
void m(int i) {
String s = switch (i) {
default -> {
String temp = "abc";
break temp;
}
};
}
}
@@ -0,0 +1,7 @@
class MyTest {
void m(int i) {
String s = switch (i) {
default -> <selection>"abc"</selection>;
};
}
}
@@ -247,6 +247,10 @@ public class IntroduceVariableTest extends LightCodeInsightTestCase {
doTest(new MockIntroduceVariableHandler("temp", true, false, false, CommonClassNames.JAVA_LANG_STRING));
}
public void testEnsureCodeBlockAroundBreakStatementJava12Preview() {
doTest(new MockIntroduceVariableHandler("temp", true, false, false, CommonClassNames.JAVA_LANG_STRING));
}
public void testDeclareTernary() {
doTest(new MockIntroduceVariableHandler("temp", true, false, false, CommonClassNames.JAVA_LANG_STRING));
}