[ty] Support type[…] and Type[…] in implicit type aliases (#21421)

## Summary

Support `type[…]` in implicit type aliases, for example:
```py
SubclassOfInt = type[int]

reveal_type(SubclassOfInt)  # GenericAlias

def _(subclass_of_int: SubclassOfInt):
    reveal_type(subclass_of_int)  # type[int]
```

part of https://github.com/astral-sh/ty/issues/221

## Typing conformance

```diff
-specialtypes_type.py:138:5: error[type-assertion-failure] Argument does not have asserted type `type[Any]`
-specialtypes_type.py:140:5: error[type-assertion-failure] Argument does not have asserted type `type[Any]`
```

Two new tests passing ✔️ 

```diff
-specialtypes_type.py:146:1: error[unresolved-attribute] Object of type `GenericAlias` has no attribute `unknown`
```

An `TA4.unknown` attribute on a PEP 613 alias (`TA4: TypeAlias =
type[Any]`) is being accessed, and the conformance suite expects this to
be an error. Since we currently use the inferred type for these type
aliases (and possibly in the future as well), we treat this as a direct
access of the attribute on `type[Any]`, which falls back to an access on
`Any` itself, which succeeds. 🔴

```
+specialtypes_type.py:152:16: error[invalid-type-form] `typing.TypeVar` is not a generic class
+specialtypes_type.py:156:16: error[invalid-type-form] `typing.TypeVar` is not a generic class
```

New errors because we don't handle `T = TypeVar("T"); MyType = type[T];
MyType[T]` yet. Support for this is being tracked in
https://github.com/astral-sh/ty/issues/221 🔴

## Ecosystem impact

Looks mostly good, a few known problems. 

## Test Plan

New Markdown tests
This commit is contained in:
David Peter
2025-11-13 19:02:24 +01:00
committed by GitHub
parent f9cc26aa12
commit 9e80e5a3a6
6 changed files with 207 additions and 8 deletions

View File

@@ -6607,6 +6607,17 @@ impl<'db> Type<'db> {
.inner(db)
.in_type_expression(db, scope_id, typevar_binding_context)?)
}
KnownInstanceType::TypeGenericAlias(ty) => {
// When `type[…]` appears in a value position (e.g. in an implicit type alias),
// we infer its argument as a type expression. This ensures that we can emit
// diagnostics for invalid type expressions, and more importantly, that we can
// make use of stringified annotations. The drawback is that we need to turn
// instances back into the corresponding subclass-of types here. This process
// (`int` -> instance of `int` -> subclass of `int`) can be lossy, but it is
// okay for all valid arguments to `type[…]`.
Ok(ty.inner(db).to_meta_type(db))
}
},
Type::SpecialForm(special_form) => match special_form {
@@ -7847,6 +7858,9 @@ pub enum KnownInstanceType<'db> {
/// A single instance of `typing.Annotated`
Annotated(InternedType<'db>),
/// An instance of `typing.GenericAlias` representing a `type[...]` expression.
TypeGenericAlias(InternedType<'db>),
/// An identity callable created with `typing.NewType(name, base)`, which behaves like a
/// subtype of `base` in type expressions. See the `struct NewType` payload for an example.
NewType(NewType<'db>),
@@ -7881,7 +7895,9 @@ fn walk_known_instance_type<'db, V: visitor::TypeVisitor<'db> + ?Sized>(
visitor.visit_type(db, *element);
}
}
KnownInstanceType::Literal(ty) | KnownInstanceType::Annotated(ty) => {
KnownInstanceType::Literal(ty)
| KnownInstanceType::Annotated(ty)
| KnownInstanceType::TypeGenericAlias(ty) => {
visitor.visit_type(db, ty.inner(db));
}
KnownInstanceType::NewType(newtype) => {
@@ -7928,6 +7944,7 @@ impl<'db> KnownInstanceType<'db> {
Self::UnionType(list) => Self::UnionType(list.normalized_impl(db, visitor)),
Self::Literal(ty) => Self::Literal(ty.normalized_impl(db, visitor)),
Self::Annotated(ty) => Self::Annotated(ty.normalized_impl(db, visitor)),
Self::TypeGenericAlias(ty) => Self::TypeGenericAlias(ty.normalized_impl(db, visitor)),
Self::NewType(newtype) => Self::NewType(
newtype
.map_base_class_type(db, |class_type| class_type.normalized_impl(db, visitor)),
@@ -7950,8 +7967,9 @@ impl<'db> KnownInstanceType<'db> {
Self::Field(_) => KnownClass::Field,
Self::ConstraintSet(_) => KnownClass::ConstraintSet,
Self::UnionType(_) => KnownClass::UnionType,
Self::Literal(_) => KnownClass::GenericAlias,
Self::Annotated(_) => KnownClass::GenericAlias,
Self::Literal(_) | Self::Annotated(_) | Self::TypeGenericAlias(_) => {
KnownClass::GenericAlias
}
Self::NewType(_) => KnownClass::NewType,
}
}
@@ -8037,6 +8055,7 @@ impl<'db> KnownInstanceType<'db> {
KnownInstanceType::Annotated(_) => {
f.write_str("<typing.Annotated special form>")
}
KnownInstanceType::TypeGenericAlias(_) => f.write_str("GenericAlias"),
KnownInstanceType::NewType(declaration) => {
write!(f, "<NewType pseudo-class '{}'>", declaration.name(self.db))
}

View File

@@ -180,6 +180,9 @@ impl<'db> ClassBase<'db> {
// wrappers are just identity callables at runtime, so this sort of inheritance
// doesn't work and isn't allowed.
| KnownInstanceType::NewType(_) => None,
KnownInstanceType::TypeGenericAlias(_) => {
Self::try_from_type(db, KnownClass::Type.to_class_literal(db), subclass)
}
KnownInstanceType::Annotated(ty) => Self::try_from_type(db, ty.inner(db), subclass),
},

View File

@@ -9457,7 +9457,8 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
| Type::KnownInstance(
KnownInstanceType::UnionType(_)
| KnownInstanceType::Literal(_)
| KnownInstanceType::Annotated(_),
| KnownInstanceType::Annotated(_)
| KnownInstanceType::TypeGenericAlias(_),
),
Type::ClassLiteral(..)
| Type::SubclassOf(..)
@@ -9466,7 +9467,8 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
| Type::KnownInstance(
KnownInstanceType::UnionType(_)
| KnownInstanceType::Literal(_)
| KnownInstanceType::Annotated(_),
| KnownInstanceType::Annotated(_)
| KnownInstanceType::TypeGenericAlias(_),
),
ast::Operator::BitOr,
) if pep_604_unions_allowed() => {
@@ -10627,7 +10629,13 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
// special cases, too.
if class.is_tuple(self.db()) {
return tuple_generic_alias(self.db(), self.infer_tuple_type_expression(slice));
} else if class.is_known(self.db(), KnownClass::Type) {
let argument_ty = self.infer_type_expression(slice);
return Type::KnownInstance(KnownInstanceType::TypeGenericAlias(
InternedType::new(self.db(), argument_ty),
));
}
if let Some(generic_context) = class.generic_context(self.db()) {
return self.infer_explicit_class_specialization(
subscript,
@@ -10764,6 +10772,13 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
}
}
}
Type::SpecialForm(SpecialFormType::Type) => {
// Similar to the branch above that handles `type[…]`, handle `typing.Type[…]`
let argument_ty = self.infer_type_expression(slice);
return Type::KnownInstance(KnownInstanceType::TypeGenericAlias(
InternedType::new(self.db(), argument_ty),
));
}
_ => {}
}

View File

@@ -826,7 +826,7 @@ impl<'db> TypeInferenceBuilder<'db, '_> {
self.infer_type_expression(slice);
todo_type!("Generic specialization of types.UnionType")
}
KnownInstanceType::Literal(ty) => {
KnownInstanceType::Literal(ty) | KnownInstanceType::TypeGenericAlias(ty) => {
self.infer_type_expression(slice);
if let Some(builder) = self.context.report_lint(&INVALID_TYPE_FORM, subscript) {
builder.into_diagnostic(format_args!(