python_ast/codegen/
python_options.rs

1//! Options for Python compilation.
2
3use std::{
4    collections::{BTreeMap, HashSet},
5    default::Default,
6};
7
8use crate::Scope;
9use pyo3::{prelude::*, PyResult};
10use std::ffi::CString;
11
12pub fn sys_path() -> PyResult<Vec<String>> {
13    let pymodule_code = include_str!("path.py");
14
15    Python::with_gil(|py| -> PyResult<Vec<String>> {
16        let code_cstr = CString::new(pymodule_code)?;
17        let pymodule = PyModule::from_code(py, &code_cstr, c"path.py", c"path")?;
18        let t = pymodule
19            .getattr("path")
20            .expect("Reading path variable from interpretter");
21        assert!(t.is_callable());
22        let args = ();
23        let paths: Vec<String> = t.call1(args)?.extract()?;
24
25        Ok(paths)
26    })
27}
28
29/// The global context for Python compilation.
30#[derive(Clone, Debug)]
31pub struct PythonOptions {
32    /// Python imports are mapped into a given namespace that can be changed.
33    pub python_namespace: String,
34
35    /// The default path we will search for Python modules.
36    pub python_path: Vec<String>,
37
38    /// Collects all of the things we need to compile imports[module][asnames]
39    pub imports: BTreeMap<String, HashSet<String>>,
40
41    pub scope: Scope,
42
43    pub stdpython: String,
44    pub with_std_python: bool,
45
46    pub allow_unsafe: bool,
47}
48
49impl Default for PythonOptions {
50    fn default() -> Self {
51        Self {
52            python_namespace: String::from("__python_namespace__"),
53            // XXX: Remove unwrap.
54            python_path: sys_path().unwrap(),
55            imports: BTreeMap::new(),
56            scope: Scope::default(),
57            stdpython: "stdpython".to_string(),
58            with_std_python: true,
59            allow_unsafe: false,
60        }
61    }
62}