SimplifyBooleanExpressionFix: fix 'while' handling after ensureCodeBlock improvements

This commit is contained in:
Tagir Valeev
2018-10-02 16:36:16 +07:00
parent 49e8a5a7ff
commit 8bb578e43c
5 changed files with 72 additions and 0 deletions
@@ -31,6 +31,7 @@ import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
public class SimplifyBooleanExpressionFix extends LocalQuickFixOnPsiElement {
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.daemon.impl.quickfix.SimplifyBooleanExpression");
@@ -124,6 +125,16 @@ public class SimplifyBooleanExpressionFix extends LocalQuickFixOnPsiElement {
if (subExpression == null) return;
CommentTracker ct = new CommentTracker();
if (shouldExtractSideEffect()) {
if (!mySubExpressionValue) {
// Prevent extracting while condition to internal 'if'
PsiWhileStatement whileStatement = ObjectUtils.tryCast(PsiUtil.skipParenthesizedExprUp(subExpression.getParent()), PsiWhileStatement.class);
if (whileStatement != null && whileStatement.getCondition() != null) {
PsiStatement replacement = JavaPsiFacade.getElementFactory(project)
.createStatementFromText("if(" + whileStatement.getCondition().getText() + ");", whileStatement);
PsiIfStatement ifStatement = (PsiIfStatement)whileStatement.replace(replacement);
subExpression = Objects.requireNonNull(ifStatement.getCondition());
}
}
subExpression = RefactoringUtil.ensureCodeBlock(subExpression);
if (subExpression == null) {
LOG.error("ensureCodeBlock returned null", new Attachment("subExpression.txt", getSubExpression().getText()));
@@ -0,0 +1,15 @@
// "Remove 'while' statement extracting side effects" "true"
import org.jetbrains.annotations.Contract;
class X {
@Contract("_ -> true")
boolean test(Object obj) {
return true;
}
void doSmth(Object obj) {
if (obj != null) {
test(obj);
}
}
}
@@ -0,0 +1,16 @@
// "Simplify 'test(...) || obj == null' to true extracting side effects" "true"
import org.jetbrains.annotations.Contract;
class X {
@Contract("_ -> true")
boolean test(Object obj) {
return true;
}
void doSmth(Object obj) {
while(obj != null) {
test(obj);
System.out.println("aaahh");
}
}
}
@@ -0,0 +1,15 @@
// "Remove 'while' statement extracting side effects" "true"
import org.jetbrains.annotations.Contract;
class X {
@Contract("_ -> true")
boolean test(Object obj) {
return true;
}
void doSmth(Object obj) {
while(obj <caret>!= null && test(obj) && obj == null) {
System.out.println("aaahh");
}
}
}
@@ -0,0 +1,15 @@
// "Simplify 'test(...) || obj == null' to true extracting side effects" "true"
import org.jetbrains.annotations.Contract;
class X {
@Contract("_ -> true")
boolean test(Object obj) {
return true;
}
void doSmth(Object obj) {
while(obj != null && (test(obj) <caret>|| obj == null)) {
System.out.println("aaahh");
}
}
}