Commit Graph
5 Commits
Author SHA1 Message Date
Charlie Marsh 2a42ea550b [ty] Clarify incompatible loop declaration regression (#27640)
## Summary

Use an unambiguously incompatible `list[str]` declaration in the
loop-declaration regression. The earlier binding remains `list[int]`,
while the loop assignment now matches the declared type, so the test
isolates the incompatible pre-loop binding.

The previous `list[object]` declaration could become valid under
whole-scope bidirectional inference, making it an ambiguous example for
this diagnostic.

Follow-up to [review feedback on
#27594](https://github.com/astral-sh/ruff/pull/27594#discussion_r3753906101).
2026-08-10 19:15:56 -04:00
Charlie Marsh 3115cba9a4 [ty] Preserve contextual inference for declarations in loops (#27594)
## Summary

Previously, a declaration inside a loop could be validated against a
prior iteration's assignment before that assignment received the
declaration's contextual type:

```python
from typing import TypedDict

class Record(TypedDict):
    value: int

while True:
    record: Record
    record = {"value": 1}
```

The dictionary was inferred as `dict[str, int]`, so we incorrectly
reported `invalid-declaration` and discarded the `TypedDict` context.

We now initialize declaration-only inference cycles with the declared
type when a synthetic loop-header binding is visible.

Ordinary assignments already initialize their cycles directly in
`DefinitionInference::cycle_initial`; for collection literals, this can
seed types such as `list[Divergent]`. Annotated declarations require a
separate builder path because resolving the annotation must respect
postponed evaluation, Python 3.14 forward references, qualifiers,
diagnostics, and metadata. `infer_annotated_assignment_cycle_initial`
therefore infers only the annotation and preserves its builder state
without performing full region inference.

This applies to both `while` and `for` loops and preserves genuine
declaration errors for incompatible pre-loop bindings.

Closes https://github.com/astral-sh/ty/issues/4206.
2026-08-08 13:59:30 -04:00
David Peter 86fd9b634e [ty] Format conflicting types as an enumeration (#18956)
## Summary

Format conflicting declared types as
```
`str`, `int` and `bytes`
```

Thanks to @AlexWaygood for the initial draft.

@dcreager, looking forward to your one-character follow-up PR.
2025-06-26 14:29:33 +02:00
David Peter b01003f81d [ty] Infer nonlocal types as unions of all reachable bindings (#18750)
## Summary

This PR includes a behavioral change to how we infer types for public
uses of symbols within a module. Where we would previously use the type
that a use at the end of the scope would see, we now consider all
reachable bindings and union the results:

```py
x = None

def f():
    reveal_type(x)  # previously `Unknown | Literal[1]`, now `Unknown | None | Literal[1]`

f()

x = 1

f()
```

This helps especially in cases where the the end of the scope is not
reachable:

```py
def outer(x: int):
    def inner():
        reveal_type(x)  # previously `Unknown`, now `int`

    raise ValueError
```

This PR also proposes to skip the boundness analysis of public uses.
This is consistent with the "all reachable bindings" strategy, because
the implicit `x = <unbound>` binding is also always reachable, and we
would have to emit "possibly-unresolved" diagnostics for every public
use otherwise. Changing this behavior allows common use-cases like the
following to type check without any errors:

```py
def outer(flag: bool):
    if flag:
        x = 1

        def inner():
            print(x)  # previously: possibly-unresolved-reference, now: no error
```

closes https://github.com/astral-sh/ty/issues/210
closes https://github.com/astral-sh/ty/issues/607
closes https://github.com/astral-sh/ty/issues/699

## Follow up

It is now possible to resolve the following TODO, but I would like to do
that as a follow-up, because it requires some changes to how we treat
implicit attribute assignments, which could result in ecosystem changes
that I'd like to see separately.


https://github.com/astral-sh/ruff/blob/315fb0f3da4e5f2097a294c344025dec28ebf2a5/crates/ty_python_semantic/src/semantic_index/builder.rs#L1095-L1117

## Ecosystem analysis

[**Full report**](https://shark.fish/diff-public-types.html)

* This change obviously removes a lot of `possibly-unresolved-reference`
diagnostics (7818) because we do not analyze boundness for public uses
of symbols inside modules anymore.
* As the primary goal here, this change also removes a lot of
false-positive `unresolved-reference` diagnostics (231) in scenarios
like this:
    ```py
    def _(flag: bool):
        if flag:
            x = 1
    
            def inner():
                x
    
            raise
    ```
* This change also introduces some new false positives for cases like:
    ```py
    def _():
        x = None
    
        x = "test"
    
        def inner():
x.upper() # Attribute `upper` on type `Unknown | None | Literal["test"]`
is possibly unbound
    ```
We have test cases for these situations and it's plausible that we can
improve this in a follow-up.


## Test Plan

New Markdown tests
2025-06-26 12:24:40 +02:00
Micha Reiser b51c4f82ea Rename Red Knot (#17820) 2025-05-03 19:49:15 +02:00