1use pyo3::prelude::*;
2use pyo3::types::*;
3use std::ffi;
4use std::ptr::addr_of;
5
6use wcore::{
7 evaluator::WEval,
8 models::{Range, State, Token::*, WTokens},
9};
10
11fn create_pylist<'a>(py: Python, acc: &'a PyList, wcode: Vec<WTokens>) -> &'a PyList {
12 for section in wcode {
13 for code_result in section {
14 match code_result {
15 Container(x) | ContainerLiteral(x) | Atom(x) | Special(x) => acc.append(x).unwrap(),
16 Char(x) => acc.append(x).unwrap(),
17 Value(x) => acc.append(x).unwrap(),
18 Function(x) | FunctionLiteral(x) => {
19 let address: *const i8 = addr_of!(x).cast();
20 let slice = unsafe { ffi::CStr::from_ptr(address) };
21 acc.append(slice.to_string_lossy().into_owned()).unwrap()
22 }
23 Parameter(x) => acc
24 .append(match x {
25 Range::Full(y) => format!("{}..={}", y.start(), y.end()),
26 Range::To(y) => format!("..{}", y.start),
27 Range::From(y) => format!("{}..", y.end),
28 })
29 .unwrap(),
30 Group(x) => acc
31 .append(create_pylist(py, PyList::empty(py), vec![x]))
32 .unwrap(),
33 };
34 }
35 }
36
37 acc
38}
39
40#[pyclass(name = "State")]
41struct PyState {
42 state: State,
43}
44
45#[pymethods]
46impl PyState {
47 #[new]
48 fn __new__() -> PyResult<Self> {
49 Ok(Self {
50 state: State::new(),
51 })
52 }
53
54 fn apply<'a>(&mut self, py: Python<'a>, code: String) -> PyResult<&'a PyAny> {
55 let result = PyList::empty(py);
56 let code_eval = self.state.apply(&code);
57
58 create_pylist(py, result, code_eval);
59 Ok(result.downcast()?)
60 }
61}
62
63#[pymodule]
64fn wcore_py(_py: Python, m: &PyModule) -> PyResult<()> {
65 m.add_class::<PyState>()?;
66 Ok(())
67}