[red-knot] Minor simplifications to mro.rs (#14912)

This commit is contained in:
Alex Waygood 2024-12-11 13:14:12 +00:00 committed by GitHub
parent 01d16e8941
commit 1d91dae11f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -76,21 +76,14 @@ impl<'db> Mro<'db> {
// This *could* theoretically be handled by the final branch below, // This *could* theoretically be handled by the final branch below,
// but it's a common case (i.e., worth optimizing for), // but it's a common case (i.e., worth optimizing for),
// and the `c3_merge` function requires lots of allocations. // and the `c3_merge` function requires lots of allocations.
[single_base] => { [single_base] => ClassBase::try_from_ty(db, *single_base).map_or_else(
let single_base = ClassBase::try_from_ty(*single_base, db).ok_or(*single_base); || Err(MroErrorKind::InvalidBases(Box::from([(0, *single_base)]))),
single_base.map_or_else( |single_base| {
|invalid_base_ty| { Ok(std::iter::once(ClassBase::Class(class))
let bases_info = Box::from([(0, invalid_base_ty)]); .chain(single_base.mro(db))
Err(MroErrorKind::InvalidBases(bases_info)) .collect())
}, },
|single_base| { ),
let mro = std::iter::once(ClassBase::Class(class))
.chain(single_base.mro(db))
.collect();
Ok(mro)
},
)
}
// The class has multiple explicit bases. // The class has multiple explicit bases.
// //
@ -102,9 +95,9 @@ impl<'db> Mro<'db> {
let mut invalid_bases = vec![]; let mut invalid_bases = vec![];
for (i, base) in multiple_bases.iter().enumerate() { for (i, base) in multiple_bases.iter().enumerate() {
match ClassBase::try_from_ty(*base, db).ok_or(*base) { match ClassBase::try_from_ty(db, *base) {
Ok(valid_base) => valid_bases.push(valid_base), Some(valid_base) => valid_bases.push(valid_base),
Err(invalid_base) => invalid_bases.push((i, invalid_base)), None => invalid_bases.push((i, *base)),
} }
} }
@ -341,7 +334,7 @@ impl<'db> ClassBase<'db> {
/// Attempt to resolve `ty` into a `ClassBase`. /// Attempt to resolve `ty` into a `ClassBase`.
/// ///
/// Return `None` if `ty` is not an acceptable type for a class base. /// Return `None` if `ty` is not an acceptable type for a class base.
fn try_from_ty(ty: Type<'db>, db: &'db dyn Db) -> Option<Self> { fn try_from_ty(db: &'db dyn Db, ty: Type<'db>) -> Option<Self> {
match ty { match ty {
Type::Any => Some(Self::Any), Type::Any => Some(Self::Any),
Type::Unknown => Some(Self::Unknown), Type::Unknown => Some(Self::Unknown),
@ -373,7 +366,7 @@ impl<'db> ClassBase<'db> {
KnownInstanceType::Any => Some(Self::Any), KnownInstanceType::Any => Some(Self::Any),
// TODO: classes inheriting from `typing.Type` also have `Generic` in their MRO // TODO: classes inheriting from `typing.Type` also have `Generic` in their MRO
KnownInstanceType::Type => { KnownInstanceType::Type => {
ClassBase::try_from_ty(KnownClass::Type.to_class_literal(db), db) ClassBase::try_from_ty(db, KnownClass::Type.to_class_literal(db))
} }
}, },
} }