Skip to content

Commit 3a9e93f

Browse files
SONARPY-785 Fix FP on S1764 for expressions in try/except blocks
1 parent 11aec70 commit 3a9e93f

3 files changed

Lines changed: 13 additions & 7 deletions

File tree

its/ruling/src/test/resources/expected/python-S1764.json

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,9 +46,6 @@
4646
1140,
4747
1145,
4848
],
49-
'project:numpy-1.16.4/numpy/lib/function_base.py':[
50-
2528,
51-
],
5249
'project:numpy-1.16.4/numpy/lib/nanfunctions.py':[
5350
75,
5451
],

python-checks/src/main/java/org/sonar/python/checks/IdenticalExpressionOnBinaryOperatorCheck.java

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -47,15 +47,18 @@ private static void checkBinaryExpression(SubscriptionContext ctx) {
4747
Expression leftOperand = binaryExpression.leftOperand();
4848
Expression rightOperand = binaryExpression.rightOperand();
4949
Token operator = binaryExpression.operator();
50-
if (leftOperand.is(Tree.Kind.CALL_EXPR) || TreeUtils.hasDescendant(leftOperand, t -> t.is(Tree.Kind.CALL_EXPR))) {
51-
return;
52-
}
53-
if (CheckUtils.areEquivalent(leftOperand, rightOperand) && !isLeftShiftBy1(leftOperand, operator)) {
50+
if (CheckUtils.areEquivalent(leftOperand, rightOperand) && !isLeftShiftBy1(leftOperand, operator) && !isException(leftOperand)) {
5451
ctx.addIssue(rightOperand, "Correct one of the identical sub-expressions on both sides of operator \"" + operator.value() + "\".")
5552
.secondary(leftOperand, "");
5653
}
5754
}
5855

56+
private static boolean isException(Expression leftOperand) {
57+
// Avoid raising issue if operands are function calls or within try/except blocks
58+
return leftOperand.is(Tree.Kind.CALL_EXPR) || TreeUtils.hasDescendant(leftOperand, t -> t.is(Tree.Kind.CALL_EXPR))
59+
|| TreeUtils.firstAncestorOfKind(leftOperand, Tree.Kind.TRY_STMT) != null;
60+
}
61+
5962
private static boolean isLeftShiftBy1(Expression leftOperand, Token operator) {
6063
return "<<".equals(operator.value()) && leftOperand.is(Tree.Kind.NUMERIC_LITERAL) && ((NumericLiteral) leftOperand).valueAsLong() == 1;
6164
}

python-checks/src/test/resources/checks/identicalExpressionOnBinaryOperator.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,3 +53,9 @@ def no_issues_on_function_calls():
5353
if MyClass() == MyClass(): ...
5454
my_class = MyClass()
5555
if my_class.bar() == my_class.bar(): ...
56+
57+
def no_issues_within_try_except():
58+
try:
59+
foo(c)
60+
except ValueError:
61+
return c / c

0 commit comments

Comments
 (0)