use std::ffi::{CStr, CString, NulError};
use crate::{EngineType, Error, Result};
use super::super::FunctionBundle;
use super::{PyCodeHandle, PythonEngine};
use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;
use pyo3::types::{PyCode, PyCodeInput, PyCodeMethods, PyDict, PyDictMethods, PyModule};
use serde_json::Value;
pub(super) fn create_context() -> Py<PyDict> {
Python::attach(|py| PyDict::new(py).unbind())
}
pub(super) fn create_with_bundle(bundle: &FunctionBundle) -> PyResult<PythonEngine> {
Python::attach(|py| {
let globals = create_context();
let mut engine = PythonEngine { globals };
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(())
})
}
fn last_line_is_expr(last_line: &str) -> bool {
!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 ")
}
fn split_lines(code: &str) -> (String, String) {
let lines: Vec<&str> = code.lines().collect();
let last_line = lines.last().unwrap_or(&"").trim().to_string();
let head = if lines.len() > 1 {
lines[..lines.len() - 1].join("\n")
} else {
String::new()
};
(head, last_line)
}
fn rewrite_with_result(code: &str) -> String {
let (head, last_line) = split_lines(code);
if head.trim().is_empty() {
format!("__result__ = {last_line}")
} else {
format!("{head}\n__result__ = {last_line}")
}
}
fn nul_err(e: NulError) -> PyErr {
PyErr::new::<PyValueError, _>(format!("code contains NUL byte: {e}"))
}
fn run_exec(
py: Python<'_>,
globals: &Bound<'_, PyDict>,
src: &CStr,
pre: Option<&Py<PyCode>>,
) -> PyResult<()> {
match pre {
Some(code) => code.bind(py).run(Some(globals), Some(globals)).map(|_| ()),
None => py.run(src, Some(globals), Some(globals)),
}
}
fn fetch_result(globals: &Bound<'_, PyDict>) -> Option<Py<PyAny>> {
globals
.get_item("__result__")
.ok()
.flatten()
.map(|bound| bound.unbind())
}
fn eval_then_run(
py: Python<'_>,
globals: &Bound<'_, PyDict>,
code: &str,
pre: Option<&Py<PyCode>>,
) -> PyResult<Option<Py<PyAny>>> {
let src = CString::new(code).map_err(nul_err)?;
match py.eval(&src, Some(globals), Some(globals)) {
Ok(result) => Ok(Some(result.unbind())),
Err(eval_err) => match run_exec(py, globals, &src, pre) {
Ok(()) => Ok(None),
Err(_) => Err(eval_err),
},
}
}
fn eval_inner(
py: Python<'_>,
globals: &Bound<'_, PyDict>,
code: &str,
pre: Option<&Py<PyCode>>,
) -> PyResult<Option<Py<PyAny>>> {
let (_, last_line) = split_lines(code);
let multi_expr_tail = code.lines().count() > 1 && last_line_is_expr(&last_line);
if multi_expr_tail {
let rewritten = rewrite_with_result(code);
let exec_src = CString::new(rewritten).map_err(nul_err)?;
match py.run(&exec_src, Some(globals), Some(globals)) {
Ok(()) => Ok(fetch_result(globals)),
Err(_) => eval_then_run(py, globals, code, pre),
}
} else {
eval_then_run(py, globals, code, pre)
}
}
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(String::new());
}
let globals = engine.globals.bind(py);
match eval_inner(py, globals, code, None) {
Ok(Some(result)) => Ok(result.bind(py).to_string()),
Ok(None) => Ok("Executed successfully".to_string()),
Err(e) => Err(Error::Python(e.to_string())),
}
})
}
fn object_to_json(py: Python<'_>, obj: &Py<PyAny>) -> Result<Value> {
let unconvertible = || Error::UnconvertibleValue {
backend: EngineType::Python,
};
let json = PyModule::import(py, "json").map_err(|e| Error::Python(e.to_string()))?;
let text: String = json
.getattr("dumps")
.map_err(|e| Error::Python(e.to_string()))?
.call1((obj,))
.map_err(|_| unconvertible())?
.extract()
.map_err(|_| unconvertible())?;
serde_json::from_str(&text).map_err(|_| unconvertible())
}
pub(super) fn eval_json(engine: &mut PythonEngine, code: &str) -> Result<Value> {
Python::attach(|py| -> Result<Value> {
let code = code.trim();
if code.is_empty() {
return Ok(Value::Null);
}
let globals = engine.globals.bind(py);
match eval_inner(py, globals, code, None) {
Ok(Some(obj)) => object_to_json(py, &obj),
Ok(None) => Ok(Value::Null),
Err(e) => Err(Error::Python(e.to_string())),
}
})
}
pub(super) fn set_var(engine: &PythonEngine, name: &str, value: &Value) -> Result<()> {
Python::attach(|py| -> Result<()> {
let text = serde_json::to_string(value).map_err(|_| Error::UnconvertibleValue {
backend: EngineType::Python,
})?;
let globals = engine.globals.bind(py);
let json = PyModule::import(py, "json").map_err(|e| Error::Python(e.to_string()))?;
let obj: Bound<'_, PyAny> = json
.getattr("loads")
.map_err(|e| Error::Python(e.to_string()))?
.call1((text,))
.map_err(|_| Error::UnconvertibleValue {
backend: EngineType::Python,
})?;
globals
.set_item(name, obj)
.map_err(|e| Error::Python(e.to_string()))?;
Ok(())
})
}
fn compile_exec(py: Python<'_>, src: &str) -> PyResult<Py<PyCode>> {
let code = CString::new(src).map_err(nul_err)?;
PyCode::compile(py, &code, c"<postscriptum>", PyCodeInput::File).map(|bound| bound.unbind())
}
pub(super) fn compile_py(src: &str) -> Result<PyCodeHandle> {
Python::attach(|py| -> Result<PyCodeHandle> {
let src = src.trim().to_string();
let (_, last_line) = split_lines(&src);
let single_expr = src.lines().count() == 1 && last_line_is_expr(&last_line);
if single_expr {
let eval_src = CString::new(src.as_str())
.map_err(|e| Error::Python(format!("code contains NUL byte: {e}")))?;
if let Ok(code) = PyCode::compile(py, &eval_src, c"<postscriptum>", PyCodeInput::Eval) {
return Ok(PyCodeHandle {
code: code.unbind(),
eval_mode: true,
has_result: true,
src,
});
}
}
let multi_expr_tail = src.lines().count() > 1 && last_line_is_expr(&last_line);
if multi_expr_tail {
let rewritten = rewrite_with_result(&src);
if let Ok(code) = compile_exec(py, &rewritten) {
return Ok(PyCodeHandle {
code,
eval_mode: false,
has_result: true,
src,
});
}
}
compile_exec(py, &src)
.map(|code| PyCodeHandle {
code,
eval_mode: false,
has_result: false,
src,
})
.map_err(|e| Error::Python(e.to_string()))
})
}
pub(super) fn eval_compiled(engine: &mut PythonEngine, handle: &PyCodeHandle) -> Result<Value> {
Python::attach(|py| -> Result<Value> {
let globals = engine.globals.bind(py);
if handle.eval_mode {
if let Ok(obj) = handle.code.bind(py).run(Some(globals), Some(globals)) {
return object_to_json(py, &obj.unbind());
}
} else if handle.has_result {
if let Ok(()) = handle
.code
.bind(py)
.run(Some(globals), Some(globals))
.map(|_| ())
{
return Ok(match fetch_result(globals) {
Some(obj) => object_to_json(py, &obj)?,
None => Value::Null,
});
}
}
let pre = if !handle.eval_mode && !handle.has_result {
Some(&handle.code)
} else {
None
};
match eval_inner(py, globals, &handle.src, pre) {
Ok(Some(obj)) => object_to_json(py, &obj),
Ok(None) => Ok(Value::Null),
Err(e) => Err(Error::Python(e.to_string())),
}
})
}
pub(super) fn fork(engine: &PythonEngine) -> Result<PythonEngine> {
Python::attach(|py| -> Result<PythonEngine> {
let copied = engine
.globals
.bind(py)
.copy()
.map_err(|e| Error::Python(e.to_string()))?;
Ok(PythonEngine {
globals: copied.unbind(),
})
})
}
pub(super) fn clear(engine: &PythonEngine) -> Result<()> {
Python::attach(|py| -> Result<()> {
engine.globals.bind(py).clear();
Ok(())
})
}