[red-knot] fix: when simplifying union, True & False -> instance(bool) (#13644)

This commit is contained in:
Simon 2024-10-05 20:01:10 +02:00 committed by GitHub
parent 1c2cafc101
commit f1205177fd
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 29 additions and 3 deletions

View file

@ -66,7 +66,7 @@ impl<'db> UnionBuilder<'db> {
let mut to_remove = SmallVec::<[usize; 2]>::new();
for (index, element) in self.elements.iter().enumerate() {
if Some(*element) == bool_pair {
to_add = KnownClass::Bool.to_class(self.db);
to_add = KnownClass::Bool.to_instance(self.db);
to_remove.push(index);
// The type we are adding is a BooleanLiteral, which doesn't have any
// subtypes. And we just found that the union already contained our
@ -362,7 +362,7 @@ mod tests {
#[test]
fn build_union_bool() {
let db = setup_db();
let bool_ty = KnownClass::Bool.to_class(&db);
let bool_instance_ty = KnownClass::Bool.to_instance(&db);
let t0 = Type::BooleanLiteral(true);
let t1 = Type::BooleanLiteral(true);
@ -373,7 +373,7 @@ mod tests {
assert_eq!(union.elements(&db), &[t0, t3]);
let union = UnionType::from_elements(&db, [t0, t1, t2, t3]).expect_union();
assert_eq!(union.elements(&db), &[bool_ty, t3]);
assert_eq!(union.elements(&db), &[bool_instance_ty, t3]);
}
#[test]

View file

@ -4548,6 +4548,32 @@ mod tests {
Ok(())
}
#[test]
fn simplify_true_and_false_to_bool() -> anyhow::Result<()> {
let mut db = setup_db();
db.write_dedented(
"src/a.py",
"
from typing_extensions import reveal_type
def returns_bool() -> bool:
return True
if returns_bool():
x = True
else:
x = False
reveal_type(x)
",
)?;
assert_file_diagnostics(&db, "src/a.py", &["Revealed type is `bool`"]);
Ok(())
}
#[test]
fn literal_int_arithmetic() -> anyhow::Result<()> {
let mut db = setup_db();