1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
use std::{ffi::CString, path::PathBuf, sync::Arc};

use parking_lot::Mutex;
use pyo3::{
    pyfunction,
    types::{PyCapsule, PyDict, PyModule},
    wrap_pyfunction, PyObject, PyResult, Python,
};
use wild_doc_script::{
    anyhow::Result, async_trait, IncludeAdaptor, Stack, WildDocScript, WildDocValue,
};

pub struct WdPy {}

#[async_trait(?Send)]
impl WildDocScript for WdPy {
    fn new(_: Arc<Mutex<Box<dyn IncludeAdaptor + Send>>>, _: PathBuf, _: &Stack) -> Result<Self> {
        let _ = Python::with_gil(|py| -> PyResult<()> {
            let builtins = PyModule::import(py, "builtins")?;

            let wd = PyModule::new(py, "wd")?;
            wd.add_function(wrap_pyfunction!(wdv, wd)?)?;

            builtins.add_function(wrap_pyfunction!(wdv, builtins)?)?;

            builtins.add_submodule(wd)?;

            Ok(())
        });
        Ok(WdPy {})
    }

    async fn evaluate_module(&mut self, _: &str, code: &str, stack: &Stack) -> Result<()> {
        Python::with_gil(|py| -> PyResult<()> {
            let builtins = PyModule::import(py, "builtins")?;
            builtins.set_item(
                "wdvars",
                PyCapsule::new(py, stack.clone(), Some(CString::new("builtins.wdstack")?))?,
            )?;

            py.run(code, None, None)
        })?;
        Ok(())
    }

    async fn eval(&mut self, code: &str, stack: &Stack) -> Result<WildDocValue> {
        Ok(WildDocValue::Binary(
            Python::with_gil(|py| -> PyResult<PyObject> {
                let builtins = PyModule::import(py, "builtins")?;
                builtins.set_item(
                    "wdvars",
                    PyCapsule::new(py, stack.clone(), Some(CString::new("builtins.wdstack")?))?,
                )?;
                py.eval(code, None, None)?.extract()
            })?
            .to_string()
            .into_bytes(),
        ))
    }
}

#[pyfunction]
#[pyo3(name = "v")]
fn wdv(_py: Python, key: String) -> PyResult<PyObject> {
    Python::with_gil(|py| -> PyResult<PyObject> {
        let stack: &Stack =
            unsafe { PyCapsule::import(py, CString::new("builtins.wdstack")?.as_ref())? };

        if let Some(v) = stack.get(&key) {
            return PyModule::from_code(
                py,
                r#"
import json

def v(data):
    return json.loads(data)
"#,
                "",
                "",
            )?
            .getattr("v")?
            .call1((v.to_string(),))?
            .extract();
        }

        Ok(PyDict::new(py).into())
    })
}