[red-knot] implement attribute of union (#12601)

I hit this `todo!` trying to run type inference over some real modules.
Since it's a one-liner to implement it, I just did that rather than
changing to `Type::Unknown`.
This commit is contained in:
Carl Meyer 2024-07-31 19:45:24 -07:00 committed by GitHub
parent d774a3bd48
commit ee0518e8f7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 31 additions and 6 deletions

View file

@ -157,12 +157,15 @@ impl<'db> Type<'db> {
// TODO MRO? get_own_instance_member, get_instance_member // TODO MRO? get_own_instance_member, get_instance_member
todo!("attribute lookup on Instance type") todo!("attribute lookup on Instance type")
} }
Type::Union(_) => { Type::Union(union) => Type::Union(
// TODO perform the get_member on each type in the union union
// TODO return the union of those results .elements(db)
// TODO if any of those results is `None` then include Unknown in the result union .iter()
todo!("attribute lookup on Union type") .fold(UnionTypeBuilder::new(db), |builder, element_ty| {
} builder.add(element_ty.member(db, name))
})
.build(),
),
Type::Intersection(_) => { Type::Intersection(_) => {
// TODO perform the get_member on each type in the intersection // TODO perform the get_member on each type in the intersection
// TODO return the intersection of those results // TODO return the intersection of those results

View file

@ -2238,6 +2238,28 @@ mod tests {
Ok(()) Ok(())
} }
#[test]
fn attribute_of_union() -> anyhow::Result<()> {
let mut db = setup_db();
db.write_dedented(
"/src/a.py",
"
if flag:
class C:
x = 1
else:
class C:
x = 2
y = C.x
",
)?;
assert_public_ty(&db, "/src/a.py", "y", "Literal[1, 2]");
Ok(())
}
fn first_public_def<'db>(db: &'db TestDb, file: File, name: &str) -> Definition<'db> { fn first_public_def<'db>(db: &'db TestDb, file: File, name: &str) -> Definition<'db> {
let scope = global_scope(db, file); let scope = global_scope(db, file);
*use_def_map(db, scope) *use_def_map(db, scope)