use std::ffi::CString;
use crate::{Error, Result};
use super::super::FunctionBundle;
use super::PythonEngine;
use pyo3::prelude::*;
use pyo3::types::PyDict;
pub(super) fn create_context() -> (Py<PyDict>, Py<PyDict>) {
Python::attach(|py| {
let globals = PyDict::new(py).unbind();
let locals = PyDict::new(py).unbind();
(globals, locals)
})
}
pub(super) fn create_with_bundle(bundle: &FunctionBundle) -> PyResult<PythonEngine> {
Python::attach(|py| {
let (globals, locals) = create_context();
let mut engine = PythonEngine { globals, locals };
if let FunctionBundle::Python(python_bundle) = bundle {
python_bundle.register(py, &mut engine)?;
}
Ok(engine)
})
}
pub(super) fn register_bundle(engine: &mut PythonEngine, bundle: &FunctionBundle) -> PyResult<()> {
Python::attach(|py| {
if let FunctionBundle::Python(python_bundle) = bundle {
python_bundle.register(py, engine)?;
}
Ok(())
})
}
pub(crate) fn eval(engine: &mut PythonEngine, code: &str) -> Result<String> {
Python::attach(|py| -> Result<String> {
let code = code.trim();
if code.is_empty() {
return Ok("".to_string());
}
let globals = engine.globals.bind(py);
let locals = engine.locals.bind(py);
let lines: Vec<&str> = code.lines().collect();
let last_line = lines.last().unwrap_or(&"").trim();
let last_line_is_expr = !last_line.is_empty()
&& !last_line.ends_with(':')
&& !last_line.starts_with("def ")
&& !last_line.starts_with("class ")
&& !last_line.starts_with("if ")
&& !last_line.starts_with("elif ")
&& !last_line.starts_with("else:")
&& !last_line.starts_with("for ")
&& !last_line.starts_with("while ")
&& !last_line.starts_with("try:")
&& !last_line.starts_with("except ")
&& !last_line.starts_with("finally:")
&& !last_line.starts_with("with ")
&& !last_line.starts_with("import ")
&& !last_line.starts_with("from ")
&& !last_line.starts_with("return ")
&& !last_line.starts_with("pass")
&& !last_line.starts_with("break")
&& !last_line.starts_with("continue")
&& !last_line.starts_with("raise ")
&& !last_line.starts_with("assert ")
&& !last_line.starts_with("del ")
&& !last_line.starts_with("global ")
&& !last_line.starts_with("nonlocal ");
if last_line_is_expr && lines.len() > 1 {
let all_but_last = lines[..lines.len() - 1].join("\n");
let modified_code = if all_but_last.trim().is_empty() {
format!("__result__ = {}", last_line)
} else {
format!(
r#"
{}
__result__ = {}
"#,
all_but_last, last_line
)
};
match py.run(&CString::new(modified_code)?, Some(globals), Some(locals)) {
Ok(()) => {
match locals.get_item("__result__") {
Ok(Some(result)) => Ok(result.to_string()),
Ok(None) => Ok("Executed successfully".to_string()),
Err(_) => Ok("Executed successfully".to_string()),
}
}
Err(_) => {
match py.eval(&CString::new(code)?, Some(globals), Some(locals)) {
Ok(result) => Ok(result.to_string()),
Err(eval_err) => {
match py.run(&CString::new(code)?, Some(globals), Some(locals)) {
Ok(()) => Ok("Executed successfully".to_string()),
Err(_run_err) => Err(Error::Python(eval_err.to_string())),
}
}
}
}
}
} else if last_line_is_expr && lines.len() == 1 {
match py.eval(&CString::new(code)?, Some(globals), Some(locals)) {
Ok(result) => Ok(result.to_string()),
Err(eval_err) => match py.run(&CString::new(code)?, Some(globals), Some(locals)) {
Ok(()) => Ok("Executed successfully".to_string()),
Err(_run_err) => Err(Error::Python(eval_err.to_string())),
},
}
} else {
match py.eval(&CString::new(code)?, Some(globals), Some(locals)) {
Ok(result) => Ok(result.to_string()),
Err(eval_err) => match py.run(&CString::new(code)?, Some(globals), Some(locals)) {
Ok(()) => Ok("Executed successfully".to_string()),
Err(_run_err) => Err(Error::Python(eval_err.to_string())),
},
}
}
})
}