[red-knot] Fix is_assignable_to for unions (#14196)

## Summary

Fix `Type::is_assignable_to` for union types on the left hand side (of
`.is_assignable_to`; or the right hand side of the `… = …` assignment):

`Literal[1, 2]` should be assignable to `int`.

## Test Plan

New unit tests that were previously failing.
This commit is contained in:
David Peter 2024-11-08 10:53:48 +01:00 committed by GitHub
parent d1ef418bb0
commit fed35a25e8
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -626,6 +626,10 @@ impl<'db> Type<'db> {
match (self, target) {
(Type::Unknown | Type::Any | Type::Todo, _) => true,
(_, Type::Unknown | Type::Any | Type::Todo) => true,
(Type::Union(union), ty) => union
.elements(db)
.iter()
.all(|&elem_ty| elem_ty.is_assignable_to(db, ty)),
(ty, Type::Union(union)) => union
.elements(db)
.iter()
@ -2765,6 +2769,14 @@ mod tests {
#[test_case(Ty::IntLiteral(1), Ty::Union(vec![Ty::BuiltinInstance("int"), Ty::BuiltinInstance("str")]))]
#[test_case(Ty::IntLiteral(1), Ty::Union(vec![Ty::Unknown, Ty::BuiltinInstance("str")]))]
#[test_case(Ty::Union(vec![Ty::IntLiteral(1), Ty::IntLiteral(2)]), Ty::Union(vec![Ty::IntLiteral(1), Ty::IntLiteral(2)]))]
#[test_case(
Ty::Union(vec![Ty::IntLiteral(1), Ty::IntLiteral(2)]),
Ty::BuiltinInstance("int")
)]
#[test_case(
Ty::Union(vec![Ty::IntLiteral(1), Ty::None]),
Ty::Union(vec![Ty::BuiltinInstance("int"), Ty::None])
)]
#[test_case(Ty::Tuple(vec![Ty::Todo]), Ty::Tuple(vec![Ty::IntLiteral(2)]))]
#[test_case(Ty::Tuple(vec![Ty::IntLiteral(2)]), Ty::Tuple(vec![Ty::Todo]))]
fn is_assignable_to(from: Ty, to: Ty) {
@ -2776,6 +2788,14 @@ mod tests {
#[test_case(Ty::IntLiteral(1), Ty::BuiltinInstance("str"))]
#[test_case(Ty::BuiltinInstance("int"), Ty::BuiltinInstance("str"))]
#[test_case(Ty::BuiltinInstance("int"), Ty::IntLiteral(1))]
#[test_case(
Ty::Union(vec![Ty::IntLiteral(1), Ty::None]),
Ty::BuiltinInstance("int")
)]
#[test_case(
Ty::Union(vec![Ty::IntLiteral(1), Ty::None]),
Ty::Union(vec![Ty::BuiltinInstance("str"), Ty::None])
)]
fn is_not_assignable_to(from: Ty, to: Ty) {
let db = setup_db();
assert!(!from.into_type(&db).is_assignable_to(&db, to.into_type(&db)));