Commit Graph
12 Commits
Author SHA1 Message Date
Charlie Marsh 07bd1f1a5c [ty] Fix panic on a chained assignment with a missing value (#29787)
## Summary

Debug builds of ty panic when an annotation refers to a target of an
incomplete chained assignment.

```python
X = Y =
x: X
```

The parser uses an invalid name for the missing right-hand side. When
checking whether `X` was an implicit type alias, we tried to resolve
that name as a reference. This triggered a debug assertion because both
targets share a standalone expression.

We now rule out an implicit type alias when the right-hand side is an
invalid name. ty reports the syntax error, treats the annotation as
`Unknown`, and continues checking the file.

Closes https://github.com/astral-sh/ty/issues/4837.
2026-10-28 09:55:29 -07:00
Micha Reiser 689dc812f3 Rename TokenKind::Name to Identifier (#28667) 2026-09-17 15:47:10 +02:00
Alex Waygood ad6cf1776e [ty] Preserve list literal positions in starred unpacking (#28061)
## Summary

Fix false-positive `invalid-assignment` diagnostics when unpacking list
literals, and consolidate the sequence matching, expansion, and
capture-list inference used for tuples and lists:

```python
first: int
first, *rest = [1, "wrong"]
```

Previously, unpacking the inferred `list[int | str]` lost the positions
of the individual elements and checked `int | str` against the
annotation on `first`. Preserving the literal's positions gives
`Literal[1]` for `first` and `list[str]` for `rest`.

The implementation shares the underlying operations across their
consumers:

- `Tuple::unpack` matches fixed and variable source sequences to fixed
and starred targets. Assignment unpacking, tuple resizing, and
sequence-pattern analysis use this matching logic.
- `TupleBuilder<T, V>` generalizes tuple construction and provides
shared concatenation through `concat_with`. Tuple inference can retain
symbolic `TypeVarTuple` segments, while assignment unpacking can retain
source expressions.
- A shared literal-expansion traversal serves assignment inference,
tuple-expression inference, and source-expression lookup for
diagnostics. It preserves nested literal positions and known prefixes
and suffixes around expansions without assigning persistent fixed-length
types to mutable lists.
- Starred assignments and sequence-pattern captures use the same helper
to infer their new lists, sharing literal and tuple-size promotion rules
with ordinary mutable-collection inference.

List literals now receive the same length-mismatch diagnostics and
unknown-type recovery as tuples. Starred captures from tuples also
follow mutable-list promotion rules, including `list[Unknown]` for empty
captures. The existing large-tuple precision limit counts elements
contributed by literal expansions, and its widening is preserved through
nested unpacking.

## Out of scope: contextual inference for unpacking

Unpacking does not currently use annotations on assignment targets as
type context when inferring the right-hand side. This is a pre-existing
limitation for both tuple and list right-hand sides. For example, these
valid assignments still produce false positives:

```python
from typing import Literal

value: list[Literal[1]]
value, other = ([1], 0)  # Inferred list[int] is rejected.
value, other = [[1], 0]  # Inferred list[int] is rejected.
```

In both cases, the nested list is inferred without the target's
annotation. Fixing this missing contextual inference is out of scope for
this PR.
2026-08-28 10:51:03 +01:00
Carl Meyer b4531166f3 [ty] Avoid panics on incomplete protocol type parameter lists (#28088)
ty can panic when a generic protocol definition has an incomplete type
parameter list. The autofix for `invalid-generic-class` assumes that the
list contains both brackets, which can produce an inverted range or
split a Unicode identifier when the closing bracket is missing.

Check the delimiters before comparing the type parameters with the
`Protocol` subscript. Incomplete lists still produce diagnostics, but do
not receive this autofix. Targeted Hawk expectations preserve the public
saturating arithmetic helpers in `TextSize`.

Fixes astral-sh/ty#4397.

## Test plan

Add mdtests for an empty, unclosed type parameter list and an unclosed
list containing a Unicode name. Both cases produce diagnostics without
panicking. Existing protocol tests retain coverage for the autofix on
complete type parameter lists.
2026-08-27 04:05:57 +00:00
Carl Meyer fce9727c83 [ty] Fix panic from mismatched OR-pattern bindings (#27533)
## Summary

https://github.com/astral-sh/ruff/pull/27438 modeled OR-pattern
alternatives as distinct control-flow paths rather than linear control
flow. This is correct, but the implementation was inadequate; it
effectively treated all of these branches simultaneously as "definitely
taken", which becomes a problem in the (invalid syntax) case where not
all branches bind the same name(s). That caused a panic.

Fix this by introducing reachability predicates to explicitly model that
only one of these "branches" can be taken.

Closes astral-sh/ty#4194.

## Test plan

Added mdtests covering distinct and overlapping captures, alternatives
without bindings in either order, three-way alternatives, previously
bound names, nested mismatches, guard references, and the original
malformed-case panic.
2026-08-05 17:39:50 -07:00
Carl Meyer c88d3c57b8 [ty] Avoid double inference of Unpack operands in Union (#27525)
Fixes astral-sh/ty#4193.

Ensure `Unpack` always infers its operand, including in invalid
contexts, so `Union` can reuse the recorded type instead of inferring
the same expression twice. Preserve runtime diagnostics for evaluated
operands while suppressing them inside invalid string annotations.

## Test plan

- Cover malformed `Unpack[]` nested inside `Union` and a generic
specialization.
- Cover syntactically valid `Unpack[int]` nested inside `Union` and
preserve unsupported `Unpack[Ts]` recovery.
- Verify invalid evaluated contexts report operand errors while invalid
string annotations suppress them.
2026-08-05 14:29:55 -07:00
Ed Page 34d0944f3b Reduce syntax error noise by swallowing dedents like indents 2026-07-24 14:42:57 -05:00
justinandLérè 3a200ce85a [ty] Distinguish typing.Callable from collections.abc.Callable (#24954)
## Summary
https://github.com/astral-sh/ty/issues/887

This is a blocker to supporting `Callable()` in class patterns in match
statements (discussion
[below](https://github.com/astral-sh/ruff/pull/24954#discussion_r3171744197)).
`typing.Callable` is a deprecated alias to `collections.abc.Callable` -
calling the former raises a `TypeError` at runtime whereas the latter
doesn't.

To allow `Callable()` to be used in `match` statements, we need to be
able to distinguish between the two.

Complication: typeshed defines `collections.abc.Callable` as a re-export
alias from `typing` (`collections/abc.pyi` -> `_collections_abc.pyi` ->
`from typing import Callable as Callable`). This required some
additional plumbing to pass `collections.abc` through as the known
module (the re-exporting module) vs `typing`

## Test Plan
New mdtests

---------

Co-authored-by: Lérè <contact@lrbr.dev>
2026-06-01 12:50:16 -07:00
Charlie Marsh c09080468a [ty] Avoid panic from non-name walrus targets (#25121)
## Summary

This PR fixes a panic when parser recovery produces a walrus expression
whose target is not an identifier, and that expression is then used as
part of a member expression:

```python
obj = 1
out = (obj.attr := obj).attr
```
2026-05-12 15:04:36 -04:00
Charlie Marsh 385dd2770b [ty] Avoid double-inference on non-tuple argument to Annotated (#21837)
## Summary

If you pass a non-tuple to `Annotated`, we end up running inference on
it twice. I _think_ the only case here is `Annotated[]`, where we insert
a (fake) empty `Name` node in the slice.

Closes https://github.com/astral-sh/ty/issues/1801.
2025-12-08 10:24:05 -05:00
David Peter e8e8180888 [ty] Implicit type aliases: Add support for typing.Union (#21363)
## Summary

Add support for `typing.Union` in implicit type aliases / in value
position.

## Typing conformance tests

Two new tests are passing

## Ecosystem impact

* The 2k new `invalid-key` diagnostics on pydantic are caused by
https://github.com/astral-sh/ty/issues/1479#issuecomment-3513854645.
* Everything else I've checked is either a known limitation (often
related to type narrowing, because union types are often narrowed down
to a subset of options), or a true positive.

## Test Plan

New Markdown tests
2025-11-12 12:59:14 +01:00
Micha Reiser b51c4f82ea Rename Red Knot (#17820) 2025-05-03 19:49:15 +02:00