Skip to content

Commit e2d6475

Browse files
SONARPY-2114 Migrate S5707 ExceptionCauseTypeCheck to the V2 type model
1 parent 61347bd commit e2d6475

File tree

1 file changed

+6
-12
lines changed

1 file changed

+6
-12
lines changed

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

Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -29,11 +29,8 @@
2929
import org.sonar.plugins.python.api.tree.QualifiedExpression;
3030
import org.sonar.plugins.python.api.tree.RaiseStatement;
3131
import org.sonar.plugins.python.api.tree.Tree.Kind;
32-
import org.sonar.plugins.python.api.types.InferredType;
33-
34-
import static org.sonar.plugins.python.api.types.BuiltinTypes.BASE_EXCEPTION;
35-
import static org.sonar.plugins.python.api.types.BuiltinTypes.NONE_TYPE;
36-
import static org.sonar.plugins.python.api.types.BuiltinTypes.STR;
32+
import org.sonar.python.types.v2.PythonType;
33+
import org.sonar.python.types.v2.TriBool;
3734

3835
@Rule(key = "S5707")
3936
public class ExceptionCauseTypeCheck extends PythonSubscriptionCheck {
@@ -62,13 +59,10 @@ private static void check(@Nullable Expression cause, SubscriptionContext ctx) {
6259
if (cause == null) {
6360
return;
6461
}
65-
InferredType causeType = cause.type();
66-
if (causeType.canBeOrExtend("type")) {
67-
// SONARPY-1666: Here we should only exclude type objects that represent Exception types
68-
return;
69-
}
70-
// TODO remove the test against str once type inference knows the complete hierarchy of str
71-
if ((!causeType.canBeOrExtend(BASE_EXCEPTION) && !causeType.canOnlyBe(NONE_TYPE)) || causeType.canOnlyBe(STR)) {
62+
PythonType causeType = cause.typeV2();
63+
TriBool inheritsFromBaseException = ctx.typeChecker().typeCheckBuilder().isInstanceOf("BaseException").check(causeType);
64+
TriBool isNoneType = ctx.typeChecker().typeCheckBuilder().isBuiltinWithName("NoneType").check(causeType);
65+
if (inheritsFromBaseException == TriBool.FALSE && isNoneType == TriBool.FALSE) {
7266
ctx.addIssue(cause, "Replace this expression with an exception or None");
7367
}
7468
}

0 commit comments

Comments
 (0)