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:S1643
Issue:
S1643 reports logStatement = logStatement + val + ", " inside a loop. Write the target as this.logStatement = logStatement + val + ", " and it isn’t reported, though it’s the same field concatenated in the same loop.
StringConcatenationInLoopCheck.concatenateVariable decides the assignment appends to its target with SyntacticEquivalence.areEquivalent(variable, operand) (StringConcatenationInLoopCheck.java:130 at 8.34.0.44906, same at 8.41.0.47177). this.logStatement and logStatement aren’t syntactically equivalent, so it’s treated as assigning some unrelated value. The check already resolves the target’s symbol (to skip variables local to the loop), so comparing symbols, or stripping this. before the comparison, would catch both.
Reproducer:
seed/ConcatInLoop.java:
import java.util.Arrays;
import java.util.List;
public class ConcatInLoop {
private String logStatement = "";
public void bad() {
List<String> values = Arrays.asList("tic", "tac", "toe");
for (String val : values) {
logStatement = logStatement + val + ", "; // Noncompliant: S1643 reported
}
}
}
variant/ConcatInLoop.java:
import java.util.Arrays;
import java.util.List;
public class ConcatInLoop {
private String logStatement = "";
public void bad() {
List<String> values = Arrays.asList("tic", "tac", "toe");
for (String val : values) {
this.logStatement = logStatement + val + ", "; // same statement, no S1643
}
}
}
Expected behavior:
S1643 on the concatenation in variant/ConcatInLoop.java, as on the one in seed/ConcatInLoop.java: the loop appends to the same field.
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: S1643
--- SEED -- expected: reported (seed/)
java:S1220 line - Move this file to a named package.
java:S1643 line 10 Use a StringBuilder instead. <== S1643
[S1643: 1]
--- VARIANT -- expected: reported; actual: not reported (variant/)
java:S1220 line - Move this file to a named package.
[S1643: 0]