Skip to content

Commit a04edb1

Browse files
committed
apply reviews
1 parent f4674b6 commit a04edb1

4 files changed

Lines changed: 136 additions & 58 deletions

File tree

‎crates/codegen/src/symboltable.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2226,8 +2226,8 @@ impl SymbolTableBuilder {
22262226

22272227
// PEP 709: Mark non-generator comprehensions for inlining.
22282228
// CPython's symtable marks all non-generator comprehensions for
2229-
// inlining, except annotation scopes nested in classes that can see
2230-
// class scope.
2229+
// inlining, except scopes nested under a parent that can see class
2230+
// scope (for example annotation scopes inside classes).
22312231
if !is_generator {
22322232
let parent = self.tables.iter().rev().nth(1);
22332233
let parent_can_see_class = parent.is_some_and(|t| t.can_see_class_scope);

‎crates/vm/src/builtins/frame.rs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -454,7 +454,7 @@ impl Frame {
454454

455455
#[pygetset]
456456
fn f_locals(&self, vm: &VirtualMachine) -> PyResult {
457-
let result = self.locals(vm).map(Into::into);
457+
let result = self.f_locals_mapping(vm).map(Into::into);
458458
self.locals_dirty
459459
.store(true, core::sync::atomic::Ordering::Release);
460460
result
@@ -703,6 +703,7 @@ impl Py<Frame> {
703703

704704
// Clear temporary refs
705705
self.temporary_refs.lock().clear();
706+
self.f_locals_hidden_overlay.lock().take();
706707

707708
Ok(())
708709
}

‎crates/vm/src/frame.rs‎

Lines changed: 77 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ use crate::{
3030
function::{ArgMapping, Either, FuncArgs, PyMethodFlags},
3131
object::PyAtomicBorrow,
3232
object::{Traverse, TraverseFn},
33-
protocol::{PyIter, PyIterReturn},
33+
protocol::{PyIter, PyIterReturn, PyMapping},
3434
scope::Scope,
3535
sliceable::SliceableSequenceOp,
3636
stdlib::{_typing, builtins, sys::monitoring},
@@ -609,6 +609,9 @@ pub struct InterpreterFrame {
609609
pub(crate) owner: atomic::AtomicI8,
610610
/// Set when f_locals is accessed. Cleared after locals_to_fast() sync.
611611
pub(crate) locals_dirty: atomic::AtomicBool,
612+
/// Persistent overlay for `frame.f_locals` when hidden locals need a
613+
/// snapshot separate from the backing locals mapping.
614+
pub(crate) f_locals_hidden_overlay: PyMutex<Option<PyDictRef>>,
612615
/// Number of stack entries to pop after set_f_lineno returns to the
613616
/// execution loop. set_f_lineno cannot pop directly because the
614617
/// execution loop holds the state mutex.
@@ -660,6 +663,7 @@ unsafe impl Traverse for Frame {
660663
iframe.builtins.traverse(tracer_fn);
661664
iframe.trace.traverse(tracer_fn);
662665
iframe.temporary_refs.traverse(tracer_fn);
666+
iframe.f_locals_hidden_overlay.traverse(tracer_fn);
663667
}
664668
}
665669

@@ -739,6 +743,7 @@ impl Frame {
739743
previous: AtomicPtr::new(core::ptr::null_mut()),
740744
owner: atomic::AtomicI8::new(FrameOwner::FrameObject as i8),
741745
locals_dirty: atomic::AtomicBool::new(false),
746+
f_locals_hidden_overlay: PyMutex::new(None),
742747
pending_stack_pops: Default::default(),
743748
pending_unwind_from_stack: Default::default(),
744749
};
@@ -797,6 +802,7 @@ impl Frame {
797802
for slot in fastlocals.iter_mut() {
798803
*slot = None;
799804
}
805+
self.f_locals_hidden_overlay.lock().take();
800806
}
801807

802808
/// Get cell contents by localsplus index.
@@ -865,9 +871,16 @@ impl Frame {
865871
return Ok(());
866872
}
867873
let code = &**self.code;
874+
let overlay_locals = self
875+
.has_active_hidden_locals()
876+
.then(|| self.f_locals_hidden_overlay.lock().clone())
877+
.flatten()
878+
.map(ArgMapping::from_dict_exact);
879+
let locals_map = overlay_locals
880+
.as_ref()
881+
.map_or_else(|| self.locals.mapping(vm), ArgMapping::mapping);
868882
// SAFETY: Called before generator resume; no concurrent access.
869883
let fastlocals = unsafe { (*self.iframe.get()).localsplus.fastlocals_mut() };
870-
let locals_map = self.locals.mapping(vm);
871884
for (i, &varname) in code.varnames.iter().enumerate() {
872885
if i >= fastlocals.len() {
873886
break;
@@ -882,23 +895,12 @@ impl Frame {
882895
Ok(())
883896
}
884897

885-
pub fn locals(&self, vm: &VirtualMachine) -> PyResult<ArgMapping> {
886-
use rustpython_compiler_core::bytecode::{
887-
CO_FAST_CELL, CO_FAST_FREE, CO_FAST_HIDDEN, CO_FAST_LOCAL,
888-
};
889-
// SAFETY: Either the frame is not executing (caller checked owner),
890-
// or we're in a trace callback on the same thread that's executing.
891-
let locals = &self.locals;
898+
fn has_active_hidden_locals(&self) -> bool {
899+
use rustpython_compiler_core::bytecode::{CO_FAST_CELL, CO_FAST_FREE, CO_FAST_HIDDEN};
892900
let code = &**self.code;
893-
let locals_map = locals.mapping(vm);
894901
let fastlocals = unsafe { (*self.iframe.get()).localsplus.fastlocals() };
895-
896-
// Iterate through all localsplus slots using localspluskinds
897-
let nlocalsplus = code.localspluskinds.len();
898-
let nfrees = code.freevars.len();
899-
let free_start = nlocalsplus - nfrees;
900902
let is_optimized = code.flags.contains(bytecode::CodeFlags::OPTIMIZED);
901-
let has_active_hidden_locals = !is_optimized
903+
!is_optimized
902904
&& code.localspluskinds.iter().enumerate().any(|(i, &kind)| {
903905
if kind & CO_FAST_HIDDEN == 0 {
904906
return false;
@@ -914,16 +916,27 @@ impl Frame {
914916
}
915917
}
916918
}
917-
});
918-
let overlay_locals = if has_active_hidden_locals {
919-
// Match CPython's PyEval_GetLocals() behavior for frames with
920-
// PEP 709 hidden locals: locals() inside an inlined comprehension
921-
// returns a snapshot of the active fast locals only, not the
922-
// backing module/class/eval mapping.
923-
Some(vm.ctx.new_dict())
924-
} else {
925-
None
919+
})
920+
}
921+
922+
fn sync_visible_locals_to_mapping(
923+
&self,
924+
locals_map: PyMapping<'_>,
925+
vm: &VirtualMachine,
926+
) -> PyResult<()> {
927+
use rustpython_compiler_core::bytecode::{
928+
CO_FAST_CELL, CO_FAST_FREE, CO_FAST_HIDDEN, CO_FAST_LOCAL,
926929
};
930+
// SAFETY: Either the frame is not executing (caller checked owner),
931+
// or we're in a trace callback on the same thread that's executing.
932+
let code = &**self.code;
933+
let fastlocals = unsafe { (*self.iframe.get()).localsplus.fastlocals() };
934+
935+
// Iterate through all localsplus slots using localspluskinds
936+
let nlocalsplus = code.localspluskinds.len();
937+
let nfrees = code.freevars.len();
938+
let free_start = nlocalsplus - nfrees;
939+
let is_optimized = code.flags.contains(bytecode::CodeFlags::OPTIMIZED);
927940

928941
// Track which non-merged cellvar index we're at
929942
let mut nonmerged_cell_idx = 0;
@@ -1001,24 +1014,52 @@ impl Frame {
10011014
fastlocals[i].clone()
10021015
};
10031016

1004-
let result = if let Some(dict) = &overlay_locals {
1005-
match value {
1006-
Some(value) => dict.set_item(name, value, vm),
1007-
None => dict.del_item(name, vm),
1008-
}
1009-
} else {
1010-
locals_map.ass_subscript(name, value, vm)
1011-
};
1017+
let result = locals_map.ass_subscript(name, value, vm);
10121018
match result {
10131019
Ok(()) => {}
10141020
Err(e) if e.fast_isinstance(vm.ctx.exceptions.key_error) => {}
10151021
Err(e) => return Err(e),
10161022
}
10171023
}
1018-
if let Some(dict) = overlay_locals {
1019-
Ok(ArgMapping::from_dict_exact(dict))
1024+
Ok(())
1025+
}
1026+
1027+
pub fn f_locals_mapping(&self, vm: &VirtualMachine) -> PyResult<ArgMapping> {
1028+
if !self.has_active_hidden_locals() {
1029+
self.f_locals_hidden_overlay.lock().take();
1030+
return self.locals(vm);
1031+
}
1032+
1033+
let needs_refresh = !self.locals_dirty.load(atomic::Ordering::Acquire);
1034+
let overlay_dict = {
1035+
let mut overlay = self.f_locals_hidden_overlay.lock();
1036+
match overlay.as_ref() {
1037+
Some(dict) => dict.clone(),
1038+
None => {
1039+
let dict = vm.ctx.new_dict();
1040+
*overlay = Some(dict.clone());
1041+
dict
1042+
}
1043+
}
1044+
};
1045+
if needs_refresh {
1046+
PyDict::clear(&overlay_dict);
1047+
let overlay = ArgMapping::from_dict_exact(overlay_dict.clone());
1048+
self.sync_visible_locals_to_mapping(overlay.mapping(), vm)?;
1049+
}
1050+
Ok(ArgMapping::from_dict_exact(overlay_dict))
1051+
}
1052+
1053+
pub fn locals(&self, vm: &VirtualMachine) -> PyResult<ArgMapping> {
1054+
if self.has_active_hidden_locals() {
1055+
// Match CPython's locals() behavior for frames with PEP 709 hidden
1056+
// locals: return a fresh snapshot instead of the backing mapping.
1057+
let overlay = ArgMapping::from_dict_exact(vm.ctx.new_dict());
1058+
self.sync_visible_locals_to_mapping(overlay.mapping(), vm)?;
1059+
Ok(overlay)
10201060
} else {
1021-
Ok(locals.clone_mapping(vm))
1061+
self.sync_visible_locals_to_mapping(self.locals.mapping(vm), vm)?;
1062+
Ok(self.locals.clone_mapping(vm))
10221063
}
10231064
}
10241065
}

‎scripts/compare_bytecode.py‎

Lines changed: 55 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
PROJECT_ROOT = os.path.dirname(SCRIPT_DIR)
2626
DIS_DUMP = os.path.join(SCRIPT_DIR, "dis_dump.py")
2727
DEFAULT_REPORT = os.path.join(PROJECT_ROOT, "compare_bytecode.report")
28+
DUMP_TIMEOUT = 600
2829

2930

3031
def find_rustpython():
@@ -69,13 +70,15 @@ def _start_one(interpreter, targets, base_dir):
6970
if interpreter != sys.executable:
7071
env["RUSTPYTHONPATH"] = base_dir
7172

72-
files_file = tempfile.NamedTemporaryFile(
73-
mode="w", encoding="utf-8", delete=False, dir=PROJECT_ROOT
74-
)
75-
output_file = tempfile.NamedTemporaryFile(
76-
mode="w", encoding="utf-8", delete=False, dir=PROJECT_ROOT
77-
)
73+
files_file = None
74+
output_file = None
7875
try:
76+
files_file = tempfile.NamedTemporaryFile(
77+
mode="w", encoding="utf-8", delete=False, dir=PROJECT_ROOT
78+
)
79+
output_file = tempfile.NamedTemporaryFile(
80+
mode="w", encoding="utf-8", delete=False, dir=PROJECT_ROOT
81+
)
7982
for _, path in targets:
8083
files_file.write(path)
8184
files_file.write("\n")
@@ -109,8 +112,14 @@ def _start_one(interpreter, targets, base_dir):
109112
"base_dir": base_dir,
110113
}
111114
except Exception:
112-
os.unlink(files_file.name)
113-
os.unlink(output_file.name)
115+
for handle in (files_file, output_file):
116+
if handle is None:
117+
continue
118+
try:
119+
handle.close()
120+
finally:
121+
if os.path.exists(handle.name):
122+
os.unlink(handle.name)
114123
raise
115124

116125

@@ -130,19 +139,18 @@ def _load_dump_output(output_file):
130139
return None
131140

132141

133-
def _run_sync_dump(interpreter, targets, base_dir, timeout=600):
142+
def _run_sync_dump(interpreter, targets, base_dir, timeout=DUMP_TIMEOUT):
134143
job = _start_one(interpreter, targets, base_dir)
135144
proc = job["proc"]
145+
stdout = b""
146+
timed_out = False
136147
try:
137-
stdout = proc.communicate(timeout=600)[0]
148+
stdout = proc.communicate(timeout=timeout)[0]
138149
except subprocess.TimeoutExpired:
139150
proc.kill()
140151
proc.communicate()
141-
print(" Timeout (600s)", file=sys.stderr)
142-
stdout = b""
152+
print(f" Timeout ({timeout}s)", file=sys.stderr)
143153
timed_out = True
144-
finally:
145-
timed_out = locals().get("timed_out", False)
146154

147155
try:
148156
data = _load_dump_output(job["output_file"])
@@ -163,24 +171,52 @@ def _run_sync_dump(interpreter, targets, base_dir, timeout=600):
163171

164172
def _rerun_missing_targets(interpreter, targets, base_dir):
165173
recovered = {}
174+
failed = []
175+
empty = []
166176
for target in targets:
177+
relpath = target[0]
167178
data = _run_sync_dump(interpreter, [target], base_dir)
168-
if data:
179+
if data is None:
180+
failed.append(relpath)
181+
recovered[relpath] = {
182+
"status": "error",
183+
"error": "dump helper failed while rerunning target",
184+
}
185+
elif data:
169186
recovered.update(data)
187+
else:
188+
empty.append(relpath)
189+
recovered[relpath] = {
190+
"status": "error",
191+
"error": "dump helper produced no data while rerunning target",
192+
}
193+
if failed:
194+
print(
195+
" Warning: rerun failed for %d file(s): %s"
196+
% (len(failed), ", ".join(failed[:5])),
197+
file=sys.stderr,
198+
)
199+
if empty:
200+
print(
201+
" Warning: rerun produced no data for %d file(s): %s"
202+
% (len(empty), ", ".join(empty[:5])),
203+
file=sys.stderr,
204+
)
170205
return recovered
171206

172207

173-
def _finish_one(job):
208+
def _finish_one(job, timeout=DUMP_TIMEOUT):
174209
"""Wait for a single dis_dump.py process and return parsed JSON."""
175210
proc = job["proc"]
176211
expected = {relpath for relpath, _ in job["targets"]}
212+
stdout = b""
177213
try:
178-
stdout = proc.communicate(timeout=600)[0]
214+
stdout = proc.communicate(timeout=timeout)[0]
179215
except subprocess.TimeoutExpired:
180216
proc.kill()
181217
proc.communicate()
182218
print(
183-
" Timeout (600s), retrying %d file(s) serially" % len(job["targets"]),
219+
f" Timeout ({timeout}s), retrying {len(job['targets'])} file(s) serially",
184220
file=sys.stderr,
185221
)
186222
data = None
@@ -194,7 +230,7 @@ def _finish_one(job):
194230
if proc.returncode != 0:
195231
print(" Warning: exited with code %d" % proc.returncode, file=sys.stderr)
196232

197-
stray = stdout.decode(errors="replace").strip() if "stdout" in locals() else ""
233+
stray = stdout.decode(errors="replace").strip()
198234
if stray:
199235
print(" Warning: unexpected stdout from dump helper", file=sys.stderr)
200236

0 commit comments

Comments
 (0)