rustpython/
interpreter.rs1use rustpython_vm::InterpreterBuilder;
2
3pub trait InterpreterBuilderExt {
5 #[cfg(feature = "stdlib")]
9 fn init_stdlib(self) -> Self;
10}
11
12impl InterpreterBuilderExt for InterpreterBuilder {
13 #[cfg(feature = "stdlib")]
14 fn init_stdlib(self) -> Self {
15 let defs = rustpython_stdlib::stdlib_module_defs(&self.ctx);
16 let builder = self.add_native_modules(&defs);
17
18 #[cfg(feature = "freeze-stdlib")]
19 let builder = builder
20 .add_frozen_modules(rustpython_pylib::FROZEN_STDLIB)
21 .init_hook(set_frozen_stdlib_dir);
22
23 #[cfg(not(feature = "freeze-stdlib"))]
24 let builder = builder.init_hook(setup_dynamic_stdlib);
25
26 builder
27 }
28}
29
30#[cfg(all(feature = "stdlib", feature = "freeze-stdlib"))]
32fn set_frozen_stdlib_dir(vm: &mut crate::VirtualMachine) {
33 use rustpython_vm::common::rc::PyRc;
34
35 let state = PyRc::get_mut(&mut vm.state).unwrap();
36 state.config.paths.stdlib_dir = Some(rustpython_pylib::LIB_PATH.to_owned());
37}
38
39#[cfg(all(feature = "stdlib", not(feature = "freeze-stdlib")))]
41fn setup_dynamic_stdlib(vm: &mut crate::VirtualMachine) {
42 use rustpython_vm::common::rc::PyRc;
43
44 let state = PyRc::get_mut(&mut vm.state).unwrap();
45 let paths = collect_stdlib_paths();
46
47 if let Some(first_path) = paths.first() {
49 state.config.paths.stdlib_dir = Some(first_path.clone());
50 }
51
52 for path in paths.into_iter().rev() {
54 state.config.paths.module_search_paths.insert(0, path);
55 }
56}
57
58#[cfg(all(feature = "stdlib", not(feature = "freeze-stdlib")))]
60fn collect_stdlib_paths() -> Vec<String> {
61 if let Some(paths) = option_env!("BUILDTIME_RUSTPYTHONPATH") {
63 crate::settings::split_paths(paths)
64 .map(|path| path.into_os_string().into_string().unwrap())
65 .collect()
66 } else {
67 #[cfg(feature = "rustpython-pylib")]
68 {
69 vec![rustpython_pylib::LIB_PATH.to_owned()]
70 }
71 #[cfg(not(feature = "rustpython-pylib"))]
72 {
73 vec![]
74 }
75 }
76}