use CommentTracker.text() with precedence argument

This commit is contained in:
Bas Leijdekkers
2018-01-18 15:19:20 +01:00
parent 28f36903e9
commit f2e6fca603
20 changed files with 109 additions and 203 deletions
@@ -0,0 +1,15 @@
// "Merge sequential 'if's" "true"
class ImplicitOr {
void liability() {
/*equivocal*/
if (true || true) {
System.out.println();
// atavistic
return;
}
/*indubious*/
// vestigial
}
}
@@ -0,0 +1,17 @@
// "Merge sequential 'if's" "true"
class ImplicitOr {
void liability() {
<caret>if /*equivocal*/(true) {
System.out.println();
// atavistic
return;
}
if/*indubious*/ (true) {
System.out.println();
// vestigial
return;
}
}
}
@@ -159,20 +159,12 @@ public class IfMayBeConditionalInspection extends BaseInspection {
PsiReplacementUtil.replaceStatement(ifStatement, replacementText.toString(), tracker);
}
private static void appendExpressionText(@Nullable PsiExpression expression,
StringBuilder out,
CommentTracker tracker) {
private static void appendExpressionText(@Nullable PsiExpression expression, StringBuilder out, CommentTracker tracker) {
expression = ParenthesesUtils.stripParentheses(expression);
if (expression == null) {
return;
}
final String expressionText = tracker.text(expression);
if (ParenthesesUtils.getPrecedence(expression) > ParenthesesUtils.CONDITIONAL_PRECEDENCE) {
out.append('(').append(expressionText).append(')');
}
else {
out.append(expressionText);
}
out.append(tracker.text(expression, ParenthesesUtils.CONDITIONAL_PRECEDENCE));
}
}
@@ -104,12 +104,7 @@ public class EqualityToEqualsFix extends InspectionGadgetsFix {
if (JavaTokenType.NE.equals(expression.getOperationTokenType())) {
newExpression.append('!');
}
if (ParenthesesUtils.getPrecedence(lhs) > ParenthesesUtils.METHOD_CALL_PRECEDENCE) {
newExpression.append('(').append(commentTracker.text(lhs)).append(')');
}
else {
newExpression.append(commentTracker.text(lhs));
}
newExpression.append(commentTracker.text(lhs, ParenthesesUtils.METHOD_CALL_PRECEDENCE));
newExpression.append(".equals(").append(commentTracker.text(rhs)).append(')');
PsiReplacementUtil.replaceExpressionAndShorten(expression, newExpression.toString(), commentTracker);
@@ -1,17 +1,5 @@
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package com.siyeh.ig.fixes;
@@ -67,18 +55,14 @@ public class EqualsToEqualityFix extends InspectionGadgetsFix {
return;
}
final PsiElement parent = ParenthesesUtils.getParentSkipParentheses(call);
CommentTracker commentTracker = new CommentTracker();
commentTracker.markUnchanged(lhs);
commentTracker.markUnchanged(rhs);
final CommentTracker commentTracker = new CommentTracker();
final String lhsText = commentTracker.text(lhs, ParenthesesUtils.EQUALITY_PRECEDENCE);
final String rhsText = commentTracker.text(rhs, ParenthesesUtils.EQUALITY_PRECEDENCE);
if (parent instanceof PsiExpression && BoolUtils.isNegation((PsiExpression)parent)) {
PsiReplacementUtil.replaceExpression((PsiExpression)parent, getText(lhs) + "!=" + getText(rhs), commentTracker);
PsiReplacementUtil.replaceExpression((PsiExpression)parent, lhsText + "!=" + rhsText, commentTracker);
}
else {
PsiReplacementUtil.replaceExpression(call, getText(lhs) + "==" + getText(rhs), commentTracker);
PsiReplacementUtil.replaceExpression(call, lhsText + "==" + rhsText, commentTracker);
}
}
private static String getText(PsiExpression rhs) {
return ParenthesesUtils.getPrecedence(rhs) > ParenthesesUtils.EQUALITY_PRECEDENCE ? '(' + rhs.getText() + ')' : rhs.getText();
}
}
@@ -93,20 +93,12 @@ public class MultiplyOrDivideByPowerOfTwoInspection
if (!(rhs instanceof PsiLiteralExpression)) return null;
commentTracker.markUnchanged(lhs);
final String lhsText;
if (ParenthesesUtils.getPrecedence(lhs) > ParenthesesUtils.SHIFT_PRECEDENCE) {
lhsText = '(' + lhs.getText() + ')';
}
else {
lhsText = lhs.getText();
}
final String lhsText = commentTracker.text(lhs, ParenthesesUtils.SHIFT_PRECEDENCE);
String expString = lhsText + operator + ShiftUtils.getLogBaseTwo((PsiLiteralExpression)rhs);
final PsiElement parent = expression.getParent();
if (parent instanceof PsiExpression) {
if (!(parent instanceof PsiParenthesizedExpression) &&
ParenthesesUtils.getPrecedence((PsiExpression)parent) <
ParenthesesUtils.SHIFT_PRECEDENCE) {
ParenthesesUtils.getPrecedence((PsiExpression)parent) < ParenthesesUtils.SHIFT_PRECEDENCE) {
expString = '(' + expString + ')';
}
}
@@ -134,13 +134,8 @@ public class ImplicitNumericConversionInspection extends BaseInspection {
}
}
CommentTracker commentTracker = new CommentTracker();
final String castExpression;
if (ParenthesesUtils.getPrecedence(expression) <= ParenthesesUtils.TYPE_CAST_PRECEDENCE) {
castExpression = '(' + expectedType.getCanonicalText() + ')' + commentTracker.text(expression);
}
else {
castExpression = '(' + expectedType.getCanonicalText() + ")(" + commentTracker.text(expression) + ')';
}
final String castExpression =
'(' + expectedType.getCanonicalText() + ')' + commentTracker.text(expression, ParenthesesUtils.TYPE_CAST_PRECEDENCE);
PsiReplacementUtil.replaceExpression(expression, castExpression, commentTracker);
}
}
@@ -272,7 +272,7 @@ public class ManualArrayCopyInspection extends BaseInspection {
}
min = ParenthesesUtils.stripParentheses(min);
if (min == null) {
return buildExpressionText(max, plusOne, false, commentTracker);
return buildExpressionText(max, plusOne, commentTracker);
}
final Object minConstant = ExpressionUtils.computeConstantExpression(min);
if (minConstant instanceof Number) {
@@ -285,7 +285,7 @@ public class ManualArrayCopyInspection extends BaseInspection {
minValue = minNumber.intValue();
}
if (minValue == 0) {
return buildExpressionText(max, false, false, commentTracker);
return buildExpressionText(max, false, commentTracker);
}
if (max instanceof PsiLiteralExpression) {
final Object maxConstant = ExpressionUtils.computeConstantExpression(max);
@@ -294,7 +294,7 @@ public class ManualArrayCopyInspection extends BaseInspection {
return String.valueOf(number.intValue() - minValue);
}
}
final String maxText = buildExpressionText(max, false, false, commentTracker);
final String maxText = buildExpressionText(max, false, commentTracker);
if (minValue > 0) {
return maxText + '-' + minValue;
}
@@ -302,33 +302,14 @@ public class ManualArrayCopyInspection extends BaseInspection {
return maxText + '+' + -minValue;
}
}
final int precedence = ParenthesesUtils.getPrecedence(min);
final String minText;
if (precedence >= ParenthesesUtils.ADDITIVE_PRECEDENCE) {
minText = '(' + commentTracker.text(min) + ')';
}
else {
minText = commentTracker.text(min);
}
final String maxText = buildExpressionText(max, plusOne, false, commentTracker);
final String minText = commentTracker.text(min, ParenthesesUtils.ADDITIVE_PRECEDENCE);
final String maxText = buildExpressionText(max, plusOne, commentTracker);
return maxText + '-' + minText;
}
private static String buildExpressionText(PsiExpression expression,
boolean plusOne,
boolean parenthesize,
CommentTracker commentTracker) {
private static String buildExpressionText(PsiExpression expression, boolean plusOne, CommentTracker commentTracker) {
if (!plusOne) {
final int precedence = ParenthesesUtils.getPrecedence(expression);
if (precedence > ParenthesesUtils.ADDITIVE_PRECEDENCE) {
return '(' + commentTracker.text(expression) + ')';
}
else {
if (parenthesize && precedence >= ParenthesesUtils.ADDITIVE_PRECEDENCE) {
return '(' + commentTracker.text(expression) + ')';
}
return commentTracker.text(expression);
}
return commentTracker.text(expression, ParenthesesUtils.ADDITIVE_PRECEDENCE);
}
if (expression instanceof PsiBinaryExpression) {
final PsiBinaryExpression binaryExpression = (PsiBinaryExpression)expression;
@@ -348,18 +329,7 @@ public class ManualArrayCopyInspection extends BaseInspection {
return String.valueOf(integer.intValue() + 1);
}
}
final int precedence = ParenthesesUtils.getPrecedence(expression);
final String result;
if (precedence > ParenthesesUtils.ADDITIVE_PRECEDENCE) {
result = '(' + commentTracker.text(expression) + ")+1";
}
else {
result = commentTracker.text(expression) + "+1";
}
if (parenthesize) {
return '(' + result + ')';
}
return result;
return commentTracker.text(expression, ParenthesesUtils.ADDITIVE_PRECEDENCE) + "+1";
}
@NonNls
@@ -380,11 +350,10 @@ public class ManualArrayCopyInspection extends BaseInspection {
if (initialValue == null) {
return null;
}
return buildExpressionText(initialValue, plusOne, false, commentTracker);
return buildExpressionText(initialValue, plusOne, commentTracker);
}
else if (expression instanceof PsiBinaryExpression) {
final PsiBinaryExpression binaryExpression =
(PsiBinaryExpression)expression;
final PsiBinaryExpression binaryExpression = (PsiBinaryExpression)expression;
final PsiExpression lhs = binaryExpression.getLOperand();
final PsiExpression rhs = binaryExpression.getROperand();
final String rhsText =
@@ -399,16 +368,13 @@ public class ManualArrayCopyInspection extends BaseInspection {
}
if (plusOne && tokenType.equals(JavaTokenType.MINUS) &&
ExpressionUtils.isOne(rhs)) {
return buildOffsetText(lhs, variable, limitExpression,
false, commentTracker);
return buildOffsetText(lhs, variable, limitExpression, false, commentTracker);
}
final String lhsText = buildOffsetText(lhs, variable,
limitExpression, plusOne, commentTracker);
final String lhsText = buildOffsetText(lhs, variable, limitExpression, plusOne, commentTracker);
if (ExpressionUtils.isZero(rhs)) {
return lhsText;
}
return collapseConstant(lhsText + sign.getText() + rhsText,
variable);
return collapseConstant(lhsText + sign.getText() + rhsText, variable);
}
return collapseConstant(commentTracker.text(expression), variable);
}
@@ -218,12 +218,7 @@ public class PointlessBooleanExpressionInspection extends BaseInspection {
out.append(tracker.text(lhs)).append(negatedComparison).append(tracker.text(rhs));
}
else {
if (ParenthesesUtils.getPrecedence(expression) > ParenthesesUtils.PREFIX_PRECEDENCE) {
out.append("!(").append(tracker.text(expression)).append(')');
}
else {
out.append('!').append(tracker.text(expression));
}
out.append('!').append(tracker.text(expression, ParenthesesUtils.PREFIX_PRECEDENCE));
}
}
else {
@@ -0,0 +1,6 @@
class Precedence {
boolean m(Integer i) {
return (i++).equals(Integer.valueOf(10));
}
}
@@ -0,0 +1,6 @@
class Precedence {
boolean m(Integer i) {
return i++ ==<caret> Integer.valueOf(10);
}
}
@@ -0,0 +1,6 @@
class Precedence {
double m(int i) {
return (double) (i * 10);
}
}
@@ -0,0 +1,6 @@
class Precedence {
double m(int i) {
return i *<caret> 10;
}
}
@@ -1,22 +1,11 @@
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package com.siyeh.ig.fixes.bugs;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.IGQuickFixesTestCase;
import com.siyeh.ig.bugs.NumberEqualityInspection;
import com.siyeh.ig.bugs.ObjectEqualityInspection;
/**
@@ -25,12 +14,14 @@ import com.siyeh.ig.bugs.ObjectEqualityInspection;
public class EqualityToEqualsFixTest extends IGQuickFixesTestCase {
public void testSimple() { doTest(InspectionGadgetsBundle.message("equality.to.equals.quickfix")); }
public void testPrecedence() { doTest(InspectionGadgetsBundle.message("equality.to.equals.quickfix")); }
public void testNegated() { doTest(InspectionGadgetsBundle.message("inequality.to.not.equals.quickfix")); }
@Override
protected void setUp() throws Exception {
super.setUp();
myFixture.enableInspections(new ObjectEqualityInspection());
myFixture.enableInspections(new NumberEqualityInspection());
myRelativePath = "bugs/equality_to_equals";
}
}
@@ -26,6 +26,7 @@ public class ImplicitNumericConversionFixTest extends IGQuickFixesTestCase {
public void testOperatorAssignment() { doTest(); }
public void testHexadecimalLiteral() { doTest(); }
public void testPrecedence() { doTest(); }
@Override
protected void setUp() throws Exception {
@@ -68,23 +68,13 @@ public class DemorgansIntention extends MutablyNamedIntention {
return result.toString();
}
private static String convertLeafExpression(PsiExpression expression,
boolean tokenTypeAndAnd,
CommentTracker tracker) {
private static String convertLeafExpression(PsiExpression expression, boolean tokenTypeAndAnd, CommentTracker tracker) {
if (BoolUtils.isNegation(expression)) {
final PsiExpression negatedExpression = BoolUtils.getNegated(expression);
if (negatedExpression == null) {
return "";
}
if (tokenTypeAndAnd) {
if (ParenthesesUtils.getPrecedence(negatedExpression) > ParenthesesUtils.OR_PRECEDENCE) {
return '(' + tracker.text(negatedExpression) + ')';
}
}
else if (ParenthesesUtils.getPrecedence(negatedExpression) > ParenthesesUtils.AND_PRECEDENCE) {
return '(' + tracker.text(negatedExpression) + ')';
}
return tracker.text(negatedExpression);
return tracker.text(negatedExpression, tokenTypeAndAnd ? ParenthesesUtils.OR_PRECEDENCE : ParenthesesUtils.AND_PRECEDENCE);
}
else if (ComparisonUtils.isComparison(expression)) {
final PsiBinaryExpression binaryExpression = (PsiBinaryExpression)expression;
@@ -94,11 +84,8 @@ public class DemorgansIntention extends MutablyNamedIntention {
assert rhs != null;
return tracker.text(lhs) + negatedComparison + tracker.text(rhs);
}
else if (ParenthesesUtils.getPrecedence(expression) > ParenthesesUtils.PREFIX_PRECEDENCE) {
return "!(" + tracker.text(expression) + ')';
}
else {
return '!' + tracker.text(expression);
return '!' + tracker.text(expression, ParenthesesUtils.PREFIX_PRECEDENCE);
}
}
}
@@ -10,7 +10,6 @@ import com.intellij.psi.PsiType;
import com.siyeh.ig.PsiReplacementUtil;
import com.siyeh.ig.psiutils.BoolUtils;
import com.siyeh.ig.psiutils.CommentTracker;
import com.siyeh.ig.psiutils.ParenthesesUtils;
import com.siyeh.ipp.base.Intention;
import com.siyeh.ipp.base.PsiElementPredicate;
import org.jetbrains.annotations.NotNull;
@@ -55,11 +54,6 @@ public class ReplaceConditionalWithBooleanExpressionIntention extends Intention
if (expression == null) {
return "";
}
if (ParenthesesUtils.getPrecedence(expression) > AND_PRECEDENCE) {
return '(' + tracker.text(expression) + ')';
}
else {
return tracker.text(expression);
}
return tracker.text(expression, AND_PRECEDENCE);
}
}
@@ -52,17 +52,10 @@ public class ReplaceForEachLoopWithIteratorForLoopIntention extends Intention {
return;
}
CommentTracker tracker = new CommentTracker();
@NonNls final StringBuilder methodCall = new StringBuilder();
if (ParenthesesUtils.getPrecedence(iteratedValue) > ParenthesesUtils.METHOD_CALL_PRECEDENCE) {
methodCall.append('(').append(tracker.text(iteratedValue)).append(')');
}
else {
methodCall.append(tracker.text(iteratedValue));
}
methodCall.append(".iterator()");
final String methodCall = tracker.text(iteratedValue, ParenthesesUtils.METHOD_CALL_PRECEDENCE) + ".iterator()";
final Project project = statement.getProject();
final PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();
final PsiExpression iteratorCall = factory.createExpressionFromText(methodCall.toString(), iteratedValue);
final PsiExpression iteratorCall = factory.createExpressionFromText(methodCall, iteratedValue);
final PsiType variableType = GenericsUtil.getVariableTypeByExpressionType(iteratorCall.getType());
if (variableType == null) {
return;
@@ -98,8 +98,7 @@ public class ReplaceShiftWithMultiplyIntention extends MutablyNamedIntention {
}
private static void replaceShiftWithMultiplyOrDivide(PsiElement element) {
final PsiBinaryExpression exp =
(PsiBinaryExpression)element;
final PsiBinaryExpression exp = (PsiBinaryExpression)element;
final PsiExpression lhs = exp.getLOperand();
final PsiExpression rhs = exp.getROperand();
final IElementType tokenType = exp.getOperationTokenType();
@@ -110,23 +109,13 @@ public class ReplaceShiftWithMultiplyIntention extends MutablyNamedIntention {
else {
operatorString = "/";
}
final String lhsText;
if (ParenthesesUtils.getPrecedence(lhs) >
ParenthesesUtils.MULTIPLICATIVE_PRECEDENCE) {
lhsText = '(' + lhs.getText() + ')';
}
else {
lhsText = lhs.getText();
}
CommentTracker commentTracker = new CommentTracker();
commentTracker.markUnchanged(lhs);
String expString =
lhsText + operatorString + ShiftUtils.getExpBase2(rhs);
final String lhsText = commentTracker.text(lhs, ParenthesesUtils.MULTIPLICATIVE_PRECEDENCE);
String expString = lhsText + operatorString + ShiftUtils.getExpBase2(rhs);
final PsiElement parent = exp.getParent();
if (parent instanceof PsiExpression) {
if (!(parent instanceof PsiParenthesizedExpression) &&
ParenthesesUtils.getPrecedence((PsiExpression)parent) <
ParenthesesUtils.MULTIPLICATIVE_PRECEDENCE) {
ParenthesesUtils.getPrecedence((PsiExpression)parent) < ParenthesesUtils.MULTIPLICATIVE_PRECEDENCE) {
expString = '(' + expString + ')';
}
}
@@ -54,24 +54,12 @@ public class MergeIfOrIntention extends Intention {
return;
}
CommentTracker tracker = new CommentTracker();
final String childConditionText;
if (ParenthesesUtils.getPrecedence(childCondition) > ParenthesesUtils.OR_PRECEDENCE) {
childConditionText = '(' + tracker.text(childCondition) + ')';
}
else {
childConditionText = tracker.text(childCondition);
}
final String childConditionText = tracker.text(childCondition, ParenthesesUtils.OR_PRECEDENCE);
final PsiExpression condition = parentStatement.getCondition();
if (condition == null) {
return;
}
final String parentConditionText;
if (ParenthesesUtils.getPrecedence(condition) > ParenthesesUtils.OR_PRECEDENCE) {
parentConditionText = '(' + tracker.text(condition) + ')';
}
else {
parentConditionText = tracker.text(condition);
}
final String parentConditionText = tracker.text(condition, ParenthesesUtils.OR_PRECEDENCE);
final PsiStatement parentThenBranch = parentStatement.getThenBranch();
if (parentThenBranch == null) {
return;
@@ -89,8 +77,7 @@ public class MergeIfOrIntention extends Intention {
statement.append("else ");
statement.append(tracker.text(childElseBranch));
}
final String newStatement = statement.toString();
PsiReplacementUtil.replaceStatement(parentStatement, newStatement, tracker);
PsiReplacementUtil.replaceStatement(parentStatement, statement.toString(), tracker);
}
private static void replaceMergeableImplicitIf(PsiJavaToken token) {
@@ -101,25 +88,14 @@ public class MergeIfOrIntention extends Intention {
if (childCondition == null) {
return;
}
CommentTracker tracker = new CommentTracker();
final String childConditionText;
if (ParenthesesUtils.getPrecedence(childCondition) > ParenthesesUtils.OR_PRECEDENCE) {
childConditionText = '(' + tracker.text(childCondition) + ')';
}
else {
childConditionText = tracker.text(childCondition);
}
CommentTracker parentTracker = new CommentTracker();
CommentTracker childTracker = new CommentTracker();
final String childConditionText = childTracker.text(childCondition, ParenthesesUtils.OR_PRECEDENCE);
final PsiExpression condition = parentStatement.getCondition();
if (condition == null) {
return;
}
final String parentConditionText;
if (ParenthesesUtils.getPrecedence(condition) > ParenthesesUtils.OR_PRECEDENCE) {
parentConditionText = '(' + tracker.text(condition) + ')';
}
else {
parentConditionText = tracker.text(condition);
}
final String parentConditionText = parentTracker.text(condition, ParenthesesUtils.OR_PRECEDENCE);
final PsiStatement parentThenBranch = parentStatement.getThenBranch();
if (parentThenBranch == null) {
return;
@@ -130,13 +106,13 @@ public class MergeIfOrIntention extends Intention {
newStatement.append("||");
newStatement.append(childConditionText);
newStatement.append(')');
newStatement.append(tracker.text(parentThenBranch));
newStatement.append(parentTracker.text(parentThenBranch));
final PsiStatement childElseBranch = childStatement.getElseBranch();
if (childElseBranch != null) {
newStatement.append("else ");
newStatement.append(tracker.text(childElseBranch));
newStatement.append(childTracker.text(childElseBranch));
}
PsiReplacementUtil.replaceStatement(parentStatement, newStatement.toString());
tracker.deleteAndRestoreComments(childStatement);
PsiReplacementUtil.replaceStatement(parentStatement, newStatement.toString(), parentTracker);
childTracker.deleteAndRestoreComments(childStatement);
}
}