ConditionalExpressionGenerator: minor fixes

Review ID: IDEA-CR-59614

GitOrigin-RevId: b42420290fd1cc85dc7024b4a1cdab6b9a9cac91
This commit is contained in:
Tagir Valeev
2020-03-10 05:03:32 +00:00
committed by intellij-monorepo-bot
parent a6824c8de5
commit f24047635c
2 changed files with 31 additions and 11 deletions
@@ -69,12 +69,22 @@ public final class ConditionalExpressionGenerator {
PsiExpression condition = model.getCondition();
PsiExpression thenExpression = model.getThenExpression();
PsiExpression elseExpression = model.getElseExpression();
if (PsiType.BOOLEAN.equals(model.getType())) {
if (PsiType.BOOLEAN.equals(model.getType()) || model.getType().equalsToText(CommonClassNames.JAVA_LANG_BOOLEAN)) {
PsiLiteralExpression thenLiteral = ExpressionUtils.getLiteral(thenExpression);
PsiLiteralExpression elseLiteral = ExpressionUtils.getLiteral(elseExpression);
Boolean thenValue = thenLiteral == null ? null : tryCast(thenLiteral.getValue(), Boolean.class);
Boolean elseValue = elseLiteral == null ? null : tryCast(elseLiteral.getValue(), Boolean.class);
if (thenValue != null || elseValue != null) {
if (thenValue != null && elseValue != null) {
if (thenValue.equals(elseValue)) {
// Equal branches are handled by separate inspections
return null;
}
if (thenValue) {
return new ConditionalExpressionGenerator("", condition);
}
return new ConditionalExpressionGenerator("", ct -> BoolUtils.getNegatedExpressionText(condition, ct));
}
if ((thenValue != null || elseValue != null) && PsiType.BOOLEAN.equals(model.getType())) {
return getAndOrGenerator(condition, thenExpression, elseExpression, thenValue, elseValue);
}
if (BoolUtils.areExpressionsOpposite(thenExpression, elseExpression)) {
@@ -93,15 +103,6 @@ public final class ConditionalExpressionGenerator {
PsiExpression elseExpression,
Boolean thenValue,
Boolean elseValue) {
if (thenValue != null && elseValue != null) {
if (thenValue.equals(elseValue)) {
return new ConditionalExpressionGenerator("", thenExpression);
}
if (thenValue) {
return new ConditionalExpressionGenerator("", condition);
}
return new ConditionalExpressionGenerator("", ct -> BoolUtils.getNegatedExpressionText(condition, ct));
}
if (thenValue != null) {
if (thenValue) {
return new ConditionalExpressionGenerator("||", ct -> joinConditions(condition, elseExpression, false, ct));
@@ -91,6 +91,25 @@ public class TrivialIfInspectionTest extends LightJavaInspectionTestCase {
" else return false;\n" +
"}\n");
}
public void testReturnEqualBranches() {
// no warning: another inspection takes care about this
doMemberTest("\n" +
" boolean b(int x) {\n" +
" if (x > 20) return true;\n" +
" else return true;\n" +
"}\n");
}
public void testMethodCall() {
doMemberTest("void test(int x, Boolean foo) {\n" +
" if (x == 0) System.out.println(foo);\n" +
" else {\n" +
" /*'if' statement can be simplified*/if/**/ (x > 0) test(0, true);\n" +
" else test(0, false);\n" +
" }\n" +
"}");
}
@Override
protected InspectionProfileEntry getInspection() {