Commit Graph
16 Commits
Author SHA1 Message Date
Carl Meyer c08d12bfc9 [ty] Infer implicit aliases from their definition as type expressions (#29200)
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.
2026-10-23 16:32:27 -07:00
Charlie Marsh 02f3326445 [ty] Preserve recursive structure in Annotated values (#29058)
## 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.
2026-10-07 09:22:57 -04:00
Carl Meyer 17761270a5 [ty] Preserve short-circuit reachability for direct conditions (#28082)
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.
2026-08-27 17:03:22 -07:00
Charlie Marsh 34bc477604 [ty] Avoid panic on unpacked kwargs in string annotations (#27963)
## 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.
2026-08-21 16:54:41 -04:00
Alex Waygood d031eb1fc9 [ty] Support Annotated inside type[...] (#27629) 2026-08-10 13:25:10 +01:00
David Peter 7b3b6a0b8c [ty] Split ty_extensions into public and internal parts (#26586)
## 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`
2026-07-07 02:32:21 -07:00
Charlie Marsh c256d5f573 [ty] Support Annotated[Any, ...] as a class base (#26133)
## 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.
2026-06-18 12:16:52 -04:00
Alex Waygood 99d97bd72f [ty] Tighten up a few edge cases in Concatenate type-expression parsing (#24172)
## 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
2026-04-09 09:43:50 +01:00
Alex Waygood 7192216ead [ty] Fix panic on list[Annotated[()]] (#24303) 2026-03-30 18:14:04 +01:00
cb58704e08 [ty] Sync vendored typeshed stubs (#23006)
Close and reopen this PR to trigger CI

---------

Co-authored-by: typeshedbot <>
Co-authored-by: David Peter <mail@david-peter.de>
2026-02-03 13:20:44 +01:00
David Peter e9a5337136 [ty] Support stringified annotations in value-position Annotated instances (#21447)
## 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
2025-11-14 13:09:09 +00:00
David Peter 238f151371 [ty] Add support for Optional and Annotated in implicit type aliases (#21321)
## 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
2025-11-10 10:24:38 +01:00
Alex Waygood db0e921db1 [ty] Fix bug where ty would think all types had an __mro__ attribute (#20995) 2025-10-27 11:19:12 +00:00
1dc8f8f903 [ty] Add hints to invalid-type-form for common mistakes (#18543)
Co-authored-by: Ben Bar-Or <ben.baror@ridewithvia.com>
Co-authored-by: Alex Waygood <alex.waygood@gmail.com>
2025-06-09 00:40:05 +01:00
Charlie Marsh a2e9a7732a Update class literal display to use <class 'Foo'> style (#17889)
## Summary

Closes https://github.com/astral-sh/ruff/issues/17238.
2025-05-06 20:11:25 -04:00
Micha Reiser b51c4f82ea Rename Red Knot (#17820) 2025-05-03 19:49:15 +02:00