add necessary parentheses when simplifying if (IDEA-178828)

This commit is contained in:
Bas Leijdekkers
2017-09-12 21:21:44 +02:00
parent 22f01cfd39
commit 2efae9fe9a
4 changed files with 25 additions and 30 deletions
@@ -92,7 +92,7 @@ public class BoolUtils {
}
if (expression instanceof PsiPolyadicExpression) {
final PsiPolyadicExpression polyadicExpression = (PsiPolyadicExpression)expression;
IElementType tokenType = polyadicExpression.getOperationTokenType();
final IElementType tokenType = polyadicExpression.getOperationTokenType();
final PsiExpression[] operands = polyadicExpression.getOperands();
if (ComparisonUtils.isComparison(polyadicExpression)) {
final String negatedComparison = ComparisonUtils.getNegatedComparison(tokenType);
@@ -121,23 +121,23 @@ public class BoolUtils {
}
if(tokenType.equals(JavaTokenType.ANDAND) || tokenType.equals(JavaTokenType.OROR)) {
final String targetToken;
final boolean needParenthesis;
final int newPrecedence;
if (tokenType.equals(JavaTokenType.ANDAND)) {
targetToken = "||";
needParenthesis = ParenthesesUtils.OR_PRECEDENCE > precedence;
newPrecedence = ParenthesesUtils.OR_PRECEDENCE;
}
else {
targetToken = "&&";
needParenthesis = ParenthesesUtils.AND_PRECEDENCE > precedence;
newPrecedence = ParenthesesUtils.AND_PRECEDENCE;
}
Function<PsiElement, String> replacer = child -> {
final Function<PsiElement, String> replacer = child -> {
if (child instanceof PsiExpression) {
return getNegatedExpressionText((PsiExpression)child);
return getNegatedExpressionText((PsiExpression)child, newPrecedence);
}
return child instanceof PsiJavaToken ? targetToken : child.getText();
};
final String join = StringUtil.join(polyadicExpression.getChildren(), replacer, "");
return needParenthesis ? '(' + join + ')' : join;
return (newPrecedence > precedence) ? '(' + join + ')' : join;
}
}
return '!' + ParenthesesUtils.getText(expression, ParenthesesUtils.PREFIX_PRECEDENCE);
@@ -0,0 +1,5 @@
class X {
boolean test(String s1, String s2) {
return (s1 == null || s1.isEmpty()) && (s2 == null || s2.isEmpty());
}
}
@@ -0,0 +1,6 @@
class X {
boolean test(String s1, String s2) {
if<caret>(s1 != null && !s1.isEmpty() || s2 != null && !s2.isEmpty()) return false;
return true;
}
}
@@ -28,27 +28,11 @@ public class TrivialIfFixTest extends IGQuickFixesTestCase {
myDefaultHint = "Simplify 'if else'";
}
public void testComments() {
doTest();
}
public void testCommentsInAssignment() {
doTest();
}
public void testNegatedConditional() {
doTest();
}
public void testNegatedConditional1() {
doTest();
}
public void testAssert1() {
doTest();
}
public void testAssert2() {
doTest();
}
public void testComments() { doTest(); }
public void testCommentsInAssignment() { doTest(); }
public void testNegatedConditional() { doTest(); }
public void testNegatedConditional1() { doTest(); }
public void testAssert1() { doTest(); }
public void testAssert2() { doTest(); }
public void testParentheses() { doTest(); }
}