Skip to content

Commit 8df1f07

Browse files
committed
InterpreterConfig
1 parent 597ad01 commit 8df1f07

File tree

3 files changed

+484
-416
lines changed

3 files changed

+484
-416
lines changed

src/interpreter.rs

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
use rustpython_vm::{Interpreter, Settings, VirtualMachine};
2+
3+
pub type InitHook = Box<dyn FnOnce(&mut VirtualMachine)>;
4+
5+
#[derive(Default)]
6+
pub struct InterpreterConfig {
7+
settings: Option<Settings>,
8+
init_hooks: Vec<InitHook>,
9+
}
10+
11+
impl InterpreterConfig {
12+
pub fn new() -> Self {
13+
Self::default()
14+
}
15+
pub fn interpreter(self) -> Interpreter {
16+
let settings = self.settings.unwrap_or_default();
17+
Interpreter::with_init(settings, |vm| {
18+
for hook in self.init_hooks {
19+
hook(vm);
20+
}
21+
})
22+
}
23+
24+
pub fn settings(mut self, settings: Settings) -> Self {
25+
self.settings = Some(settings);
26+
self
27+
}
28+
pub fn init_hook(mut self, hook: InitHook) -> Self {
29+
self.init_hooks.push(hook);
30+
self
31+
}
32+
#[cfg(feature = "stdlib")]
33+
pub fn init_stdlib(self) -> Self {
34+
self.init_hook(Box::new(init_stdlib))
35+
}
36+
}
37+
38+
#[cfg(feature = "stdlib")]
39+
pub fn init_stdlib(vm: &mut VirtualMachine) {
40+
vm.add_native_modules(rustpython_stdlib::get_module_inits());
41+
42+
// if we're on freeze-stdlib, the core stdlib modules will be included anyway
43+
#[cfg(feature = "freeze-stdlib")]
44+
vm.add_frozen(rustpython_pylib::frozen_stdlib());
45+
46+
#[cfg(not(feature = "freeze-stdlib"))]
47+
{
48+
use rustpython_vm::common::rc::PyRc;
49+
50+
let state = PyRc::get_mut(&mut vm.state).unwrap();
51+
let settings = &mut state.settings;
52+
53+
#[allow(clippy::needless_collect)] // false positive
54+
let path_list: Vec<_> = settings.path_list.drain(..).collect();
55+
56+
// BUILDTIME_RUSTPYTHONPATH should be set when distributing
57+
if let Some(paths) = option_env!("BUILDTIME_RUSTPYTHONPATH") {
58+
settings.path_list.extend(
59+
crate::settings::split_paths(paths)
60+
.map(|path| path.into_os_string().into_string().unwrap()),
61+
)
62+
} else {
63+
#[cfg(feature = "rustpython-pylib")]
64+
settings
65+
.path_list
66+
.push(rustpython_pylib::LIB_PATH.to_owned())
67+
}
68+
69+
settings.path_list.extend(path_list.into_iter());
70+
}
71+
}

0 commit comments

Comments
 (0)