Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Fix stack error when with-statement __exit__ raises exception #5273

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 25, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 21 additions & 4 deletions vm/src/frame.rs
Original file line number Diff line number Diff line change
Expand Up @@ -925,15 +925,15 @@ impl ExecutingFrame<'_> {
_ => None,
};

let exit = self.pop_value();
let exit = self.top_value();

let args = if let Some(exc) = exc {
vm.split_exception(exc)
} else {
(vm.ctx.none(), vm.ctx.none(), vm.ctx.none())
};
let exit_res = exit.call(args, vm)?;
self.push_value(exit_res);
self.replace_top(exit_res);

Ok(None)
}
Expand Down Expand Up @@ -994,7 +994,7 @@ impl ExecutingFrame<'_> {
}
bytecode::Instruction::GetANext => {
let aiter = self.top_value();
let awaitable = vm.call_special_method(&aiter, identifier!(vm, __anext__), ())?;
let awaitable = vm.call_special_method(aiter, identifier!(vm, __anext__), ())?;
let awaitable = if awaitable.payload_is::<PyCoroutine>() {
awaitable
} else {
Expand Down Expand Up @@ -1911,8 +1911,18 @@ impl ExecutingFrame<'_> {
});
}

#[track_caller]
fn pop_block(&mut self) -> Block {
let block = self.state.blocks.pop().expect("No more blocks to pop!");
#[cfg(debug_assertions)]
if self.state.stack.len() < block.level {
dbg!(&self);
panic!(
"stack size reversion: current size({}) < truncates target({}).",
self.state.stack.len(),
block.level
);
}
self.state.stack.truncate(block.level);
block
}
Expand Down Expand Up @@ -1945,7 +1955,14 @@ impl ExecutingFrame<'_> {
}

#[inline]
#[track_caller] // not a real track_caller but pop_value is not very useful
fn replace_top(&mut self, mut top: PyObjectRef) -> PyObjectRef {
let last = self.state.stack.last_mut().unwrap();
std::mem::swap(&mut top, last);
top
}

#[inline]
#[track_caller] // not a real track_caller but top_value is not very useful
fn top_value(&self) -> &PyObject {
match &*self.state.stack {
[.., last] => last,
Expand Down