Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[red-knot] Simplify and generalize Type::is_subtype_of a little bit #15622

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 11 additions & 20 deletions crates/red_knot_python_semantic/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -964,33 +964,24 @@ impl<'db> Type<'db> {
// `Literal[str]` is a subtype of `type` because the `str` class object is an instance of its metaclass `type`.
// `Literal[abc.ABC]` is a subtype of `abc.ABCMeta` because the `abc.ABC` class object
// is an instance of its metaclass `abc.ABCMeta`.
(
Type::ClassLiteral(ClassLiteralType { class: self_class }),
Type::Instance(InstanceType {
class: target_class,
}),
) => self_class.is_instance_of(db, target_class),
(Type::ClassLiteral(ClassLiteralType { class }), _) => class
.metaclass(db)
.to_instance(db)
.is_subtype_of(db, target),

// `type[str]` (== `SubclassOf("str")` in red-knot) describes all possible runtime subclasses
// of the class object `str`. It is a subtype of `type` (== `Instance("type")`) because `str`
// is an instance of `type`, and so all possible subclasses of `str` will also be instances of `type`.
//
// Similarly `type[enum.Enum]` is a subtype of `enum.EnumMeta` because `enum.Enum`
// is an instance of `enum.EnumMeta`.
(
Type::SubclassOf(subclass_of_ty),
Type::Instance(InstanceType {
class: target_class,
}),
) => subclass_of_ty
.subclass_of()
.into_class()
.is_some_and(|subclass_class| subclass_class.is_instance_of(db, target_class)),

// Other than the cases enumerated above, `type[]` and class-literal types just delegate to `Instance("type")`
(Type::SubclassOf(_) | Type::ClassLiteral(_), _) => {
KnownClass::Type.to_instance(db).is_subtype_of(db, target)
}
(Type::SubclassOf(subclass_of_ty), _) => match subclass_of_ty.subclass_of() {
ClassBase::Class(class) => class
.metaclass(db)
.to_instance(db)
.is_subtype_of(db, target),
ClassBase::Dynamic(_) => KnownClass::Type.to_instance(db).is_subtype_of(db, target),
},

// For example: `Type::KnownInstance(KnownInstanceType::Type)` is a subtype of `Type::Instance(_SpecialForm)`,
// because `Type::KnownInstance(KnownInstanceType::Type)` is a set with exactly one runtime value in it
Expand Down
Loading