postscriptum 0.1.1

Multi-interpreted-language scripting engine for Rust with Rhai and Python backends
Documentation
//! Error types for postscriptum.
//!
//! All public fallible APIs return [`Result`] / [`Error`], so consumers can
//! match on the failure cause instead of a crate-specific opaque error.

use std::ffi::NulError;

use super::EngineType;

/// The `Result` type used across postscriptum.
pub type Result<T> = std::result::Result<T, Error>;

/// Which resource budget a bounded eval exhausted.
///
/// Each variant maps to one rhai limiter (`set_max_*`); `Source` is a
/// host-side pre-check on input length (enforced before compiling).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LimitKind {
    /// Operation count (`set_max_operations`).
    Operations,
    /// Call depth (`set_max_call_levels`).
    CallDepth,
    /// String size (`set_max_string_size`).
    String,
    /// Array size (`set_max_array_size`).
    Array,
    /// Object-map size (`set_max_map_size`).
    Map,
    /// Source length (host-side byte cap, enforced before eval).
    Source,
}

/// The error type returned by postscriptum.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// The engine mutex was poisoned (a thread panicked while it was locked).
    #[error("engine mutex poisoned")]
    MutexPoisoned,

    /// The Rhai engine reported an error while evaluating a script.
    #[error("rhai error: {0}")]
    Rhai(String),

    /// The Python engine reported an error while evaluating a script or
    /// registering functions.
    #[error("python error: {0}")]
    Python(String),

    /// A bounded eval exhausted one of its resource budgets.
    ///
    /// Returned by `BoundedRhaiEngine` when a rhai limiter fires;
    /// match on `kind` instead of string-matching the message.
    #[error("resource exhausted ({kind:?}) on {backend:?} engine")]
    ResourceExhausted {
        backend: EngineType,
        kind: LimitKind,
    },

    /// The requested budget cannot be enforced on this backend.
    ///
    /// CPython offers no safe in-process fuel cap, so any bounded-eval
    /// entry point called with `EngineType::Python` fails with this
    /// instead of a fake guarantee. Never a timeout: killing a
    /// GIL-holding thread is unsound.
    #[error("{limit} not supported on {backend:?} engine")]
    LimitUnsupported {
        backend: EngineType,
        limit: &'static str,
    },

    /// A script result (or host binding) could not cross the JSON
    /// boundary. Never a panic: exotic values (bytes, object
    /// handles, …) fail with this instead.
    #[error("value not convertible to JSON on {backend:?} engine")]
    UnconvertibleValue { backend: EngineType },

    /// A variable name was rejected by the shared `set_var`
    /// precondition (must be a valid identifier on both backends —
    /// the WASM backend interpolates the name into code).
    #[error("invalid variable name: {0}")]
    InvalidName(String),

    /// Static expression validation failed (G7): one or more
    /// [`ValidationError`] issues. UX/early-error only — never the
    /// security boundary (fail-open walker + fuel caps + sandbox
    /// are the backstop).
    #[error("expression validation failed: {0}")]
    ValidationFailed(ValidationError),

    /// A function name could not be converted to a C string.
    #[error("invalid function name: {0}")]
    FunctionName(#[from] NulError),
}

/// Which static check produced an [`ExprIssue`] (G7).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ExprIssueKind {
    /// Unparseable source (or over the length cap — same bucket:
    /// static rejections the author must fix, message
    /// disambiguates).
    Syntax,
    /// A bare root outside the allowed set and local declarations.
    UnknownRoot,
    /// A call to `eval(...)` (defeats the root check statically).
    DynamicEval,
}

/// One static validation finding (G7): `locator` is caller-supplied
/// (`columns[3].expression`, `filter_expression`, …) and preserved
/// verbatim; `message` names the offender.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExprIssue {
    pub locator: String,
    pub message: String,
    pub kind: ExprIssueKind,
}

/// Failed static validation: the non-empty issue list. Empty means
/// valid — constructors outside `validate` must uphold that.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValidationError(pub Vec<ExprIssue>);

impl std::fmt::Display for ValidationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let kinds = self
            .0
            .iter()
            .map(|issue| format!("{:?}: {}", issue.kind, issue.message))
            .collect::<Vec<_>>()
            .join("; ");
        write!(f, "{} issue(s): {kinds}", self.0.len())
    }
}