Skip to content

Commit 84d7afc

Browse files
authored
Preserve enclosing free variables in class scopes (#9444)
Assisted-by: Codex:GPT-6
1 parent 099fbeb commit 84d7afc

2 files changed

Lines changed: 32 additions & 1 deletion

File tree

‎crates/codegen/src/symboltable.rs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -740,6 +740,9 @@ impl SymbolTableAnalyzer {
740740

741741
// Analyze symbols in current scope
742742
let function_like_scope = SymbolTableBuilder::is_function_like_scope(symbol_table.typ);
743+
// Class implicit cells satisfy child requests, not this scope's own
744+
// closure. Keep its free names out of drop_class_free().
745+
let mut scope_free = IndexSet::default();
743746
for symbol in symbol_table.symbols.values_mut() {
744747
self.analyze_symbol(
745748
symbol,
@@ -760,7 +763,7 @@ impl SymbolTableAnalyzer {
760763
if symbol.scope == SymbolScope::Free
761764
|| symbol.flags.contains(SymbolFlags::DEF_FREE_CLASS)
762765
{
763-
newfree.insert(symbol.name.clone());
766+
scope_free.insert(symbol.name.clone());
764767
}
765768
}
766769

@@ -797,6 +800,7 @@ impl SymbolTableAnalyzer {
797800
}
798801
}
799802

803+
newfree.extend(scope_free);
800804
Ok(newfree)
801805
}
802806

‎extra_tests/snippets/syntax_annotations.py‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
from typing import get_type_hints
22

3+
from testutils import assert_raises
4+
35
# Future f-string annotations canonicalize fields, not their literal padding.
46
for formatted, expected in (
57
("f'{ value }'", "f'{value}'"),
@@ -33,3 +35,28 @@ def func(s: str) -> int:
3335
"from __future__ import annotations\nx: " + template, "<test>", "exec"
3436
)
3537
assert expected in annotation_code.co_consts
38+
39+
40+
# Conditional annotations belong to the inner class, not an enclosing scope.
41+
for future in ("", "from __future__ import annotations\n"):
42+
namespace = {}
43+
exec(
44+
future
45+
+ """
46+
class Outer:
47+
class Inner:
48+
if True:
49+
included: int
50+
if False:
51+
omitted: str
52+
""",
53+
namespace,
54+
)
55+
assert get_type_hints(namespace["Outer"].Inner) == {"included": int}
56+
57+
with assert_raises(SyntaxError):
58+
compile(
59+
"class C:\n if True: x: int\n global __conditional_annotations__",
60+
"<test>",
61+
"exec",
62+
)

0 commit comments

Comments
 (0)