Skip to content

Commit

Permalink
Short circuit on unsupported operations
Browse files Browse the repository at this point in the history
  • Loading branch information
sharkdp committed Oct 17, 2024
1 parent 28b985e commit 59387bb
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 15 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,16 @@ reveal_type(small > large) # revealed: Literal[False]
reveal_type(small >= large) # revealed: Literal[False] | bool
reveal_type(small < large) # revealed: Literal[True] | bool
```

## Unsupported operations

Make sure we emit a diagnostic if *any* of the possible comparisons is
unsupported. For now, we fall back to `bool` for the result type instead of
trying to infer something more precise from the other (supported) variants:

```py
x = [1, 2] if flag else 1

result = 1 in x # error: "Operator `in` is not supported"
reveal_type(result) # revealed: bool
```
32 changes: 17 additions & 15 deletions crates/red_knot_python_semantic/src/types/infer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ use crate::types::{
};
use crate::Db;

use super::KnownClass;
use super::{KnownClass, UnionBuilder};

/// Infer all types for a [`ScopeId`], including all definitions and expressions in that scope.
/// Use when checking a scope, or needing to provide a type for an arbitrary expression in the
Expand Down Expand Up @@ -2700,6 +2700,8 @@ impl<'db> TypeInferenceBuilder<'db> {
)
}

/// Build a union type from all results
/// Infers the type of a binary comparison (e.g. 'left == right'). See
/// `infer_compare_expression` for the higher level logic dealing with multi-comparison
/// expressions.
Expand All @@ -2717,20 +2719,20 @@ impl<'db> TypeInferenceBuilder<'db> {
// - `[ast::CompOp::Is]`: return `false` if unequal, `bool` if equal
// - `[ast::CompOp::IsNot]`: return `true` if unequal, `bool` if equal
match (left, right) {
(Type::Union(union), other) => Some(UnionType::from_elements(
self.db,
union
.elements(self.db)
.iter()
.filter_map(|element| self.infer_binary_type_comparison(*element, op, other)),
)),
(other, Type::Union(union)) => Some(UnionType::from_elements(
self.db,
union
.elements(self.db)
.iter()
.filter_map(|element| self.infer_binary_type_comparison(other, op, *element)),
)),
(Type::Union(union), other) => {
let mut builder = UnionBuilder::new(self.db);
for element in union.elements(self.db) {
builder = builder.add(self.infer_binary_type_comparison(*element, op, other)?);
}
Some(builder.build())
}
(other, Type::Union(union)) => {
let mut builder = UnionBuilder::new(self.db);
for element in union.elements(self.db) {
builder = builder.add(self.infer_binary_type_comparison(other, op, *element)?);
}
Some(builder.build())
}

(Type::IntLiteral(n), Type::IntLiteral(m)) => match op {
ast::CmpOp::Eq => Some(Type::BooleanLiteral(n == m)),
Expand Down

0 comments on commit 59387bb

Please sign in to comment.