[ty] perform type narrowing for places marked global too (#19381)
Some checks are pending
CI / cargo build (msrv) (push) Blocked by required conditions
CI / Determine changes (push) Waiting to run
CI / cargo fmt (push) Waiting to run
CI / cargo clippy (push) Blocked by required conditions
CI / cargo test (linux) (push) Blocked by required conditions
CI / cargo test (linux, release) (push) Blocked by required conditions
CI / cargo test (windows) (push) Blocked by required conditions
CI / cargo test (wasm) (push) Blocked by required conditions
CI / cargo build (release) (push) Waiting to run
CI / cargo fuzz build (push) Blocked by required conditions
CI / fuzz parser (push) Blocked by required conditions
CI / test scripts (push) Blocked by required conditions
CI / ecosystem (push) Blocked by required conditions
CI / Fuzz for new ty panics (push) Blocked by required conditions
CI / cargo shear (push) Blocked by required conditions
CI / python package (push) Waiting to run
CI / pre-commit (push) Waiting to run
CI / mkdocs (push) Waiting to run
CI / formatter instabilities and black similarity (push) Blocked by required conditions
CI / test ruff-lsp (push) Blocked by required conditions
CI / check playground (push) Blocked by required conditions
CI / benchmarks-instrumented (push) Blocked by required conditions
CI / benchmarks-walltime (push) Blocked by required conditions
[ty Playground] Release / publish (push) Waiting to run

Fixes https://github.com/astral-sh/ty/issues/311.
This commit is contained in:
Jack O'Connor 2025-07-22 16:42:10 -07:00 committed by GitHub
parent dc10ab81bd
commit ba070bb6d5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 20 additions and 1 deletions

View file

@ -71,6 +71,19 @@ def f():
reveal_type(x) # revealed: Literal[1]
```
Same for an `if` statement:
```py
x: int | None
def f():
# The `global` keyword isn't necessary here, but this is testing that it doesn't get in the way
# of narrowing.
global x
if x == 1:
y: int = x # allowed, because x cannot be None in this branch
```
## `nonlocal` and `global`
A binding cannot be both `nonlocal` and `global`. This should emit a semantic syntax error. CPython

View file

@ -6377,7 +6377,13 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
if let Some(name) = expr.as_name() {
if let Some(symbol_id) = place_table.place_id_by_name(name) {
if self.skip_non_global_scopes(file_scope_id, symbol_id) {
return global_symbol(self.db(), self.file(), name);
return global_symbol(self.db(), self.file(), name).map_type(|ty| {
self.narrow_place_with_applicable_constraints(
expr,
ty,
&constraint_keys,
)
});
}
is_nonlocal_binding = self
.index