Rename the method, attribute, property, and mutable override rules to
`incompatible-…-override`. The old names remain aliases in configuration
and inline suppressions:
| Before | After |
|---|---|
| `invalid-method-override` | `incompatible-method-override` |
| `invalid-attribute-override` | `incompatible-attribute-override` |
| `invalid-property-type-override` | `incompatible-property-override` |
| `invalid-mutable-override` | `incompatible-mutable-override` |
A follow-up PR will split `invalid-method-override` into two rules.
Fixesastral-sh/ty#2001.
---------
Co-authored-by: Alex Waygood <alex.waygood@gmail.com>
## Summary
Users can now suppress an attribute error that affects only some union
members and still catch names that are missing from every member. For
example, both lines below previously reported `unresolved-attribute`:
```python
def clean(value: str | int) -> str:
value.stirp() # missing-attribute: neither str nor int has stirp
return value.strip() # missing-union-attribute: str has strip, int does not
```
The motivation is that a project adopting ty may want `value.strip()` on
`str | None` to only warn while a typo remains an error-severity
diagnostic.
Both rules default to errors. The same distinction applies to optional
values such as `str | None` and to attribute deletion. Attributes
defined only conditionally on a class continue to use
`possibly-missing-attribute`.
### Comparison to other type checkers
Pyright distinguishes between `reportOptionalMemberAccess` (which is
specifically for unions with `None`) and `reportAttributeAccessIssue`,
which is for all other unions. mypy, meanwhile, distinguishes between
`union-attr` (which is an error code for all attribute-access errors on
union types) and `attr-defined` (which is an error code for all
attribute-access errors on non-union types). So this new split doesn't
_exactly_ align with either precedent -- but I _do_ think it's probably
the most useful split we can do, and it's the one that makes the most
sense _a priori_ in my opinion.
### Compatibility
`unresolved-attribute` remains an alias for `missing-attribute` in
configuration and inline ignores. To preserve a setting such as
`unresolved-attribute = "warn"` for both cases, also set
`missing-union-attribute = "warn"`. On an access that fails for only
some union members, replace `# ty: ignore[unresolved-attribute]` with `#
ty: ignore[missing-union-attribute]`. Tools that consume diagnostic
codes should recognize both new names.
Fixesastral-sh/ty#2839 and fixesastral-sh/ty#2471.
## Test Plan
A comparison with ty 0.0.96 on typeshed-stats, docstring-adder,
sphinx-lint, and typing_extensions found the same messages, locations,
and severities. Eight diagnostics received `missing-union-attribute`
across those four projects (two in sphinx-lint and six in
typing_extensions).
---------
Co-authored-by: Brent Westbrook <brentrwestbrook@gmail.com>
## Summary
We now check that attribute and property overrides preserve the types
that can be read and written through the superclass. The checks extend
`invalid-attribute-override` and introduce two separately configurable
rules, following the distinction proposed in
[ty#2158](https://github.com/astral-sh/ty/issues/2158).
### `invalid-attribute-override`
We reject ordinary attributes whose readable type is incompatible with
the inherited declaration. This rule is enabled by default:
```python
class Base:
value: int
class Child(Base):
value: str # Now rejected: invalid-attribute-override.
```
The rule also rejects removing write access, such as replacing a
writable attribute with a `Final` attribute, and retains the existing
checks for incompatible `ClassVar` qualifiers.
### `invalid-property-type-override`
We reject incompatible property result types, setters that accept fewer
values than the inherited setter, and getter-only properties that
replace writable attributes. This rule is also enabled by default:
```python
class Base:
@property
def value(self) -> int:
return 0
class Child(Base):
@property
def value(self) -> str: # Now rejected: invalid-property-type-override.
return ""
```
A read-only property returning `bool` would be a valid override of this
`int` property. Reads can become more specific; writes must continue to
accept every value permitted by the superclass.
### `invalid-mutable-override`
Narrowing a writable attribute's type preserves reads but restricts
writes. We report this separately, and leave the rule disabled by
default:
```python
class Base:
value: int
class Child(Base):
value: bool # invalid-mutable-override, when enabled.
def reset(obj: Base) -> None:
obj.value = 42
child = Child()
reset(child) # Allowed through Base, but child.value is no longer a bool.
```
This distinction lets users opt into mutable invariance without changing
the other override checks.
## Case analysis
### Cached properties in Home Assistant
The [ecosystem report](https://fed09ff3.ty-ecosystem-ext.pages.dev/diff)
adds 6,986 `invalid-property-type-override` diagnostics.
Home Assistant accounts for 6,863 of those, including 6,861 cases where
a read-only property replaces a writable attribute.
A common pattern is
[BlueCurrentEntity.available](https://github.com/home-assistant/core/blob/8f4c394961405acec82bc01f24620359736617b3/homeassistant/components/blue_current/entity.py#L43),
which replaces the inherited [Entity.available cached
property](https://github.com/home-assistant/core/blob/8f4c394961405acec82bc01f24620359736617b3/homeassistant/helpers/entity.py#L870)
with a getter-only property:
```python
from functools import cached_property
class Entity:
@cached_property
def available(self) -> bool:
return True
class IntegrationEntity(Entity):
@property
def available(self) -> bool: # Now rejected: invalid-property-type-override.
return True
def mark_unavailable(entity: Entity) -> None:
entity.available = False
mark_unavailable(Entity()) # Succeeds.
mark_unavailable(IntegrationEntity()) # Raises AttributeError.
```
Both getters return `bool`, but the override removes a supported write
(a `cached_property` stores its value in the instance dictionary and
permits assignment to replace it, even before the first read, so it's
writable).
This PR retains the diagnostic (it's correct, after all): a function
accepting `Entity` can assign to `entity.available`. Replacing the
cached property with a getter-only property makes that valid operation
fail on subclass instances.
(pyright 1.1.411 in standard mode rejects this override, but mypy 2.3.1
and pyrefly 1.2.0 with default checks accept it.)
Part of https://github.com/astral-sh/ty/issues/2158.
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.
## 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.
## Summary
Previously, chained assignments could panic when their shared right-hand
side contained both an assignment expression and a lambda:
```python
first = second = (named := lambda: 0)
```
Each target independently imported the same nested binding, violating
the uniqueness invariant for inferred bindings.
We now record whether an assignment's value bindings belong to its
definition or its enclosing statement during semantic indexing.
Statements claim shared bindings once while individual targets retain
contextual expression inference. The same ownership rule handles
unpacking, subscript targets, and assignment expressions in lambda
defaults:
```python
first = second = lambda value=(named := 1): value
```
(Stacked on top of #27872)
## Summary
Add a disabled-by-default `unsound-assignment` rule for variable
assignments whose inferred value is assignable to a fully static
declared type but is not a subtype of it. Attribute and subscript
assignments are deliberately excluded from this initial implementation.
Share declaration lookup and diagnostic rendering with
`invalid-assignment` so the rule points to the annotation responsible
for the expected type, including parameters, variadics, global/nonlocal
bindings, and augmented assignments.
Fixesastral-sh/ty#4289.
## Summary
Previously, we treated augmented assignments as ordinary bindings when
inferring implicit attributes. However, `self.value += 1` first reads
`self.value`, so it cannot establish an otherwise missing attribute:
```python
class Counter:
def __init__(self) -> None:
self.value = 0
def increment(self) -> None:
self.value += 1
class UninitializedCounter:
def increment(self) -> None:
self.value += 1 # error: [unresolved-attribute]
```
We now distinguish assignments that establish an attribute from
augmented assignments that require an existing value. Class and instance
member lookup collects augmented assignments while traversing the MRO
and incorporates their inferred results only after resolving an
independent attribute binding.
This preserves missing-attribute diagnostics and allows augmented
assignments to contribute to inferred attribute types.
## Summary
Previously, augmented assignments validated the operator but not the
assignment of its result back to an attribute or subscript:
```python
class A:
def __add__(self, other: object) -> object:
return other
class B:
x: A
b = B()
b.x += 1 # error: [invalid-assignment]
```
We now validate augmented attribute and subscript stores through the
same statement-level assignment machinery as ordinary assignments,
including property setters, descriptors, read-only targets, `Final`,
`ClassVar`, `TypedDict` entries, and union receivers and keys. Failed
operators preserve their recovery types without triggering a write.
We also include augmented assignments when inferring public
instance-attribute types, which lets inferred attributes evolve without
assignment-specific exemptions. Existing receiver-correlation and
unannotated-collection inference limitations remain out of scope.
Closes https://github.com/astral-sh/ty/issues/2175.
## Summary
PEP 484's numeric tower means we represent a `float` annotation as the
semantic union `int | float*` and `complex` as `int | float* |
complex*`. We previously rendered those internal unions directly, which
exposed an implementation detail in user-facing output:
```python
def f() -> float:
return 1
reveal_type(f()) # Before: int | float; after: float
```
This change recognizes complete numeric-tower unions during display and
renders them using their canonical annotation spelling, `float` or
`complex`.
The implementation does _not_ preserve explicit unions, e.g., if the
user writes out `int | float`, we still collapse that rather than trying
to preserve it, mostly for simplicity (as per
https://github.com/astral-sh/ty/issues/2184#issuecomment-4345219164).
Closes https://github.com/astral-sh/ty/issues/2184.
## Summary
This is a first step towards #20411. After this, we would work to either
upstream changes or adjust things within Ruff.
Performance improvements have already been upstreamed
(https://github.com/rust-lang/annotate-snippets-rs/pull/437,
https://github.com/rust-lang/annotate-snippets-rs/pull/440)
Re-implemented the following from the fork:
- Hidden snippets
(https://github.com/rust-lang/annotate-snippets-rs/issues/448)
- Renderer-level disabling of hyperlinks
- Jupyter cell indices
(https://github.com/rust-lang/annotate-snippets-rs/issues/449)
- Fixable mark
(https://github.com/rust-lang/annotate-snippets-rs/issues/450)
- `lineno_offset` (maybe not needed if #20648 is taken care of)
- anonymized lines affects origin
(https://github.com/rust-lang/annotate-snippets-rs/issues/451)
- cut indicator (maybe not needed if we can switch to unicode renderer)
Additional hacks to minimize behavior change include
- Adjust upstream's hidden severity behavior to match Ruff's
(https://github.com/rust-lang/annotate-snippets-rs/issues/452)
- How newlines are annotated
(https://github.com/rust-lang/annotate-snippets-rs/issues/454)
- To not indent for line numbers when none will be present
(https://github.com/rust-lang/annotate-snippets-rs/issues/453)
- Enabling `simd` by default
All of the above represents work that needs to be resolved to address
#20411.
`lib.name` hack is used to simplify maintenance with the assumption that
we'll continue working towards #20411.
Behavior changes that were included
- Tweak when implicit padding lines are present
- Fix Origin's line/column is now derived from the primary annotation
- Make consistent the rendering of primary/context annotations
- Fix snippets to show up for empty source (but may degrade #24528)
- Fix handling of term width
- Fix rendering of annotations between newline and first character
(granted, maybe the caller is wrong)
- Tweak multiline annotation markers
New or upcoming features annotate-snippets features that we will be able
to leverage by moving this forward
- `AnnotationKind::Visible` to improve the quality of built-in
code-folding if Ruff were to switch to it
- `DecorStyle::Unicode`
- *(upcoming)* No-graphiscs mode for screen readers (may also be useful
for AIs)
Deferred:
- Moving related `Group`s into the same `Report`
- Using `secondary_title` for any `Group` after the first in a `Report`
- Using a `Snippet`, instead of titles, for "virtual code" like
https://github.com/astral-sh/ruff/pull/27033#discussion_r3622727236
- Switching hidden snippets to `Origin`
## Test Plan
Within cpython, I ran
```console
$ hyperfine -i "../../ruff/target-baseline/release/ruff check" "../../ruff/target-update/release/ruff check" -N -m20 --output=null
Benchmark 1: ../../ruff/target-baseline/release/ruff check
Time (mean ± σ): 27.5 ms ± 1.1 ms [User: 33.0 ms, System: 108.4 ms]
Range (min … max): 25.0 ms … 31.7 ms 94 runs
Warning: Ignoring non-zero exit code.
Benchmark 2: ../../ruff/target-update/release/ruff check
Time (mean ± σ): 28.1 ms ± 2.0 ms [User: 33.4 ms, System: 105.7 ms]
Range (min … max): 24.8 ms … 38.9 ms 102 runs
Warning: Ignoring non-zero exit code.
Warning: Statistical outliers were detected. Consider re-running this benchmark on a quiet system without any interferences from other programs. It might help to use t
he '--warmup' or '--prepare' options.
Summary
../../ruff/target-baseline/release/ruff check ran
1.03 ± 0.08 times faster than ../../ruff/target-update/release/ruff check
```
Before:
<img width="486" height="583" alt="image"
src="https://github.com/user-attachments/assets/2d94dabf-b28d-48c1-b17c-52aac59fd57e"
/>
After:
<img width="486" height="583" alt="image"
src="https://github.com/user-attachments/assets/b388ada3-e3d7-4ba0-b90b-1330eb81f4be"
/>
These tests are currently split across `assignment/annotations.md` and
`bidirectional.md` somewhat arbitrarily. I merged the two and
reorganized some of the larger snippets which had devolved into
catch-all sections.
Extends https://github.com/astral-sh/ruff/pull/25279 to support
full-scope inference for all unannotated collection literals, even those
that are non-empty, e.g.,
```py
x = [1]
x.append("2")
reveal_type(x) # revealed: list[int | str]
```
## Summary
Add a new lint that detects generic types used without explicit type
parameters in annotations (e.g. `list` instead of `list[int]`).
This is equivalent to mypy's `--disallow-any-generics` and pyright's
`reportMissingTypeArgument`.
Can be enabled via:
```
[rules]
missing-type-argument = "warn"
```
It skips classes where all type parameters have PEP 696 defaults.
This should fix the following issue in ty:
- https://github.com/astral-sh/ty/issues/2442
## Test Plan
Added tests covering stdlib generics, user-defined generics, PEP 696
defaults, dotted names, function signatures, base classes, and variable annotations.
---------
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
Close and reopen this PR to trigger CI
---------
Co-authored-by: typeshedbot <>
Co-authored-by: Micha Reiser <micha@reiser.io>
Co-authored-by: Alex Waygood <alex.waygood@gmail.com>
This is a refactoring in support of
https://github.com/astral-sh/ty/issues/2799. The eventual goal is to use
a `ConstraintSet` to hold the pending specialization being built in
`SpecializationBuilder`. That will automatically cause us to combine
mappings with union or intersection as appropriate.
This PR removes several methods from the `SpecializationBuilder` API:
- `mapped` is removed in favor of a new `build_with` that applies the
mapping while constructing the specialization. The callback is updated
to receive the typevar's lower/upper bound from (eventually) the
constraint set solution. (For now, we just give it both types from the
pending hash map.)
- `infer_reverse` and friends are removed in favor of constructing a
constraint set directly via `when_constraint_set_assignable_to`. The
reverse inference was used to apply our inference logic with the
formal/actual reversed. Constraint set assignability handles that just
fine.
- `type_mappings` and `into_type_mappings` are also removed. These were
used to consume the resut of the `infer_reverse` calls. We can replace
that by consuming the constraint set created by the assignability check.
This requires a `solutions` wrapper that takes in a similar hook
callback as above.
Collection literals are effectively a special case of generic calls, so
there's no reason we shouldn't be applying the same narrowing logic
here.
Part of https://github.com/astral-sh/ty/issues/3001.
## Summary
Part of https://github.com/astral-sh/ty/issues/1240
Stop unioning `Unknown` into the types of un-annotated container
literals.
We discussed perhaps continuing to union `Unknown` if the inferred type
is a singleton type like `None`. I'd like to explore this as a separate
change so we can see the ecosystem impact more clearly.
## Test Plan
Adjusted many mdtest expectations.
There's one test case that regresses with this change, because we don't
fully support union type contexts (it can require a lot of repeat
inference in pathological cases). So `x10: list[int | str] | list[int |
None] = [1, 2, 3]` previously passed only because we inferred the RHS as
`list[Unknown | int]` -- now we infer it as `list[int]` and the
assignment fails due to invariance. I've kept this test as a TODO since
it's not trivial to fix. Mypy errors in the same way we now do,
suggesting it's not necessarily a huge priority either.
## Ecosystem
This change is expected to cause new diagnostics and some false
positives, since we are replacing very-forgiving gradual types with
non-gradual inference heuristics.
Many of these issues could be solved or significantly mitigated by
https://github.com/astral-sh/ty/issues/1473, depending how far we are
able to go with that, and particularly whether we can afford to apply it
also to container literals which are not empty at construction. The
downside of broad application of this approach is that in some cases it
could cause us to widen container types when the user actually just made
a mistake and added the wrong thing to a container, and would prefer an
error at that location.
Some categories of new error that show up in the ecosystem report:
### Implicit TypedDicts
These are cases where the dictionary is heterogeneous and would ideally
be typed as a `TypedDict` but isn't, for example:
```py
def make_person(photo: bytes | None):
person = {"name": "Pat", age: 29}
if photo is not None:
person["photo"] = photo
```
We (and pyrefly, and pyright in strict mode) error on the last line here
because we already inferred `dict[str, str | int]`, so we can't add a
`bytes` value.
Mypy prefers common-base joins over union joins, so it infers `dict[str,
object]`, which avoids the error adding a `bytes` value. This means the
value type is less precise, which theoretically means potentially more
errors using values from the dict later. But in practice with this
heterogeneous pattern, either `object` or the union will cause similar
problems when using values from the dict -- in either case you'd
probably have to cast or narrow.
Pyright (in non-strict mode) has a special case where it falls back to
`Unknown` when it sees heterogenous value types, so it infers this as
`dict[str, Unknown]`.
I think we could consider either the mypy or pyright approaches here,
but we don't need to do it in this PR; we can file an issue and consider
it as a follow-up.
Another symptom of this same root cause is repetitive diagnostics
arising from a large union inferred as value type; the same fixes would
address this.
### Negative intersections, particularly with e.g. `~AlwaysFalsy` or
`~None`.
Example:
```py
class A: ...
def _(a: A | None) -> dict[str, A]:
if a:
d = {"a": a}
return d
return {}
```
We error on `return d` because "expected `dict[str, A]`, found
`dict[str, A & ~AlwaysFalsy]`". This is an issue specific to
intersection types, so no other type checker has this problem.
I think when we "promote literals" (we may need to give this operation a
broader name -- it's really "type promotion to give a better inferred
type when invariance means too-precise is bad") we should also eliminate
all negative types from intersections. I would prefer to do this as a
separate PR for easier review and better visibility of ecosystem impact,
but I think it's high priority to land soon after this PR (ideally
before a release).
### Overly-precise inference for singleton `None`
This did show up, to the tune of ~100 new diagnostics
([example](https://github.com/pytorch/ignite/blob/b73a4c20e991b3e14949f2a69651ed2a7219f2fd/tests/ignite/engine/test_engine.py#L158)),
so I think it is worth addressing as a follow-up.
- Updated the `prek` hook to replace `blacken-docs` with ruff
- Added some formatting directives to preserve obvious intentional
formatting choices
- Made some choice edits to content for better readability with new format
- Formatted md tests and updated snapshots
## Summary
We currently ignore type context that contains inferable type variables.
Instead, we can specialize these to a special marker type which is
ignored when inferring from the type context, while still using the rest
of the type.
Part of https://github.com/astral-sh/ty/issues/2521.
## Summary
The following snippet currently errors because we widen the inferred
type, even though `X` is covariant over `T`. If `T` was contravariant or
invariant, this would be fine, as it would lead to an assignability
error anyways.
```python
class X[T]:
def __init__(self: X[None]): ...
def pop(self) -> T:
raise NotImplementedError
# error: Argument to bound method `__init__` is incorrect: Expected `X[None]`, found `X[int | None]`
x: X[int | None] = X()
```
There are some cases where it is still helpful to prefer covariant
declared types, but this error seems hard to fix otherwise, and makes
our heuristics more consistent overall.
## Summary
This PR takes the improvements we made to unsupported-comparison
diagnostics in https://github.com/astral-sh/ruff/pull/21737, and extends
them to other `unsupported-operator` diagnostics.
## Test Plan
Mdtests and snapshots
## Summary
We now use the type context for a lot of things, so re-inferring without
type context actually makes diagnostics more confusing (in most cases).
## Summary
This PR proposes that we add a new `set_concise_message` functionality
to our `Diagnostic` construction API. When used, the concise message
that is otherwise auto-generated from the main diagnostic message and
the primary annotation will be overwritten with the custom message.
To understand why this is desirable, let's look at the `invalid-key`
diagnostic. This is how I *want* the full diagnostic to look like:
<img width="620" height="282" alt="image"
src="https://github.com/user-attachments/assets/3bf70f52-9d9f-4817-bc16-fb0ebf7c2113"
/>
However, without the change in this PR, the concise message would have
the following form:
```
error[invalid-key]: Unknown key "Age" for TypedDict `Person`: Unknown key "Age" - did you mean "age"?
```
This duplication is why the full `invalid-key` diagnostic used a main
diagnostic message that is only "Invalid key for TypedDict `Person`", to
make that bearable:
```
error[invalid-key] Invalid key for TypedDict `Person`: Unknown key "Age" - did you mean "age"?
```
This is still less than ideal, *and* we had to make the "full"
diagnostic worse. With the new API here, we have to make no such
compromises. We need to do slightly more work (provide one additional
custom-designed message), but we get to keep the "full" diagnostic that
we actually want, and we can make the concise message more terse and
readable:
```
error[invalid-key] Unknown key "Age" for TypedDict `Person` - did you mean "age"?
```
Similar problems exist for other diagnostics as well (I really want this
for https://github.com/astral-sh/ruff/pull/21476). In this PR, I only
changed `invalid-key` and `type-assertion-failure`.
The PR here is somewhat related to the discussion in
https://github.com/astral-sh/ty/issues/1418, but note that we are
solving a problem that is unrelated to sub-diagnostics.
## Test Plan
Updated tests
## Summary
Extends literal promotion to apply to any generic method, as opposed to
only generic class constructors. This PR also improves our literal
promotion heuristics to only promote literals in non-covariant position
in the return type, and avoid promotion if the literal is present in
non-covariant position in any argument type.
Resolves https://github.com/astral-sh/ty/issues/1357.
## Summary
We currently fail to account for the type context when inferring generic
classes constructed with `__new__`, or synthesized `__init__` for
dataclasses.
This manifested as an error when inferring the type of a PEP-695 generic
class via its constructor parameters:
```py
class D[T, U]:
@overload
def __init__(self: "D[str, U]", u: U) -> None: ...
@overload
def __init__(self, t: T, u: U) -> None: ...
def __init__(self, *args) -> None: ...
# revealed: D[Unknown, str]
# SHOULD BE: D[str, str]
reveal_type(D("string"))
```
This manifested because `D` is inferred to be bivariant in both `T` and
`U`. We weren't seeing this in the equivalent example for legacy
typevars, since those default to invariant. (This issue also showed up
for _covariant_ typevars, so this issue was not limited to bivariance.)
The underlying cause was because of a heuristic that we have in our
current constraint solver, which attempts to handle situations like
this:
```py
def f[T](t: T | None): ...
f(None)
```
Here, the `None` argument matches the non-typevar union element, so this
argument should not add any constraints on what `T` can specialize to.
Our previous heuristic would check for this by seeing if the argument
type is a subtype of the parameter annotation as a whole — even if it
isn't a union! That would cause us to erroneously ignore the `self`
parameter in our constructor call, since bivariant classes are
equivalent to each other, regardless of their specializations.
The quick fix is to move this heuristic "down a level", so that we only
apply it when the parameter annotation is a union. This heuristic should
go away completely 🤞 with the new constraint solver.