Skip to content

Commit f5bb12d

Browse files
SONARJAVA-7241: Improve S9358 to only raise when differing operands are simple and have the same type (#6402)
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
1 parent d7866af commit f5bb12d

6 files changed

Lines changed: 74 additions & 42 deletions

File tree

‎its/ruling/src/test/resources/expected/eclipse-jetty-similar-to-main/java-S9358.json‎

Lines changed: 0 additions & 9 deletions
This file was deleted.
Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,5 @@
11
{
2-
"eclipse-jetty:jetty-http/src/main/java/org/eclipse/jetty/http/QuotedQualityCSV.java": [
3-
129
4-
],
5-
"eclipse-jetty:jetty-jmx/src/main/java/org/eclipse/jetty/jmx/MBeanContainer.java": [
6-
362,
7-
373
8-
],
92
"eclipse-jetty:jetty-util/src/main/java/org/eclipse/jetty/util/JavaVersion.java": [
103
58
11-
],
12-
"eclipse-jetty:jetty-util/src/test/java/org/eclipse/jetty/util/statistic/CounterStatisticTest.java": [
13-
91
144
]
155
}

‎its/ruling/src/test/resources/expected/guava/java-S9358.json‎

Lines changed: 0 additions & 12 deletions
This file was deleted.
Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,5 @@
11
{
2-
"sonarqube-6.5:src/main/java/org/sonar/server/computation/task/projectanalysis/qualitygate/ConditionEvaluator.java": [
3-
113
4-
],
52
"sonarqube-6.5:src/main/java/org/sonar/server/qualitygate/QualityGateConditionsUpdater.java": [
63
175
7-
],
8-
"sonarqube-6.5:src/main/java/org/sonar/server/qualityprofile/RuleActivator.java": [
9-
200
10-
],
11-
"sonarqube-6.5:src/main/java/org/sonar/server/setting/ws/ValuesAction.java": [
12-
247
134
]
145
}

‎java-checks-test-sources/default/src/main/java/checks/TernaryOperatorSameOperationCheckSample.java‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,37 @@ void testNonIdentifierReceiver() {
177177
Object nir1 = condition ? getObj().foo(a) : getObj().foo(b); // Noncompliant
178178
}
179179

180+
void testComplexArguments(String value, StringBuilder buffer, int index) {
181+
String c12 = condition ? foo(value.substring(1)) : foo(value); // Compliant - method invocation as differing argument
182+
String c13 = condition ? foo(value.substring(1)) : foo(value.substring(2)); // Compliant - nested invocations
183+
Object c14 = condition ? new Thread(() -> {}) : new Thread(this::run); // Compliant - lambda and method reference
184+
Object c15 = condition ? new Foo((String) obj.toString()) : new Foo(value); // Compliant - cast
185+
Object c16 = condition ? new Foo(value + "x") : new Foo(value); // Compliant - binary expression
186+
String c17 = condition ? foo(new String("a")) : foo(value); // Compliant - object creation
187+
String[] arr = {value};
188+
String c18 = condition ? arr[index + 1] : arr[index]; // Compliant - complex index
189+
190+
String s1 = condition ? foo("abc") : foo("def"); // Noncompliant
191+
String s2 = condition ? foo(this.field) : foo(value); // Noncompliant
192+
String s3 = condition ? foo(obj.field) : foo(obj2.field); // Noncompliant
193+
String s4 = condition ? foo((value)) : foo(field); // Noncompliant
194+
Object s5 = condition ? overloaded(-1) : overloaded(index); // Noncompliant
195+
String s6 = condition ? arr[0] : arr[index]; // Noncompliant
196+
}
197+
198+
void testDifferentArgumentTypes(int primitive, Integer boxed, long longValue, Object object, String string) {
199+
Object t1 = condition ? takesLong(primitive) : takesLong(longValue); // Compliant - different argument types
200+
Object t2 = condition ? takesObject(boxed) : takesObject(primitive); // Compliant - unboxing would occur
201+
Object t3 = condition ? takesObject(string) : takesObject(object); // Compliant - different argument types
202+
Object t4 = condition ? foo(string) : foo(null); // Compliant - null literal
203+
Object t5 = condition ? takesLong(longValue) : takesLong(1L); // Noncompliant
204+
}
205+
180206
// Private methods used in ternary
207+
String field;
208+
private void run() { }
209+
private Object takesLong(long l) { return l; }
210+
private Object takesObject(Object o) { return o; }
181211
private String foo(String s) { return s; }
182212
private String foo(String s, String t) { return s + t; }
183213
private String bar(String s) { return s; }

‎java-checks/src/main/java/org/sonar/java/checks/TernaryOperatorSameOperationCheck.java‎

Lines changed: 44 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,14 +22,17 @@
2222
import org.sonar.java.model.SyntacticEquivalence;
2323
import org.sonar.plugins.java.api.IssuableSubscriptionVisitor;
2424
import org.sonar.plugins.java.api.semantic.Symbol;
25+
import org.sonar.plugins.java.api.semantic.Type;
2526
import org.sonar.plugins.java.api.tree.ArrayAccessExpressionTree;
2627
import org.sonar.plugins.java.api.tree.ConditionalExpressionTree;
2728
import org.sonar.plugins.java.api.tree.ExpressionTree;
2829
import org.sonar.plugins.java.api.tree.IdentifierTree;
30+
import org.sonar.plugins.java.api.tree.LiteralTree;
2931
import org.sonar.plugins.java.api.tree.MemberSelectExpressionTree;
3032
import org.sonar.plugins.java.api.tree.MethodInvocationTree;
3133
import org.sonar.plugins.java.api.tree.NewClassTree;
3234
import org.sonar.plugins.java.api.tree.Tree;
35+
import org.sonar.plugins.java.api.tree.UnaryExpressionTree;
3336

3437
@Rule(key = "S9358")
3538
public class TernaryOperatorSameOperationCheck extends IssuableSubscriptionVisitor {
@@ -130,16 +133,55 @@ private static boolean hasExactlyOneArgumentDifference(List<? extends Expression
130133
}
131134
int differences = 0;
132135
for (int i = 0; i < leftArgs.size(); i++) {
133-
if (!sameTree(leftArgs.get(i), rightArgs.get(i))) {
136+
ExpressionTree leftArg = leftArgs.get(i);
137+
ExpressionTree rightArg = rightArgs.get(i);
138+
if (!sameTree(leftArg, rightArg)) {
139+
if (!areInterchangeableOperands(leftArg, rightArg)) {
140+
return false;
141+
}
134142
differences++;
135143
}
136144
}
137145
return differences == 1;
138146
}
139147

140148
private static boolean sameArrayAccess(ArrayAccessExpressionTree left, ArrayAccessExpressionTree right) {
149+
ExpressionTree leftIndex = left.dimension().expression();
150+
ExpressionTree rightIndex = right.dimension().expression();
141151
return sameTree(left.expression(), right.expression())
142-
&& !sameTree(left.dimension().expression(), right.dimension().expression());
152+
&& !sameTree(leftIndex, rightIndex)
153+
&& areInterchangeableOperands(leftIndex, rightIndex);
154+
}
155+
156+
/**
157+
* The differing operands can be moved into a conditional expression only when doing so keeps the code readable
158+
* and does not alter semantics: both operands must be simple (identifiers, literals or field accesses)
159+
* and have the same type, so that the resulting conditional expression does not involve boxing, unboxing or
160+
* a different overload resolution.
161+
*/
162+
private static boolean areInterchangeableOperands(ExpressionTree left, ExpressionTree right) {
163+
return isSimpleOperand(left) && isSimpleOperand(right) && sameTypeOrUnknown(left.symbolType(), right.symbolType());
164+
}
165+
166+
private static boolean isSimpleOperand(ExpressionTree tree) {
167+
ExpressionTree expression = ExpressionUtils.skipParentheses(tree);
168+
if (expression instanceof LiteralTree || expression.is(Tree.Kind.IDENTIFIER)) {
169+
return true;
170+
}
171+
if (expression.is(Tree.Kind.UNARY_MINUS)) {
172+
return ((UnaryExpressionTree) expression).expression() instanceof LiteralTree;
173+
}
174+
if (expression.is(Tree.Kind.MEMBER_SELECT)) {
175+
return isSimpleOperand(((MemberSelectExpressionTree) expression).expression());
176+
}
177+
return false;
178+
}
179+
180+
private static boolean sameTypeOrUnknown(Type left, Type right) {
181+
if (left.isUnknown() || right.isUnknown()) {
182+
return true;
183+
}
184+
return left.equals(right);
143185
}
144186

145187
private static boolean sameTree(Tree left, Tree right) {

0 commit comments

Comments
 (0)