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