Commit Graph
6 Commits
Author SHA1 Message Date
Carl Meyer 7ae3af9e7d [ty] Preserve tuple shapes during concatenation (#28617)
Tuple concatenation currently discards element positions and tuple
length, so adding two fixed-length tuples produces a variable-length
tuple. Preserve the concatenated shape, including known prefixes and
suffixes around variable-length portions.

As with tuple slicing and iteration, this (unsoundly) assumes values
annotated as `tuple` behave like ordinary tuples, even though a subclass
could override `__add__` and/or `__radd__` incompatibly. Explicitly
known subclasses continue to use their operator methods.

Keep inference bounded by approximating large tuple combinations and
widening tuple lengths when their alternatives change between cycle
iterations. Stable tuple unions, including those supplied by collection
type context, retain their shapes. Some cycles with finite but changing
tuple lengths can still lose precision to ensure convergence.

Fixes https://github.com/astral-sh/ty/issues/3413.

## Ecosystem impact

- Removes tuple-shape false positives in Hydra-zen, Trio, Spark, and
SymPy, and two unsoundness warnings in pandas.
- Most other changes make existing diagnostics more precise. New errors
expose overly narrow tuple attributes and collection element types in
zope.interface and SymPy, including invariant dictionary key types.
- One new xarray false positive exposes existing dictionary-key
inference that incorrectly restricts keys to strings. This limitation is
left for separate work. Cycle widening also loses finite tuple
alternatives in Apprise, consolidating existing errors without changing
which operations are rejected.

[Full ecosystem
analysis](https://github.com/astral-sh/ruff/pull/28617#issuecomment-5687202176).

## Performance

The `many_tuple_assignments` microbenchmark increases from 141.1 ms to
159.7 ms in simulation and from 6.4 MB to 6.9 MB in memory. This is an
expected cost of preserving tuple shapes; the tradeoff is acceptable for
this change. See the [benchmark
report](https://github.com/astral-sh/ruff/pull/28617#issuecomment-5684963921).

## Test plan

- Mdtests cover fixed and empty tuples, variable-length prefixes and
suffixes, aliases, union operands, subclass overrides, and
`TypeVarTuple` concatenation with both typing syntaxes.
- Exercise ordinary and augmented concatenation, large unions with
custom operators, repeated doubling, and recursively growing local
variables and instance attributes.
- Preserve finite alternating tuple shapes and fixed-length tuple unions
supplied by an empty list's return context.
- Verify incompatible augmented assignment to `tuple[Any, Any]` and
instance-layout conflicts detected through concatenated `__slots__`.
- Unit tests cover tuple widening across cycle results, including equal
lengths, changing lengths, discarded alternatives, avoiding relation
queries, and `Never` elements.
2026-09-15 13:24:13 -07:00
Alex Waygood 7b4103bcb6 [ty] Remove special casing for tuple addition (#19636) 2025-07-30 16:25:42 +00:00
Douglas CreagerandAlex Waygood ea812d0813 [ty] Homogeneous and mixed tuples (#18600)
We already had support for homogeneous tuples (`tuple[int, ...]`). This
PR extends this to also support mixed tuples (`tuple[str, str,
*tuple[int, ...], str str]`).

A mixed tuple consists of a fixed-length (possibly empty) prefix and
suffix, and a variable-length portion in the middle. Every element of
the variable-length portion must be of the same type. A homogeneous
tuple is then just a mixed tuple with an empty prefix and suffix.

The new data representation uses different Rust types for a fixed-length
(aka heterogeneous) tuple. Another option would have been to use the
`VariableLengthTuple` representation for all tuples, and to wrap the
"variable + suffix" portion in an `Option`. I don't think that would
simplify the method implementations much, though, since we would still
have a 2×2 case analysis for most of them.

One wrinkle is that the definition of the `tuple` class in the typeshed
has a single typevar, and canonically represents a homogeneous tuple.
When getting the class of a tuple instance, that means that we have to
summarize our detailed mixed tuple type information into its
"homogeneous supertype". (We were already doing this for heterogeneous
types.)

A similar thing happens when concatenating two mixed tuples: the
variable-length portion and suffix of the LHS, and the prefix and
variable-length portion of the RHS, all get unioned into the
variable-length portion of the result. The LHS prefix and RHS suffix
carry through unchanged.

---------

Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>
2025-06-20 18:23:54 -04:00
Douglas Creager 0fb94c052e [ty] Infer parameter specializations of generic aliases (#18021)
This updates our function specialization inference to infer type
mappings from parameters that are generic aliases, e.g.:

```py
def f[T](x: list[T]) -> T: ...

reveal_type(f(["a", "b"]))  # revealed: str
```

Though note that we're still inferring the type of list literals as
`list[Unknown]`, so for now we actually need something like the
following in our tests:

```py
def _(x: list[str]):
    reveal_type(f(x))  # revealed: str
```
2025-05-12 22:12:44 -04:00
Alex Waygood 55df9271ba [ty] Understand homogeneous tuple annotations (#17998) 2025-05-12 22:02:25 -04:00
Micha Reiser b51c4f82ea Rename Red Knot (#17820) 2025-05-03 19:49:15 +02:00