19
19
*/
20
20
package org .sonar .python .checks ;
21
21
22
- import java .util .Arrays ;
23
- import java .util .HashSet ;
24
22
import java .util .List ;
25
- import java .util .Set ;
26
23
import org .sonar .check .Rule ;
27
24
import org .sonar .plugins .python .api .PythonSubscriptionCheck ;
28
- import org .sonar .plugins .python .api .symbols .Symbol ;
29
25
import org .sonar .plugins .python .api .tree .Expression ;
30
- import org .sonar .plugins .python .api .tree .Name ;
31
26
import org .sonar .plugins .python .api .tree .RaiseStatement ;
32
27
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 ;
34
30
35
31
import static org .sonar .plugins .python .api .types .BuiltinTypes .BASE_EXCEPTION ;
36
32
import static org .sonar .plugins .python .api .types .BuiltinTypes .EXCEPTION ;
37
33
38
34
@ Rule (key = "S112" )
39
35
public class GenericExceptionRaisedCheck extends PythonSubscriptionCheck {
40
36
41
- private static final Set <String > GENERIC_EXCEPTION_NAMES = new HashSet <>(Arrays .asList (EXCEPTION , BASE_EXCEPTION ));
42
-
43
37
@ Override
44
38
public void initialize (Context context ) {
45
39
context .registerSyntaxNodeConsumer (Kind .RAISE_STMT , ctx -> {
@@ -49,19 +43,12 @@ public void initialize(Context context) {
49
43
return ;
50
44
}
51
45
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 ) {
54
50
ctx .addIssue (expression , "Replace this generic exception class with a more specific one." );
55
51
}
56
52
});
57
53
}
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
-
67
54
}
0 commit comments