Skip to content

Commit 723f0eb

Browse files
SONARPY-1935 Migrate rule S112 GenericExceptionRaised to typeV2 (#1868)
1 parent 1dc4218 commit 723f0eb

File tree

1 file changed

+6
-19
lines changed

1 file changed

+6
-19
lines changed

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

Lines changed: 6 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -19,27 +19,21 @@
1919
*/
2020
package org.sonar.python.checks;
2121

22-
import java.util.Arrays;
23-
import java.util.HashSet;
2422
import java.util.List;
25-
import java.util.Set;
2623
import org.sonar.check.Rule;
2724
import org.sonar.plugins.python.api.PythonSubscriptionCheck;
28-
import org.sonar.plugins.python.api.symbols.Symbol;
2925
import org.sonar.plugins.python.api.tree.Expression;
30-
import org.sonar.plugins.python.api.tree.Name;
3126
import org.sonar.plugins.python.api.tree.RaiseStatement;
3227
import org.sonar.plugins.python.api.tree.Tree.Kind;
33-
import org.sonar.plugins.python.api.types.InferredType;
28+
import org.sonar.python.types.v2.PythonType;
29+
import org.sonar.python.types.v2.TriBool;
3430

3531
import static org.sonar.plugins.python.api.types.BuiltinTypes.BASE_EXCEPTION;
3632
import static org.sonar.plugins.python.api.types.BuiltinTypes.EXCEPTION;
3733

3834
@Rule(key = "S112")
3935
public class GenericExceptionRaisedCheck extends PythonSubscriptionCheck {
4036

41-
private static final Set<String> GENERIC_EXCEPTION_NAMES = new HashSet<>(Arrays.asList(EXCEPTION, BASE_EXCEPTION));
42-
4337
@Override
4438
public void initialize(Context context) {
4539
context.registerSyntaxNodeConsumer(Kind.RAISE_STMT, ctx -> {
@@ -49,19 +43,12 @@ public void initialize(Context context) {
4943
return;
5044
}
5145
Expression expression = expressions.get(0);
52-
InferredType type = expression.type();
53-
if (GENERIC_EXCEPTION_NAMES.stream().anyMatch(type::canOnlyBe) || isGenericExceptionClass(expression)) {
46+
PythonType pythonType = expression.typeV2();
47+
TriBool isException = ctx.typeChecker().typeCheckBuilder().isBuiltinWithName(EXCEPTION).check(pythonType);
48+
TriBool isBaseException = ctx.typeChecker().typeCheckBuilder().isBuiltinWithName(BASE_EXCEPTION).check(pythonType);
49+
if (isException == TriBool.TRUE || isBaseException == TriBool.TRUE) {
5450
ctx.addIssue(expression, "Replace this generic exception class with a more specific one.");
5551
}
5652
});
5753
}
58-
59-
private static boolean isGenericExceptionClass(Expression expression) {
60-
if (expression.is(Kind.NAME)) {
61-
Symbol symbol = ((Name) expression).symbol();
62-
return symbol != null && GENERIC_EXCEPTION_NAMES.contains(symbol.fullyQualifiedName());
63-
}
64-
return false;
65-
}
66-
6754
}

0 commit comments

Comments
 (0)