Product/version: SonarQube Community Build 26.9.0.129388 (sonar-java 8.41.0.47177); also 26.7.0.124771 (sonar-java 8.34.0.44906), sonar-scanner 8.1.0.6389
Language: Java
Rule: java:S1121
Issue:
The Exceptions section of the description says: “This rule ignores assignments in conditions of while statements and assignments enclosed in relational expressions.” (a = b) != 0 in seed/Asg.java isn’t reported. (a += b) != 0 in variant/Asg.java is, but a compound assignment is an assignment expression too (JLS 15.26), in the same relational expression.
The check only applies the exception to =. AssignmentInSubExpressionCheck.getInnerAssignmentExpression accepts Kind.ASSIGNMENT and nothing else (AssignmentInSubExpressionCheck.java:115-121 at 8.34.0.44906, same on master). The check’s own sample has if ((a += b) > 0) as Noncompliant (AssignmentInSubExpressionCheckSample.java:71), while the while exception does cover while ((a += 0) > 42) (line 62).
The earlier forum thread (t/62665, 2022-05) says the relational expression has to be the direct parent, but nothing about the assignment having to be a simple one. So either the description should say “simple assignments (=) enclosed in relational expressions”, or compound forms should be exempt too, like they are in while conditions.
Reproducer:
seed/Asg.java:
public class Asg {
int f(int a, int b) {
if ((a = b) != 0) { // no S1121: the documented exception
return a;
}
return 0;
}
}
variant/Asg.java:
public class Asg {
int f(int a, int b) {
if ((a += b) != 0) { // S1121 reported
return a;
}
return 0;
}
}
Expected behavior:
Either no S1121 on (a += b) != 0 in variant/Asg.java, as on (a = b) != 0 in seed/Asg.java, or a description whose exception names the simple assignment.
How to reproduce:
# one project per file
sonar-scanner -Dsonar.projectKey=<key> -Dsonar.sources=. \
-Dsonar.java.binaries=. -Dsonar.scm.disabled=true
Output of the commands above:
### SonarQube Community Build 26.9.0.129388 (sonar-java 8.41.0.47177), server reports 26.9.0.129388, default Sonar way profile rule: S1121
--- SEED -- expected by the description: not reported (the documented exception); actual: not reported (seed/)
java:S1220 line - Move this file to a named package.
java:S1226 line 3 Introduce a new variable instead of reusing the parameter "a
[S1121: 0]
--- VARIANT -- expected by the description: not reported (a compound assignment enclosed in the same relational expression); actual: java:S1121 reported (variant/)
java:S1220 line - Move this file to a named package.
java:S1121 line 3 Extract the assignment out of this expression. <== S1121
[S1121: 1]