Skip to content

Commit

Permalink
SONARJAVA-5096 S1764: FP on expressions with side-effects (#4878)
Browse files Browse the repository at this point in the history
  • Loading branch information
kaufco authored Sep 23, 2024
1 parent 8333a7d commit d709152
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package checks;

import java.util.Random;

class IdenticalOperandOnBinaryExpressionCheck {
void foo(boolean a, boolean b, boolean c, boolean e) {
if(a == b) { }
Expand Down Expand Up @@ -41,4 +43,16 @@ void fun(Object a, Object b) {
java.util.Objects.deepEquals(a, b);
java.util.Objects.isNull(a);
}

void sonarJava5096() {
Random r = new Random();
var a = r.nextBoolean() && r.nextBoolean(); // Compliant
var b = foo() - foo(); // Compliant
var c = (foo()) - (foo()); // Compliant
var d = (3 + foo() * 4) - (3 + foo() * 4); // Compliant
}

int foo() {
return 42;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ public static ExpressionTree equivalentOperand(BinaryExpressionTree tree, Expres
}

public static ExpressionTree equivalentOperand(ExpressionTree left, ExpressionTree right, Tree.Kind binaryKind) {
if (SyntacticEquivalence.areEquivalent(left, right)) {
if (SyntacticEquivalence.areEquivalent(left, right, (t1, t2) -> t1.is(Tree.Kind.METHOD_INVOCATION), false)) {
return left;
}
// Check other operands if operator is symmetric.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,8 +96,7 @@ private static boolean areEquivalent(List<? extends Tree> leftList,
return true;
}

@VisibleForTesting
static boolean areEquivalent(@Nullable Tree leftNode, @Nullable Tree rightNode, BiPredicate<JavaTree, JavaTree> overwriteEquivalence, boolean equivalenceValue) {
public static boolean areEquivalent(@Nullable Tree leftNode, @Nullable Tree rightNode, BiPredicate<JavaTree, JavaTree> overwriteEquivalence, boolean equivalenceValue) {
return areEquivalent((JavaTree) leftNode, (JavaTree) rightNode, overwriteEquivalence, equivalenceValue);
}

Expand Down

0 comments on commit d709152

Please sign in to comment.