Skip to content

Commit

Permalink
SONARJAVA-5216 S1871 Consider variable identity when testing branch e…
Browse files Browse the repository at this point in the history
…quivalence. (#4935)
  • Loading branch information
tomasz-tylenda-sonarsource authored Dec 2, 2024
1 parent 17e0e36 commit a8c1c27
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -216,4 +216,35 @@ private void f() {
private void f(int i) {
}

static class Parent {};
static class A extends Parent {};
static class B extends Parent {};

// Edge case involving variables introduced with `instanceof`.
// See: https://community.sonarsource.com/t/fp-java-s1871-branch-code-block-is-the-same/130645
void variablesBoundInInstanceOf() {
Parent p1 = new A();
Parent p2 = new B();
if(Math.random() < 0.5) {
p1 = new B();
p2 = new A();
}

// No problem when `a` refers to different variables.
Parent p = null;
if (p1 instanceof A a) {
p = a;
}
else if (p2 instanceof A a) {
p = a;
}

// Variables have different names and identities.
if (p1 instanceof A a1) {
p = a1;
}
else if (p2 instanceof A a2) {
p = a2;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ private static IfElseChain collectIdenticalBranches(List<StatementTree> allBranc
for (int j = i + 1; j < allBranches.size(); j++) {
StatementTree statement1 = allBranches.get(i);
StatementTree statement2 = allBranches.get(j);
if (SyntacticEquivalence.areEquivalent(statement1, statement2)) {
if (SyntacticEquivalence.areEquivalentIncludingSameVariables(statement1, statement2)) {
duplicates.add(statement2);
ifElseChain.branches.computeIfAbsent(statement1, k -> new HashSet<>()).add(statement2);
}
Expand Down

0 comments on commit a8c1c27

Please sign in to comment.