Skip to main content

rustpython/
interpreter.rs

1use rustpython_vm::InterpreterBuilder;
2
3/// Extension trait for InterpreterBuilder to add rustpython-specific functionality.
4pub trait InterpreterBuilderExt {
5    /// Initialize the Python standard library.
6    ///
7    /// Requires the `stdlib` feature to be enabled.
8    #[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/// Set stdlib_dir for frozen standard library
31#[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/// Setup dynamic standard library loading from filesystem
40#[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    // Set stdlib_dir to the first stdlib path if available
48    if let Some(first_path) = paths.first() {
49        state.config.paths.stdlib_dir = Some(first_path.clone());
50    }
51
52    // Insert at the beginning so stdlib comes before user paths
53    for path in paths.into_iter().rev() {
54        state.config.paths.module_search_paths.insert(0, path);
55    }
56}
57
58/// Collect standard library paths from build-time configuration
59#[cfg(all(feature = "stdlib", not(feature = "freeze-stdlib")))]
60fn collect_stdlib_paths() -> Vec<String> {
61    // BUILDTIME_RUSTPYTHONPATH should be set when distributing
62    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}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.