https://github.com/astral-sh/ruff/pull/28425 added a new way to infer
implicit and PEP 613 type aliases, which I'd previously described in
https://github.com/astral-sh/ty/issues/1711. Rather than using the value
type of the alias and converting it back to its type-annotation meaning,
this system goes back to the original definition and infers it directly
as a type expression. This gives us more robust validation that implicit
type aliases are valid type expressions, and allows us to emit accurate
diagnostics both for invalid-as-type-expression and for
invalid-at-runtime.
https://github.com/astral-sh/ruff/pull/28425 used this new approach only
for recursive type aliases; this PR expands it to all implicit and PEP
613 type aliases, so that we consistently get its benefits. This also
significantly improves our conformance results for implicit type
aliases; we now pass two more conformance files.
This is an example of the sort of thing that we previously accepted as a
type alias, and now reject (as the conformance suite says we should):
```py
BadAlias = (lambda: int)()
def f(value: BadAlias): # Main: int, Now: invalid-type-form
...
```
This also makes us more consistent (with ourselves, other type checkers
,and the conformance suite) when a generic type is used "bare" in an
alias. The core rule we use is that the RHS of an implicit or PEP 613
type alias is a type expression, therefore a use of a bare generic alias
in that type expression should be implicitly default-specialized.
```py
from typing import TypeVar
T = TypeVar("T", default=str)
GenAlias = list[T]
AnotherAlias = GenAlias | int
# this is now an error: AnotherAlias is not generic
def _(x: AnotherAlias[bytes]): ...
# The bare reference to GenAlias inside AnotherAlias is default-specialized:
def _(x: AnotherAlias):
reveal_type(x) # list[str] | int
```
We do make one carve-out from this rule: we consider a plain assignment
like `A = B` or `A = module.B` to be a direct "rename" or "forward" that
doesn't really treat the RHS as a type expression, and thus doesn't
default-specialize anything; instead `A` just becomes a new name for
`B`. This feels more intuitive, and matches pyrefly and pyright. This
carve-out does not apply to PEP 613 type aliases: `A: TypeAlias = B` is
explicitly a type alias, not a rename, so it does default-specialize
`B`.
Reject computed values used as types, including values that evaluate to
classes or `Any`, and preserve that validation when `invalid-type-form`
is disabled. Definition lookup stays behind a tracked query so unrelated
edits in an imported module do not invalidate consumers.
Fixes https://github.com/astral-sh/ty/issues/1711.
Fixes https://github.com/astral-sh/ty/issues/1846.
Prepares https://github.com/astral-sh/ty/issues/4683. Runtime `|`
behavior is not changed here.
Source-location diagnostic explanations for invalid aliases are added in
the follow-up #29654.
## Ecosystem
[Full ecosystem
analysis](https://github.com/astral-sh/ruff/pull/29200#issuecomment-6353595871)
for `b175c73` covers all 150 diagnostic changes across 21 projects: 61
additions, 58 removals, and 31 message changes. New diagnostics
primarily validate computed values used as types and default-specialized
explicit aliases. Improved alias inference removes cascading errors and
preserves forward references and generic parameters.
The nine new discord.py false positives match the known
[ty#4016](https://github.com/astral-sh/ty/issues/4016) callback-context
limitation and are accepted for this PR. No other new false positives
were identified.
Conformance gains six expected diagnostics (five in
`aliases_implicit.py`, one in `aliases_explicit.py`) and two fully
passing files, with no new conformance false positives.
## Summary
We now terminate inference when an `Annotated` value recursively wraps
its own inferred type:
```python
from typing import Annotated, reveal_type
from ty_extensions._internal import TypeOf
value = int
while True:
value = Annotated[TypeOf[value], "metadata"]
reveal_type(value)
```
We preserve the `Annotated` wrapper when simplifying the recursive type,
so inference can recognize the cycle and stop expanding it.
Addresses the runtime `Annotated` reproducer in
https://github.com/astral-sh/ty/issues/3837.
ty can incorrectly treat a branch guarded by an impossible compound
condition as reachable when an operand has potentially mutable
truthiness. For example, `if value and False:` always skips its body in
CPython; the first falsy operand selects the control-flow path
immediately, it doesn't fully evaluate `value and False` and then
re-evaluate the truthiness of the result. Saving `value and False` to a
variable and then testing the saved object can instead call
`value.__bool__` twice and get different answers.
Distinguish expressions consumed directly as conditions from expressions
that produce values. Evaluate direct boolean and conditional expressions
structurally, and retain the combined truthiness of chained comparisons
even when a comparison returns an arbitrary object. Operands with types
equivalent to `Never` cannot produce a result; preserve that distinction
from ambiguous truthiness while composing conditions. Value contexts
continue to allow repeated truthiness checks to disagree.
To limit retained memory, comparison truthiness uses sparse overrides in
optional inference metadata, stored as boxed slices. Ordinary comparison
chains use the truthiness of their inferred value type, and root
chained-comparison conditions reuse expression inference without a
separate condition-analysis memo. Cycle widening preserves overrides
when needed to keep the effective truthiness monotonic. Tracking
operands that cannot produce a result adds only transient evaluation
state.
Prerequisite for #28045, which addresses astral-sh/ty#4380.
## Ecosystem results
Five expected diagnostic removals across pwndbg, pytest, and Spark; no
additions. Each comes from a branch that is unreachable under the
checked platform or declared types. See the [Codex ecosystem
analysis](https://github.com/astral-sh/ruff/pull/28082#issuecomment-5434341797)
for details and minimized reproducers.
## Test plan
- Mdtests cover compound conditions, nested boolean operations and
`not`, conditional expressions, and chained comparisons across branches,
loops, assertions, comprehension filters, and match guards.
- Reachability assertions use revealed variable types, including
reachable saved results, assignment expressions, nested value
expressions, and call arguments whose truthiness can be tested again.
- Cases with operands narrowed to `Never`, aliases and unions of aliases
of `Never`, and type variables bounded by `Never` assert branch
reachability using unrelated variables and check precise
conditional-expression result types.
- Additional cases cover unreachable loop assignments and conditional
expressions in stringified `Annotated` metadata.
- A Rust invariant test covers sparse comparison-truthiness overrides
appearing or disappearing across inference-cycle results, including
preservation of previous-only overrides.
## Summary
Previously, `Annotated` metadata containing unpacked keyword arguments
could panic when the annotation was written as a string:
```python
from typing import Annotated
value: "Annotated[int, dict(**{})]"
```
Dictionary-key narrowing attempted to look up use-definition information
for the unpacked keyword argument, but parsed string-annotation nodes
are not present in the semantic index.
We now skip dictionary-key narrowing inside string annotations while
preserving ordinary call inference. This also handles unpacked
dictionaries in parameter and return annotations.
## Summary
Split `ty_extensions` into a public part (`ty_extensions`), and an
internal part (`ty_extensions._internal`). For now, move everything to
`_internal`, except for:
- `static_assert`
- `Unknown`
- `AlwaysTruthy`, `AlwaysFalsy`
- `Intersection`, `Not`
- `Top`, `Bottom`
- `JustFloat`, `JustComplex`
- `NamedTupleLike`
## Summary
`Annotated[T, ...]` is equivalent to `T`, but when it is used as a class
base, we currently only convert nominal inner types back to class
objects. This causes valid dynamic bases to be rejected:
```python
from typing import Annotated, Any
class F(Annotated[Any, "metadata"]): ...
```
This preserves dynamic inner types as dynamic class bases, so
`Annotated[Any, ...]` behaves like `Any` while existing nominal
`Annotated` bases continue to work unchanged.
## Summary
There were:
- a couple of places where we emitted two diagnostics where one would do
- a few places where we fell back to overly precise inferred types in
error cases (inferring types like `(Unknown, /) -> None` where `(...) ->
None` would arguably be better)
- a few places where we correctly emitted a diagnostic, but didn't have
an ideal error message
This PR just makes some minor cleanups in that area
## Test Plan
new mdtests
## Summary
Infer the first argument `type` inside `Annotated[type, …]` as a type
expression. This allows us to support stringified annotations inside
`Annotated`.
## Ecosystem
* The removed diagnostic on `prefect` shows that we now understand the
`State.data` type annotation in
`src/prefect/client/schemas/objects.py:230`, which uses a stringified
annotation in `Annoated`. The other diagnostics are downstream changes
that result from this, it seems to be a commonly used data type.
* `artigraph` does something like `Annotated[cast(Any,
field_info.annotation), *field_info.metadata]` which I'm not sure we
need to allow? It's unfortunate since this is probably supported at
runtime, but it seems reasonable that they need to add a `# type:
ignore` for that.
* `pydantic` uses something like `Annotated[(self.annotation,
*self.metadata)]` but adds a `# type: ignore`
## Test Plan
New Markdown test
## Summary
Add support for `Optional` and `Annotated` in implicit type aliases
part of https://github.com/astral-sh/ty/issues/221
## Typing conformance changes
New expected diagnostics.
## Ecosystem
A lot of true positives, some known limitations unrelated to this PR.
## Test Plan
New Markdown tests