Skip to content

Commit 5c3c0c4

Browse files
authored
[red-knot] Inference for comparison of union types (#13781)
## Summary Add type inference for comparisons involving union types. For example: ```py one_or_two = 1 if flag else 2 reveal_type(one_or_two <= 2) # revealed: Literal[True] reveal_type(one_or_two <= 1) # revealed: bool reveal_type(one_or_two <= 0) # revealed: Literal[False] ``` closes #13779 ## Test Plan See `resources/mdtest/comparison/unions.md`
1 parent 6b7a738 commit 5c3c0c4

File tree

4 files changed

+108
-2
lines changed

4 files changed

+108
-2
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
# Comparison: Unions
2+
3+
## Union on one side of the comparison
4+
5+
Comparisons on union types need to consider all possible cases:
6+
7+
```py
8+
one_or_two = 1 if flag else 2
9+
10+
reveal_type(one_or_two <= 2) # revealed: Literal[True]
11+
reveal_type(one_or_two <= 1) # revealed: bool
12+
reveal_type(one_or_two <= 0) # revealed: Literal[False]
13+
14+
reveal_type(2 >= one_or_two) # revealed: Literal[True]
15+
reveal_type(1 >= one_or_two) # revealed: bool
16+
reveal_type(0 >= one_or_two) # revealed: Literal[False]
17+
18+
reveal_type(one_or_two < 1) # revealed: Literal[False]
19+
reveal_type(one_or_two < 2) # revealed: bool
20+
reveal_type(one_or_two < 3) # revealed: Literal[True]
21+
22+
reveal_type(one_or_two > 0) # revealed: Literal[True]
23+
reveal_type(one_or_two > 1) # revealed: bool
24+
reveal_type(one_or_two > 2) # revealed: Literal[False]
25+
26+
reveal_type(one_or_two == 3) # revealed: Literal[False]
27+
reveal_type(one_or_two == 1) # revealed: bool
28+
29+
reveal_type(one_or_two != 3) # revealed: Literal[True]
30+
reveal_type(one_or_two != 1) # revealed: bool
31+
32+
a_or_ab = "a" if flag else "ab"
33+
34+
reveal_type(a_or_ab in "ab") # revealed: Literal[True]
35+
reveal_type("a" in a_or_ab) # revealed: Literal[True]
36+
37+
reveal_type("c" not in a_or_ab) # revealed: Literal[True]
38+
reveal_type("a" not in a_or_ab) # revealed: Literal[False]
39+
40+
reveal_type("b" in a_or_ab) # revealed: bool
41+
reveal_type("b" not in a_or_ab) # revealed: bool
42+
43+
one_or_none = 1 if flag else None
44+
45+
reveal_type(one_or_none is None) # revealed: bool
46+
reveal_type(one_or_none is not None) # revealed: bool
47+
```
48+
49+
## Union on both sides of the comparison
50+
51+
With unions on both sides, we need to consider the full cross product of
52+
options when building the resulting (union) type:
53+
54+
```py
55+
small = 1 if flag_s else 2
56+
large = 2 if flag_l else 3
57+
58+
reveal_type(small <= large) # revealed: Literal[True]
59+
reveal_type(small >= large) # revealed: bool
60+
61+
reveal_type(small < large) # revealed: bool
62+
reveal_type(small > large) # revealed: Literal[False]
63+
```
64+
65+
## Unsupported operations
66+
67+
Make sure we emit a diagnostic if *any* of the possible comparisons is
68+
unsupported. For now, we fall back to `bool` for the result type instead of
69+
trying to infer something more precise from the other (supported) variants:
70+
71+
```py
72+
x = [1, 2] if flag else 1
73+
74+
result = 1 in x # error: "Operator `in` is not supported"
75+
reveal_type(result) # revealed: bool
76+
```

crates/red_knot_python_semantic/src/types.rs

+5
Original file line numberDiff line numberDiff line change
@@ -415,6 +415,11 @@ impl<'db> Type<'db> {
415415
(_, Type::Unknown | Type::Any | Type::Todo) => false,
416416
(Type::Never, _) => true,
417417
(_, Type::Never) => false,
418+
(Type::BooleanLiteral(_), Type::Instance(class))
419+
if class.is_known(db, KnownClass::Bool) =>
420+
{
421+
true
422+
}
418423
(Type::IntLiteral(_), Type::Instance(class)) if class.is_known(db, KnownClass::Int) => {
419424
true
420425
}

crates/red_knot_python_semantic/src/types/builder.rs

+6
Original file line numberDiff line numberDiff line change
@@ -374,6 +374,12 @@ mod tests {
374374

375375
let union = UnionType::from_elements(&db, [t0, t1, t2, t3]).expect_union();
376376
assert_eq!(union.elements(&db), &[bool_instance_ty, t3]);
377+
378+
let result_ty = UnionType::from_elements(&db, [bool_instance_ty, t0]);
379+
assert_eq!(result_ty, bool_instance_ty);
380+
381+
let result_ty = UnionType::from_elements(&db, [t0, bool_instance_ty]);
382+
assert_eq!(result_ty, bool_instance_ty);
377383
}
378384

379385
#[test]

crates/red_knot_python_semantic/src/types/infer.rs

+21-2
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ use crate::types::{
5757
};
5858
use crate::Db;
5959

60-
use super::KnownClass;
60+
use super::{KnownClass, UnionBuilder};
6161

6262
/// Infer all types for a [`ScopeId`], including all definitions and expressions in that scope.
6363
/// Use when checking a scope, or needing to provide a type for an arbitrary expression in the
@@ -2711,6 +2711,21 @@ impl<'db> TypeInferenceBuilder<'db> {
27112711
// - `[ast::CompOp::Is]`: return `false` if unequal, `bool` if equal
27122712
// - `[ast::CompOp::IsNot]`: return `true` if unequal, `bool` if equal
27132713
match (left, right) {
2714+
(Type::Union(union), other) => {
2715+
let mut builder = UnionBuilder::new(self.db);
2716+
for element in union.elements(self.db) {
2717+
builder = builder.add(self.infer_binary_type_comparison(*element, op, other)?);
2718+
}
2719+
Some(builder.build())
2720+
}
2721+
(other, Type::Union(union)) => {
2722+
let mut builder = UnionBuilder::new(self.db);
2723+
for element in union.elements(self.db) {
2724+
builder = builder.add(self.infer_binary_type_comparison(other, op, *element)?);
2725+
}
2726+
Some(builder.build())
2727+
}
2728+
27142729
(Type::IntLiteral(n), Type::IntLiteral(m)) => match op {
27152730
ast::CmpOp::Eq => Some(Type::BooleanLiteral(n == m)),
27162731
ast::CmpOp::NotEq => Some(Type::BooleanLiteral(n != m)),
@@ -2902,6 +2917,7 @@ impl<'db> TypeInferenceBuilder<'db> {
29022917
}
29032918
}
29042919
}
2920+
29052921
// Lookup the rich comparison `__dunder__` methods on instances
29062922
(Type::Instance(left_class_ty), Type::Instance(right_class_ty)) => match op {
29072923
ast::CmpOp::Lt => {
@@ -2911,7 +2927,10 @@ impl<'db> TypeInferenceBuilder<'db> {
29112927
_ => Some(Type::Todo),
29122928
},
29132929
// TODO: handle more types
2914-
_ => Some(Type::Todo),
2930+
_ => match op {
2931+
ast::CmpOp::Is | ast::CmpOp::IsNot => Some(KnownClass::Bool.to_instance(self.db)),
2932+
_ => Some(Type::Todo),
2933+
},
29152934
}
29162935
}
29172936

0 commit comments

Comments
 (0)