1616 */
1717package org .sonar .python .checks ;
1818
19- import java .util .List ;
2019import java .util .Set ;
2120import org .sonar .check .Rule ;
2221import org .sonar .plugins .python .api .PythonSubscriptionCheck ;
3231import org .sonar .plugins .python .api .tree .Tree ;
3332import org .sonar .plugins .python .api .tree .Tree .Kind ;
3433import org .sonar .plugins .python .api .tree .UnaryExpression ;
35- import org .sonar .plugins .python .api .types .BuiltinTypes ;
36- import org .sonar .plugins .python .api .types .InferredType ;
34+ import org .sonar .plugins .python .api .types .v2 . matchers . TypeMatcher ;
35+ import org .sonar .plugins .python .api .types .v2 . matchers . TypeMatchers ;
3736import org .sonar .python .quickfix .TextEditUtils ;
3837import org .sonar .python .tree .TreeUtils ;
3938
@@ -43,6 +42,9 @@ public class BooleanCheckNotInvertedCheck extends PythonSubscriptionCheck {
4342 private static final String MESSAGE = "Use the opposite operator (\" %s\" ) instead." ;
4443
4544 private static final Set <String > EQUALITY_COMPARATORS = Set .of ("==" , "!=" );
45+ private static final TypeMatcher IS_SET_OR_FROZENSET = TypeMatchers .any (
46+ TypeMatchers .isObjectInstanceOf ("builtins.set" ),
47+ TypeMatchers .isObjectInstanceOf ("builtins.frozenset" ));
4648
4749 @ Override
4850 public void initialize (Context context ) {
@@ -58,7 +60,7 @@ private static void checkNotExpression(SubscriptionContext ctx, UnaryExpression
5860 BinaryExpression binaryExp = (BinaryExpression ) negatedExpr ;
5961 // Don't raise warning with "not a == b == c" because a == b != c is not equivalent
6062 if (!binaryExp .leftOperand ().is (Kind .COMPARISON )) {
61- if (isSetComparison (binaryExp ) && !EQUALITY_COMPARATORS .contains (binaryExp .operator ().value ())) {
63+ if (isSetComparison (ctx , binaryExp ) && !EQUALITY_COMPARATORS .contains (binaryExp .operator ().value ())) {
6264 return ;
6365 }
6466 String oppositeOperator = oppositeOperator (binaryExp .operator ());
@@ -152,12 +154,8 @@ private static String getText(Tree defaultValue) {
152154 return valueBuilder .toString ();
153155 }
154156
155- private static boolean isSetComparison (BinaryExpression binaryExpression ) {
156- List <InferredType > inferredTypeSet = List .of (
157- binaryExpression .leftOperand ().type (),
158- binaryExpression .rightOperand ().type ()
159- );
160- return inferredTypeSet .stream ().anyMatch (inferredType ->
161- inferredType .mustBeOrExtend (BuiltinTypes .SET ) || inferredType .mustBeOrExtend (BuiltinTypes .FROZENSET ));
157+ private static boolean isSetComparison (SubscriptionContext ctx , BinaryExpression binaryExpression ) {
158+ return IS_SET_OR_FROZENSET .isTrueFor (binaryExpression .leftOperand (), ctx )
159+ || IS_SET_OR_FROZENSET .isTrueFor (binaryExpression .rightOperand (), ctx );
162160 }
163161}
0 commit comments