Skip to content

Commit 4d4c8fa

Browse files
authored
[ty] Emit diagnostic when specializing a non-generic class (#26883)
## Summary Emit `not-subscriptable` when a non-generic class is specialized in a type expression, and recover as `Unknown` instead of an internal `@Todo` type. This highlighted some scenarios in the ecosystem result where `not-subscriptable` is being emitted but it might not be ideal, refer to my inline comments. I've added mdtest cases for these looking at the ecosystem result. Closes astral-sh/ty#2439. ## Test plan Update the mdtest
1 parent 7c3e2db commit 4d4c8fa

5 files changed

Lines changed: 168 additions & 5 deletions

File tree

‎crates/ty_python_semantic/resources/mdtest/generics/legacy/classes.md‎

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,116 @@ reveal_type(generic_context(ExplicitInheritedGenericPartiallySpecialized))
158158
reveal_type(generic_context(ExplicitInheritedGenericPartiallySpecializedExtraTypevar))
159159
```
160160

161+
## Specializing classes with unavailable generic context
162+
163+
When an earlier error prevents ty from determining a class's generic context, specializing the class
164+
can emit a cascading `not-subscriptable` diagnostic.
165+
166+
### Conditional typing compatibility imports
167+
168+
Libraries support multiple Python versions by importing generic machinery from either
169+
`typing_extensions` or `typing`. ty does not yet recognize the resulting union as the corresponding
170+
typing special form.
171+
172+
```py
173+
try:
174+
import typing_extensions as typing
175+
except ImportError:
176+
import typing
177+
178+
T = typing.TypeVar("T")
179+
180+
# TODO: Fix the conditional typing import in https://github.com/astral-sh/ty/issues/1585.
181+
# error: [invalid-argument-type] "`typing_extensions.TypeVar | typing.TypeVar` is not a valid argument to `Generic`"
182+
class Parser(typing.Generic[T]): ...
183+
184+
# TODO: Remove this cascading error when https://github.com/astral-sh/ty/issues/1585 is fixed.
185+
parser: Parser[int] # error: [not-subscriptable] "Cannot subscript non-generic type `<class 'Parser'>`"
186+
```
187+
188+
### Decorated generic bases
189+
190+
A decorator that ty cannot fully understand can obscure the generic context of a base class. A
191+
subclass that forwards type variables to that base remains possibly generic.
192+
193+
```py
194+
import collections.abc
195+
from typing import Generic, TypeVar
196+
from ty_extensions._internal import generic_context
197+
198+
K = TypeVar("K")
199+
V = TypeVar("V")
200+
201+
# error: [unresolved-attribute] "Class `Mapping` has no attribute `register`"
202+
@collections.abc.Mapping.register
203+
class Mapping(Generic[K, V]): ...
204+
205+
# TODO: Invalid decorator causes us to lose the generic context from the class...
206+
reveal_type(generic_context(Mapping)) # revealed: None
207+
208+
class FrozenDict(Mapping[K, V]): ...
209+
210+
# TODO: ...which then causes us to emit this
211+
# error: [not-subscriptable] "Cannot subscript non-generic type `<class 'FrozenDict'>`"
212+
mapping: FrozenDict[str, int]
213+
```
214+
215+
### Unresolved generic bases
216+
217+
```py
218+
from typing import TypeVar
219+
220+
from missing import Base # error: [unresolved-import]
221+
222+
reveal_type(Base) # revealed: Unknown
223+
224+
T = TypeVar("T")
225+
226+
class Child(Base[T]): ...
227+
228+
# error: [not-subscriptable] "Cannot subscript non-generic type `<class 'Child'>`"
229+
child: Child[int]
230+
```
231+
232+
### Conditional generic bases
233+
234+
`base1.py`:
235+
236+
```py
237+
from typing import Generic, TypeVar
238+
239+
T = TypeVar("T")
240+
241+
class Base(Generic[T]): ...
242+
```
243+
244+
`base2.py`:
245+
246+
```py
247+
from typing import Generic, TypeVar
248+
249+
T = TypeVar("T")
250+
251+
class Base(Generic[T]): ...
252+
```
253+
254+
```py
255+
from typing import TypeVar
256+
257+
try:
258+
from base1 import Base
259+
except ImportError:
260+
from base2 import Base
261+
262+
T = TypeVar("T")
263+
264+
# error: [unsupported-base]
265+
class Child(Base[T]): ...
266+
267+
# error: [not-subscriptable] "Cannot subscript non-generic type `<class 'Child'>`"
268+
child: Child[int]
269+
```
270+
161271
## Errors for inconsistent type arguments
162272

163273
<!-- snapshot-diagnostics -->

‎crates/ty_python_semantic/resources/mdtest/generics/pep695/aliases.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,7 @@ class LegacyDict(TypedDict[T]):
152152
# error: [unbound-type-variable]
153153
x: T
154154

155+
# error: [not-subscriptable] "Cannot subscript non-generic type `<class 'LegacyDict'>`"
155156
type LegacyDictInt = LegacyDict[int]
156157

157158
# error: [not-subscriptable] "Cannot specialize non-generic type alias `LegacyDictInt`"

‎crates/ty_python_semantic/resources/mdtest/generics/pep695/classes.md‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -919,6 +919,44 @@ reveal_type(generic_context(A.merge)) # revealed: ty_extensions._internal.Gener
919919
reveal_type(generic_context(Impl.foo)) # revealed: ty_extensions._internal.GenericContext[Self@foo]
920920
```
921921

922+
## Subscripting non-generic classes
923+
924+
Subscripting a non-generic class in a type expression is an error. The invalid type expression
925+
recovers to `Unknown`.
926+
927+
```py
928+
class NonGeneric: ...
929+
930+
# error: [not-subscriptable] "Cannot subscript non-generic type `<class 'NonGeneric'>`"
931+
def direct(value: NonGeneric[int]) -> None:
932+
reveal_type(value) # revealed: Unknown
933+
```
934+
935+
The same diagnostic applies when the specialization is nested inside `type[...]`.
936+
937+
```py
938+
# error: [not-subscriptable] "Cannot subscript non-generic type `<class 'NonGeneric'>`"
939+
def nested(value: type[NonGeneric[int]]) -> None:
940+
reveal_type(value) # revealed: Unknown
941+
```
942+
943+
Inheriting from a non-generic class, or from a specialization of a generic class, does not make the
944+
subclass generic.
945+
946+
```py
947+
class Child(NonGeneric): ...
948+
class Generic[T]: ...
949+
class SpecializedChild(Generic[int]): ...
950+
951+
# error: [not-subscriptable] "Cannot subscript non-generic type `<class 'Child'>`"
952+
def child(value: Child[str]) -> None:
953+
reveal_type(value) # revealed: Unknown
954+
955+
# error: [not-subscriptable] "Cannot subscript non-generic type `<class 'SpecializedChild'>`"
956+
def specialized_child(value: SpecializedChild[bytes]) -> None:
957+
reveal_type(value) # revealed: Unknown
958+
```
959+
922960
## Tuple as a PEP-695 generic class
923961

924962
Our special handling for `tuple` does not break if `tuple` is defined as a PEP-695 generic class in

‎crates/ty_python_semantic/resources/mdtest/protocols.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6563,7 +6563,7 @@ class B1(A1[T3], Protocol[T3]): ...
65636563
class B2(A2[T4], Protocol[T4]): ...
65646564

65656565
# TODO should just be `B2[Any]`
6566-
reveal_type(T3.__bound__) # revealed: B2[Any] | @Todo(specialized non-generic class)
6566+
reveal_type(T3.__bound__) # revealed: B2[Any] | Unknown
65676567

65686568
# TODO error: [invalid-type-arguments]
65696569
def f(x: B1[int]):

‎crates/ty_python_semantic/src/types/infer/builder/type_expression.rs‎

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1341,9 +1341,16 @@ impl<'db> TypeInferenceBuilder<'db, '_> {
13411341
)
13421342
}
13431343
None => {
1344-
// TODO: emit a diagnostic if you try to specialize a non-generic class.
13451344
self.infer_expression(parameters, TypeContext::default());
1346-
todo_type!("specialized non-generic class")
1345+
if let Some(builder) =
1346+
self.context.report_lint(&NOT_SUBSCRIPTABLE, subscript)
1347+
{
1348+
builder.into_diagnostic(format_args!(
1349+
"Cannot subscript non-generic type `{}`",
1350+
value_ty.display(self.db())
1351+
));
1352+
}
1353+
Type::unknown()
13471354
}
13481355
}
13491356
}
@@ -1776,9 +1783,16 @@ impl<'db> TypeInferenceBuilder<'db, '_> {
17761783
.unwrap_or(Type::unknown())
17771784
}
17781785
_ => {
1779-
// TODO: emit a diagnostic if you try to specialize a non-generic class.
17801786
self.infer_expression(slice, TypeContext::default());
1781-
todo_type!("specialized non-generic class")
1787+
if let Some(builder) =
1788+
self.context.report_lint(&NOT_SUBSCRIPTABLE, subscript)
1789+
{
1790+
builder.into_diagnostic(format_args!(
1791+
"Cannot subscript non-generic type `{}`",
1792+
value_ty.display(self.db())
1793+
));
1794+
}
1795+
Type::unknown()
17821796
}
17831797
}
17841798
}

0 commit comments

Comments
 (0)