postscriptum 0.1.1

Multi-interpreted-language scripting engine for Rust with Rhai and Python backends
Documentation
use js_sys::Function;
use wasm_bindgen::JsValue;
use wasm_bindgen::prelude::*;

use crate::{EngineType, Error, FunctionBundle, Result, python::PythonEngine};

// External function to register all functions with Pyodide (defined in wasm_function_bundle.rs)
use crate::python::wasm_function_bundle::register_all_functions_with_pyodide;

pub fn register_bundle(engine: &mut PythonEngine, bundle: &FunctionBundle) -> Result<()> {
    // For WASM, we register functions with Pyodide when it's available
    match bundle {
        FunctionBundle::Python(_) => {
            // Register all functions from the bundle with Pyodide
            // We'll try to register, but if Pyodide isn't ready yet, we'll just continue
            println!("Registering Python function bundle with Pyodide...");
            web_sys::console::log_1(&"Registering Python function bundle...".to_string().into());

            // First, register the functions in the global scope
            if let FunctionBundle::Python(py_bundle) = bundle {
                if let Err(e) = py_bundle.register() {
                    eprintln!("Failed to register functions in global scope: {:?}", e);
                    // Don't fail entirely, continue with Pyodide registration
                }
            }

            // Then register them with Pyodide
            match register_all_functions_with_pyodide(bundle) {
                Ok(_) => {
                    println!("Successfully registered Python function bundle with Pyodide");
                    engine._initialized = true;
                }
                Err(e) => {
                    // If Pyodide isn't loaded yet, that's OK - we'll try again later when eval is called
                    eprintln!(
                        "Failed to register Python function bundle with Pyodide, will try again: {:?}",
                        e
                    );
                    // Don't fail the registration entirely, just mark that Pyodide isn't ready yet
                }
            }
        }
        _ => {
            // Ignore other bundle types
        }
    }

    Ok(())
}

pub fn eval(engine: &mut PythonEngine, code: &str) -> Result<String> {
    // Try to register functions again if the engine is not initialized yet
    if !engine._initialized {
        // We can't register the bundle functions in eval because we don't have access to the bundle here
        // This is handled in the register_bundle function when the bundle is available
    }

    let result = call_run_python(code)?;

    // Convert the result to a string
    let result_str = if result.is_string() {
        result
            .as_string()
            .unwrap_or_else(|| "<no result>".to_string())
    } else if result.is_object() {
        // For objects, try to call toString() to get the proper string representation
        let obj = result.dyn_ref::<js_sys::Object>().unwrap();
        let to_string_result = js_sys::Reflect::get(obj, &"toString".into()).ok();
        if let Some(to_string_fn) = to_string_result {
            if let Some(to_string_fn) = to_string_fn.dyn_ref::<Function>() {
                match to_string_fn.call0(obj) {
                    Ok(str_result) => str_result
                        .as_string()
                        .unwrap_or_else(|| "<toString failed>".to_string()),
                    Err(_) => "<object>".to_string(),
                }
            } else {
                // If toString is not available or not a function, use the string representation
                format!("{:?}", result)
            }
        } else {
            format!("{:?}", result)
        }
    } else {
        // For other types (numbers, booleans, etc.), use the string representation but more intelligently
        // We'll use JSON.stringify if available to get a proper representation
        use js_sys::JSON;
        match JSON::stringify(&result) {
            Ok(json_str) => json_str
                .as_string()
                .unwrap_or_else(|| format!("{:?}", result)),
            Err(_) => format!("{:?}", result), // fallback to default representation
        }
    };

    Ok(result_str)
}

/// Shared Pyodide `runPython` call: the window/object/lookup boilerplate
/// factored out of `eval` (identical behavior) so `set_var`,
/// `eval_json` and `compile_py` reuse the exact same lookup and error
/// mapping.
fn call_run_python(code: &str) -> Result<JsValue> {
    use js_sys::JsString;
    use web_sys::window;

    // Check that we have window object
    let window = window().ok_or_else(|| Error::Python("No window object available".into()))?;

    // Get the Pyodide object from global scope
    let pyodide_obj = js_sys::Reflect::get(&window.into(), &"pyodide".into()).map_err(|_| {
        console_error_panic_hook::set_once();
        eprintln!("Pyodide not found in global scope");
        Error::Python(
            "Pyodide not available. Make sure Pyodide is loaded before running Python code."
                .to_string(),
        )
    })?;

    if pyodide_obj.is_undefined() {
        return Err(Error::Python(
            "Pyodide is undefined. The Pyodide library may not be fully loaded yet.".to_string(),
        ));
    }

    // Get the runPython function
    let run_python_fn = js_sys::Reflect::get(&pyodide_obj, &"runPython".into()).map_err(|e| {
        eprintln!("Failed to get runPython function: {:?}", e);
        Error::Python("Failed to get runPython function from Pyodide object".to_string())
    })?;

    if run_python_fn.is_undefined() {
        return Err(Error::Python(
            "runPython function is undefined. Pyodide may not be fully initialized.".to_string(),
        ));
    }

    let run_python_fn = run_python_fn
        .dyn_into::<Function>()
        .map_err(|_| Error::Python("runPython is not a function".into()))?;

    // Execute the Python code
    run_python_fn
        .call1(&pyodide_obj, &JsString::from(code).into())
        .map_err(|e| {
            eprintln!("JS error calling runPython: {:?}", e);
            let error_str = format!("{:?}", e);
            Error::Python(format!(
                "JavaScript error when executing Python code: {error_str}"
            ))
        })
}

