Skip to content

Commit 6adb727

Browse files
committed
Add vm.finalize and enter/run docs
1 parent 6eed8f4 commit 6adb727

1 file changed

Lines changed: 37 additions & 5 deletions

File tree

‎vm/src/vm/interpreter.rs‎

Lines changed: 37 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
use super::{setting::Settings, thread, Context, VirtualMachine};
22
use crate::{
33
stdlib::{atexit, sys},
4+
vm::PyBaseExceptionRef,
45
PyResult,
56
};
67
use std::sync::atomic::Ordering;
@@ -59,26 +60,57 @@ impl Interpreter {
5960
Self { vm }
6061
}
6162

63+
/// Run a function with the main virtual machine and return a PyResult of the result.
64+
///
65+
/// To enter vm context multiple times or to avoid buffer/exception management, this function is preferred.
66+
/// `enter` is lightweight and it returns a python object in PyResult.
67+
/// You can stop or continue the execution multiple times by calling `enter`.
68+
///
69+
/// To finalize the vm once all desired `enter`s are called, calling `finalize` will be helpful.
70+
///
71+
/// See also [`run`] for managed way to run the interpreter.
6272
pub fn enter<F, R>(&self, f: F) -> R
6373
where
6474
F: FnOnce(&VirtualMachine) -> R,
6575
{
6676
thread::enter_vm(&self.vm, || f(&self.vm))
6777
}
6878

79+
/// Run a function with the main virtual machine and return exit code.
80+
///
81+
/// To enter vm context only once and safely terminate the vm, this function is preferred.
82+
/// Unlike [`enter`], `run` calls finalize and returns exit code.
83+
/// You will not be able to obtain Python exception in this way.
84+
///
85+
/// See [`finalize`] for the finalization steps.
86+
/// See also [`enter`] for pure function call to obtain Python exception.
6987
pub fn run<F, R>(self, f: F) -> u8
7088
where
7189
F: FnOnce(&VirtualMachine) -> PyResult<R>,
7290
{
91+
let res = self.enter(|vm| f(vm));
92+
self.finalize(res.err())
93+
}
94+
95+
/// Finalize vm and turns an exception to exit code.
96+
///
97+
/// Finalization steps including 4 steps:
98+
/// 1. Flush stdout and stderr.
99+
/// 1. Handle exit exception and turn it to exit code.
100+
/// 1. Run atexit exit functions.
101+
/// 1. Mark vm as finalized.
102+
///
103+
/// Note that calling `finalize` is not necessary by purpose though.
104+
pub fn finalize(self, exc: Option<PyBaseExceptionRef>) -> u8 {
73105
self.enter(|vm| {
74-
let res = f(vm);
75106
flush_std(vm);
76107

77108
// See if any exception leaked out:
78-
let exit_code = res
79-
.map(|_| 0)
80-
.map_err(|exc| vm.handle_exit_exception(exc))
81-
.unwrap_or_else(|code| code);
109+
let exit_code = if let Some(exc) = exc {
110+
vm.handle_exit_exception(exc)
111+
} else {
112+
0
113+
};
82114

83115
atexit::_run_exitfuncs(vm);
84116

0 commit comments

Comments
 (0)