add parentheses when necessary in quickfix for 'StringBuffer' can be replaced with 'String'

This commit is contained in:
Bas Leijdekkers
2012-01-31 20:38:30 +01:00
parent b597c0c54b
commit fd49897849
4 changed files with 36 additions and 2 deletions
@@ -24,6 +24,7 @@ import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.InspectionGadgetsFix;
import com.siyeh.ig.psiutils.ParenthesesUtils;
import com.siyeh.ig.psiutils.TypeUtils;
import com.siyeh.ig.psiutils.VariableAccessUtils;
import org.jetbrains.annotations.NotNull;
@@ -141,7 +142,13 @@ public class StringBufferReplaceableByStringInspection extends BaseInspection {
}
final PsiExpression argument = arguments[0];
if (result.length() != 0) {
result.append('+').append(argument.getText());
result.append('+');
if (ParenthesesUtils.getPrecedence(argument) > ParenthesesUtils.ADDITIVE_PRECEDENCE) {
result.append('(').append(argument.getText()).append(')');
}
else {
result.append(argument.getText());
}
}
else {
final PsiType type = argument.getType();
@@ -149,7 +156,12 @@ public class StringBufferReplaceableByStringInspection extends BaseInspection {
result.append("String.valueOf(").append(argument.getText()).append(")");
}
else {
result.append(argument.getText());
if (ParenthesesUtils.getPrecedence(argument) > ParenthesesUtils.ADDITIVE_PRECEDENCE) {
result.append('(').append(argument.getText()).append(')');
}
else {
result.append(argument.getText());
}
}
}
}
@@ -0,0 +1,9 @@
package com.siyeh.igfixes.style.replace_with_string;
import java.awt.*;
class Precedence {
public static String toRgbColor( final Color color) {
return "rgba(" + color.getRed() + ',' + color.getGreen() + ',' + color.getBlue() + ',' + (color.getAlpha() == 0 ? '0' : String.format("0.%2d", (int) (color.getAlpha() / 255.0 * 100))) + ')' + 9 * 9;
}
}
@@ -0,0 +1,12 @@
package com.siyeh.igfixes.style.replace_with_string;
import java.awt.*;
class Precedence {
public static String toRgbColor( final Color color) {
return new StringB<caret>uilder("rgba(").append(color.getRed()).append(',')
.append(color.getGreen()).append(',').append(color.getBlue())
.append(',').append(color.getAlpha() == 0 ? '0' : String.format("0.%2d", (int) (color.getAlpha() / 255.0 * 100)))
.append(')').append(9*9).toString();
}
}
@@ -33,4 +33,5 @@ public class StringBufferReplaceableWithStringFixTest extends IGQuickFixesTestCa
public void testStringBuilderAppend() { doTest("StringBuilderAppend", InspectionGadgetsBundle.message("string.builder.replaceable.by.string.quickfix")); }
public void testStringBufferVariable() { doTest(); }
public void testStartsWithPrimitive() { doTest(); }
public void testPrecedence() { doTest("Precedence", InspectionGadgetsBundle.message("string.builder.replaceable.by.string.quickfix")); }
}