/// Bind a JSON value in Pyodide's shared `__main__` namespace (G3).
///
/// Runs `{name} = json.loads({payload})` (`import json` first —
/// idempotent via the `sys.modules` cache). The name passed the
/// shared identifier precondition, so interpolation is safe; the
/// payload is a quoted literal via the shared `py_string_literal`
/// escaper (round-trips exactly for all `serde_json` output).
pub fn set_var(_engine: &PythonEngine, name: &str, value: &serde_json::Value) -> Result<()> {
    // `serde_json::Value` serializes infallibly; the error arm is
    // unreachable but keeps the failure typed.
    let payload = super::py_string_literal(&serde_json::to_string(value).map_err(|_| {
        Error::UnconvertibleValue {
            backend: EngineType::Python,
        }
    })?);
    call_run_python("import json").map(|_| ())?;
    call_run_python(&format!("{name} = json.loads({payload})")).map(|_| ())?;
    // Track for `clear()` (see `bound_names`): deduped, insertion order.
    {
        let mut bound = _engine.bound_names.borrow_mut();
        if !bound.iter().any(|n| n == name) {
            bound.push(name.to_string());
        }
    }
    Ok(())
}

/// Convert a `runPython` result to JSON (G3).
///
/// `undefined` (bare-statement runs) and `null` become `Null`;
/// everything else goes through `JSON.stringify`. Results that
/// cannot stringify (BigInt from huge Python ints, opaque PyProxy
/// objects, …) become [`Error::UnconvertibleValue`] — never a panic.
fn js_to_json(value: &JsValue) -> Result<serde_json::Value> {
    if value.is_undefined() || value.is_null() {
        return Ok(serde_json::Value::Null);
    }
    let unconvertible = || Error::UnconvertibleValue {
        backend: EngineType::Python,
    };
    // `stringify` throws on BigInt/PyProxy — mapped, not propagated.
    let text = js_sys::JSON::stringify(value).map_err(|_| unconvertible())?;
    let text = String::from(text);
    serde_json::from_str(&text).map_err(|_| unconvertible())
}

/// Evaluate and return typed JSON (G3) — the alternative to lossy
/// `to_string()`. Bare-statement runs yield `Null`.
pub fn eval_json(_engine: &mut PythonEngine, code: &str) -> Result<serde_json::Value> {
    let result = call_run_python(code.trim())?;
    js_to_json(&result)
}

/// Compile once per query (G4): validates WITHOUT executing —
/// `compile()` never runs the code, so this doubles as
/// validate-without-run.
///
/// Documented WASM gap: `runPython` only takes source text, and
/// PyProxy code objects don't survive across calls cleanly, so the
/// handle carries VALIDATED source and [`eval_compiled`] re-runs it
/// (string eval as fallback). Validation itself is real, the source
/// cap is enforced in the shared wrapper, and byte-identity with
/// [`eval_json`] still holds.
pub fn compile_py(src: &str) -> Result<super::PyCodeHandle> {
    let lit = super::py_string_literal(src.trim());
    let probe = format!("compile({lit}, '<postscriptum>', 'exec')");
    // Errors pass through unchanged: infra failures stay infra
    // failures, `SyntaxError` text stays in the message.
    call_run_python(&probe)?;
    Ok(super::PyCodeHandle {
        src: src.trim().to_string(),
    })
}

/// Evaluate a handle from [`compile_py`] (G4): re-runs the validated
/// source (see the documented gap above).
pub fn eval_compiled(
    engine: &mut PythonEngine,
    handle: &super::PyCodeHandle,
) -> Result<serde_json::Value> {
    eval_json(engine, &handle.src)
}

/// Fork into a fresh handle (G6).
///
/// Shares Pyodide's `__main__` namespace with the parent — documented
/// non-isolation (a separate namespace per handle is impractical over
/// `runPython`). Inherits the parent's tracked names so `clear()` on
/// the fork removes what it can see. Volatile callers needing real
/// isolation run Rhai.
pub fn fork(engine: &PythonEngine) -> Result<PythonEngine> {
    Ok(PythonEngine {
        _initialized: engine._initialized,
        bound_names: std::cell::RefCell::new(engine.bound_names.borrow().clone()),
    })
}

/// Unbind names tracked via `set_var` on this handle (G6).
///
/// Runs `[globals().pop('a', None), …]` — a list display (no loop
/// variable leaks into `__main__`), `pop` with a default (never
/// raises, missing names are silently skipped). Clears only
/// postscriptum-bound names: user-bound names persist (wiping the
/// shared namespace would affect every handle).
pub fn clear(engine: &PythonEngine) -> Result<()> {
    let names: Vec<String> = std::mem::take(&mut *engine.bound_names.borrow_mut());
    if names.is_empty() {
        return Ok(());
    }
    // Names passed the shared identifier precondition — interpolation
    // is safe (no quotes possible).
    let pops = names
        .iter()
        .map(|n| format!("globals().pop('{n}', None)"))
        .collect::<Vec<_>>()
        .join(", ");
    call_run_python(&format!("[{pops}]")).map(|_| ())?;
    Ok(())
}