[ty] more cases for the class body global fallback
Some checks are pending
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 build (msrv) (push) Blocked by required conditions
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

This commit is contained in:
Jack O'Connor 2025-08-06 11:14:20 -07:00
parent 462adfd0e6
commit 827456f977
5 changed files with 69 additions and 34 deletions

View file

@ -75,7 +75,7 @@ class _:
if cond(): if cond():
a = A() a = A()
reveal_type(a.x) # revealed: int | None reveal_type(a.x) # revealed: int | None | Unknown
reveal_type(a.y) # revealed: Unknown | None reveal_type(a.y) # revealed: Unknown | None
reveal_type(a.z) # revealed: Unknown | None reveal_type(a.z) # revealed: Unknown | None

View file

@ -269,6 +269,8 @@ If we try to access a variable in a class before it has been defined, the lookup
global. global.
```py ```py
import secrets
x: str = "a" x: str = "a"
def f(x: int, y: int): def f(x: int, y: int):
@ -286,4 +288,23 @@ def f(x: int, y: int):
# error: [unresolved-reference] # error: [unresolved-reference]
reveal_type(y) # revealed: Unknown reveal_type(y) # revealed: Unknown
y = None y = None
# Declarations count as definitions, even if there's no binding.
class F:
reveal_type(x) # revealed: str
x: int
reveal_type(x) # revealed: str
# Explicitly `nonlocal` variables don't count, even if they're bound.
class G:
nonlocal x
reveal_type(x) # revealed: int
x = 42
reveal_type(x) # revealed: Literal[42]
# Possibly-unbound variables get unioned with the fallback lookup.
class H:
if secrets.randbelow(2):
x = None
reveal_type(x) # revealed: None | str
``` ```

View file

@ -34,7 +34,7 @@ class C:
if coinflip(): if coinflip():
x = 1 x = 1
# error: [possibly-unresolved-reference] # Possibly unbound variables in enclosing scopes are considered bound.
y = x y = x
reveal_type(C.y) # revealed: Unknown | Literal[1, "abc"] reveal_type(C.y) # revealed: Unknown | Literal[1, "abc"]

View file

@ -80,6 +80,38 @@ impl Symbol {
self.flags.contains(SymbolFlags::MARKED_NONLOCAL) self.flags.contains(SymbolFlags::MARKED_NONLOCAL)
} }
/// Is the symbol defined in this scope, vs referring to some enclosing scope?
///
/// There are three common cases where a name refers to an enclosing scope:
///
/// 1. explicit `global` variables
/// 2. explicit `nonlocal` variables
/// 3. "free" variables, which are used in a scope where they're neither bound nor declared
///
/// Note that even if `is_local` is false, that doesn't necessarily mean there's an enclosing
/// scope that resolves the reference. The symbol could be a built-in like `print`, or a name
/// error at runtime, or a global variable added dynamically with e.g. `globals()`.
///
/// XXX: There's a fourth case that we don't (can't) handle here. A variable that's bound or
/// declared (anywhere) in a class body, but used before it's bound (at runtime), resolves
/// (unbelievably) to the global scope. For example:
/// ```py
/// x = 42
/// def f():
/// x = 43
/// class Foo:
/// print(x) # 42 (never 43)
/// if secrets.randbelow(2):
/// x = 44
/// print(x) # 42 or 44
/// ```
/// In cases like this, the resolution isn't known until runtime, and in fact it varies from
/// one use to the next. The semantic index alone can't resolve this, and instead it's a
/// special case in type inference (see `infer_place_load`).
pub(crate) fn is_local(&self) -> bool {
!self.is_global() && !self.is_nonlocal() && (self.is_bound() || self.is_declared())
}
pub(crate) const fn is_reassigned(&self) -> bool { pub(crate) const fn is_reassigned(&self) -> bool {
self.flags.contains(SymbolFlags::IS_REASSIGNED) self.flags.contains(SymbolFlags::IS_REASSIGNED)
} }

View file

@ -6664,30 +6664,19 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
if let Some(use_id) = use_id { if let Some(use_id) = use_id {
constraint_keys.push((file_scope_id, ConstraintKey::UseId(use_id))); constraint_keys.push((file_scope_id, ConstraintKey::UseId(use_id)));
} }
let local_is_unbound = local_scope_place.is_unbound();
let place = PlaceAndQualifiers::from(local_scope_place).or_fall_back_to(db, || { let place = PlaceAndQualifiers::from(local_scope_place).or_fall_back_to(db, || {
let has_bindings_in_this_scope = match place_table.place_id(place_expr) {
Some(place_id) => place_table.place(place_id).is_bound(),
None => {
assert!(
self.deferred_state.in_string_annotation(),
"Expected the place table to create a place for every Name node"
);
false
}
};
let current_file = self.file(); let current_file = self.file();
let mut symbol_resolves_locally = false;
let mut is_nonlocal_binding = false;
if let Some(symbol) = place_expr.as_symbol() { if let Some(symbol) = place_expr.as_symbol() {
if let Some(symbol_id) = place_table.symbol_id(symbol.name()) { if let Some(symbol_id) = place_table.symbol_id(symbol.name()) {
// If we try to access a variable in a class before it has been defined, // Footgun: `place_expr` and `symbol` were probably constructed with all-zero
// the lookup will fall back to global. // flags. We need to read the place table to get correct flags.
let fallback_to_global = local_is_unbound symbol_resolves_locally = place_table.symbol(symbol_id).is_local();
&& has_bindings_in_this_scope // If we try to access a variable in a class before it has been defined, the
&& scope.node(db).scope_kind().is_class(); // lookup will fall back to global. See the comment on `Symbol::is_local`.
let fallback_to_global =
scope.node(db).scope_kind().is_class() && symbol_resolves_locally;
if self.skip_non_global_scopes(file_scope_id, symbol_id) || fallback_to_global { if self.skip_non_global_scopes(file_scope_id, symbol_id) || fallback_to_global {
return global_symbol(self.db(), self.file(), symbol.name()).map_type( return global_symbol(self.db(), self.file(), symbol.name()).map_type(
|ty| { |ty| {
@ -6699,22 +6688,15 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
}, },
); );
} }
is_nonlocal_binding = self
.index
.symbol_is_nonlocal_in_scope(symbol_id, file_scope_id);
} }
} }
// If it's a function-like scope and there is one or more binding in this scope (but // Symbols that are bound or declared in the local scope, and not marked `nonlocal` or
// none of those bindings are visible from where we are in the control flow), we cannot // `global`, never refer to an enclosing scope. (If you reference such a symbol before
// fallback to any bindings in enclosing scopes. As such, we can immediately short-circuit // it's bound, you get an `UnboundLocalError`.) Short-circuit instead of walking
// here and return `Place::Unbound`. // enclosing scopes in this case. The one exception to this rule is the global fallback
// // in class bodies, which we already handled above.
// This is because Python is very strict in its categorisation of whether a variable is if symbol_resolves_locally {
// a local variable or not in function-like scopes. If a variable has any bindings in a
// function-like scope, it is considered a local variable; it never references another
// scope. (At runtime, it would use the `LOAD_FAST` opcode.)
if has_bindings_in_this_scope && scope.is_function_like(db) && !is_nonlocal_binding {
return Place::Unbound.into(); return Place::Unbound.into();
} }