postscriptum 0.1.0

Multi-interpreted-language scripting engine for Rust with Rhai and Python backends
Documentation
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 };

        // Register all functions from the bundle if it's a Python bundle
        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| {
        // Register all functions from the bundle if it's a Python bundle
        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());
        }

        // Use the persistent globals and locals dictionaries
        let globals = engine.globals.bind(py);
        let locals = engine.locals.bind(py);

        // Check if the code is a single expression or multi-line code
        // For Jupyter-like behavior, we want to capture the value of the last expression

        // Try to parse the code to identify if the last line is an expression
        let lines: Vec<&str> = code.lines().collect();
        let last_line = lines.last().unwrap_or(&"").trim();

        // If it looks like the last line is an expression (not ending with : and not a control flow statement)
        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 {
            // Multi-line code with the last line as an expression
            // We'll create a modified version that assigns the previous lines then evaluates the last expression
            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(()) => {
                    // Try to get the result
                    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(_) => {
                    // If that fails, try the original approach with eval first
                    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 {
            // Single line that is an expression
            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 {
            // Last line is a statement, just run the code normally
            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())),
                },
            }
        }
    })
}