Product/version: SonarQube Community Build 26.9.0.129388 (sonar-java 8.41.0.47177), sonar-scanner 8.1.0.6389
Language: Java
Rule: java:S1854
Issue:
S1854 reports int x = compute(); x = 3; System.out.println(x); in a method body. The same three statements inside a lambda that’s run right away aren’t reported, but inside an anonymous Runnable they are (control/DeadStoreAnonymous.java).
In DeadStoreCheck the liveness analysis runs over the enclosing method’s CFG, and a lambda only contributes the variables it uses (getUsedLocalVarInSubTree(lambda.body())), so stores inside the lambda are never candidates.
Reproducer:
seed/DeadStoreSeed.java:
class DeadStoreSeed {
void run() {
int x = compute(); // Noncompliant: S1854 reported, overwritten before use
x = 3;
System.out.println(x);
}
private int compute() { return 1; }
}
variant/DeadStoreVariant.java:
class DeadStoreVariant {
void run() {
Runnable r = () -> {
int x = compute(); // same dead store, now inside a lambda body: no S1854
x = 3;
System.out.println(x);
};
r.run();
}
private int compute() { return 1; }
}
control/DeadStoreAnonymous.java:
class DeadStoreAnonymous {
void run() {
Runnable r = new Runnable() {
public void run() {
int x = compute(); // same statements in an anonymous class: S1854 reported
x = 3;
System.out.println(x);
}
};
r.run();
}
private int compute() { return 1; }
}
Expected behavior:
S1854 on int x = compute(); inside the lambda in DeadStoreVariant.run(), as in DeadStoreSeed.run().
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: S1854
--- SEED -- expected: reported (seed/)
java:S1220 line - Move this file to a named package.
java:S1854 line 3 Remove this useless assignment to local variable "x". <== S1854
java:S106 line 5 Replace this use of System.out by a logger.
java:S3400 line 7 Remove this method and declare a constant for this value.
[S1854: 1]
--- VARIANT -- expected: reported; actual: not reported (variant/)
java:S1220 line - Move this file to a named package.
java:S106 line 6 Replace this use of System.out by a logger.
java:S3400 line 10 Remove this method and declare a constant for this value.
[S1854: 0]
--- CONTROL -- the same rule on the control file, expected: reported (control/)
java:S1220 line - Move this file to a named package.
java:S9357 line 3 Make this anonymous inner class a lambda (sonar.java.source
java:S1604 line 3 Make this anonymous inner class a lambda (sonar.java.source
java:S1854 line 5 Remove this useless assignment to local variable "x". <== S1854
java:S106 line 7 Replace this use of System.out by a logger.
java:S3400 line 12 Remove this method and declare a constant for this value.
[S1854: 1]