|
1 | 1 | use super::{setting::Settings, thread, Context, VirtualMachine}; |
2 | 2 | use crate::{ |
3 | 3 | stdlib::{atexit, sys}, |
| 4 | + vm::PyBaseExceptionRef, |
4 | 5 | PyResult, |
5 | 6 | }; |
6 | 7 | use std::sync::atomic::Ordering; |
@@ -59,26 +60,57 @@ impl Interpreter { |
59 | 60 | Self { vm } |
60 | 61 | } |
61 | 62 |
|
| 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. |
62 | 72 | pub fn enter<F, R>(&self, f: F) -> R |
63 | 73 | where |
64 | 74 | F: FnOnce(&VirtualMachine) -> R, |
65 | 75 | { |
66 | 76 | thread::enter_vm(&self.vm, || f(&self.vm)) |
67 | 77 | } |
68 | 78 |
|
| 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. |
69 | 87 | pub fn run<F, R>(self, f: F) -> u8 |
70 | 88 | where |
71 | 89 | F: FnOnce(&VirtualMachine) -> PyResult<R>, |
72 | 90 | { |
| 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 { |
73 | 105 | self.enter(|vm| { |
74 | | - let res = f(vm); |
75 | 106 | flush_std(vm); |
76 | 107 |
|
77 | 108 | // 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 | + }; |
82 | 114 |
|
83 | 115 | atexit::_run_exitfuncs(vm); |
84 | 116 |
|
|
0 commit comments