moonseed 0.2.0

Deterministic, checkpointable Lua 5.4 runtime in safe Rust
Documentation
//! Small embedding operations with explicit fuel, journal and host policy.
//! A fuel quantum bounds VM execution, not Rust callbacks or wall-clock time.
//! Pauses and waits require application action; helpers never retry or clean up.

use crate::{
    ApiError, CallOutcome, CompileError, CompiledChunk, Completion, Error, ExitStatus,
    FromLuaMulti, Journal, LuaError, Runtime, SnapshotError, StepOutcome, VmError, WaitKey,
};
use std::fmt;

/// An outcome requiring application handling after one execution quantum.
#[derive(Clone, Debug)]
#[must_use]
#[non_exhaustive]
pub enum EvalOutcome<R> {
    /// Completed and converted the results without rerunning the chunk.
    Done(R),
    /// Resume with `run`, then obtain `result_values` when completed.
    OutOfFuel,
    /// Dispatch the operation and complete it on this runtime's owning thread.
    Waiting(WaitKey),
    /// Lua requested exit; the runtime is terminal.
    ExitRequested {
        /// Requested exit status.
        status: ExitStatus,
        /// Whether runtime closing completed before returning.
        close: bool,
    },
}

/// Load a main chunk and run exactly one quantum, including zero fuel.
/// Lua errors and termination return `Err`, as with `Runtime::call`. A main
/// yield is invalid. No cumulative fuel is replenished. After a pause/wait use
/// `run` and `result_values`; calling eval again on a live chunk is Busy.
/// Compilation limits remain the compiler caller's responsibility.
///
/// ```
/// use moonseed::{*, convenience::*};
/// let mut rt = Runtime::builder().build()?;
/// let chunk = compile_named_with_limits(b"return 6 * 7", b"@answer.lua", &CompileLimits::default())?;
/// let mut journal = Journal::new();
/// let outcome = eval::<i64>(&mut rt, &chunk, &mut journal, 10_000)?;
/// assert!(matches!(outcome, EvalOutcome::Done(42)));
/// # Ok::<(), EmbedError>(())
/// ```
pub fn eval<R: FromLuaMulti>(
    rt: &mut Runtime,
    chunk: &CompiledChunk,
    journal: &mut Journal,
    fuel: u64,
) -> crate::Result<EvalOutcome<R>> {
    rt.load_main(chunk)?;
    match rt.run(fuel, journal).map_err(Error::from)? {
        StepOutcome::Completed => {
            let values = rt.result_values()?;
            R::from_lua_multi(values, rt).map(EvalOutcome::Done)
        }
        StepOutcome::LuaError(_) => Err(rt.main_error()?.ok_or(VmError::Corrupt)?.into()),
        StepOutcome::Terminated(reason) => Err(VmError::from(reason).into()),
        StepOutcome::Waiting(key) => Ok(EvalOutcome::Waiting(key)),
        StepOutcome::Paused(_) => Ok(EvalOutcome::OutOfFuel),
        StepOutcome::ExitRequested { status, close } => {
            Ok(EvalOutcome::ExitRequested { status, close })
        }
        StepOutcome::LuaYielded => Err(ApiError::InvalidCallState.into()),
    }
}

/// Complete the active wait of an outstanding host call, then run one quantum
/// through the same driver as `Runtime::call`. Validate the host call and key
/// BEFORE consuming the completion or executing anything. Main-chunk waits are
/// refused. Duplicate/unknown/wrong-owner values are never silently accepted.
/// After a valid completion, execution/conversion failure does not undo the
/// completion or external effects. No automatic retry or reply is performed.
///
/// ```
/// use moonseed::{*, convenience::*};
/// let mut rt = Runtime::builder().wait_function("read", NativePolicy::VmLocal, "read.asset").build()?;
/// let read = rt.globals().raw_get::<_, Function>(&mut rt, "read")?;
/// let CallOutcome::Waiting(key) = rt.call::<i64>(&read, "answer", &mut Journal::new(), 1000)? else { return Err(ApiError::NotWaiting.into()) };
/// let outcome = complete_call::<i64>(&mut rt, key, Completion::Return(vec![Value::Integer(42)]), &mut Journal::new(), 1000)?;
/// assert!(matches!(outcome, CallOutcome::Done(42)));
/// # Ok::<(), EmbedError>(())
/// ```
pub fn complete_call<R: FromLuaMulti>(
    rt: &mut Runtime,
    key: WaitKey,
    completion: Completion,
    journal: &mut Journal,
    fuel: u64,
) -> crate::Result<CallOutcome<R>> {
    rt.complete_host_call(key, completion, journal, fuel)
}

/// A host-side projection retaining raw chunk-name bytes and rooted Lua errors.
#[derive(Clone, Debug)]
pub struct MainDiagnostic {
    /// Caller-supplied name; cannot authenticate stripped source information.
    pub chunk_name: Vec<u8>,
    /// Unchanged executor outcome.
    pub outcome: StepOutcome,
    /// Original Lua error; traceback is transient, not checkpoint state.
    pub error: Option<LuaError>,
}

/// Project a main-thread outcome without executing guest code or `tostring`.
/// Call before replacing a failed chunk. Display decodes names and traceback
/// lossily; original bytes remain available. Missing traceback stays missing.
///
/// ```
/// use moonseed::{*, convenience::*};
/// let chunk = compile_named_with_limits(b"error('oops')", b"@example.lua", &CompileLimits::default())?;
/// let mut rt = Runtime::builder().libraries(Libraries::BASE).build()?;
/// rt.load_main(&chunk)?;
/// let stop = rt.run(1000, &mut Journal::new())?;
/// eprintln!("{}", main_diagnostic(&mut rt, b"@example.lua", stop)?);
/// # Ok::<(), EmbedError>(())
/// ```
pub fn main_diagnostic(
    rt: &mut Runtime,
    chunk_name: &[u8],
    outcome: StepOutcome,
) -> crate::Result<MainDiagnostic> {
    let error = if matches!(&outcome, StepOutcome::LuaError(_)) {
        rt.main_error()?
    } else {
        None
    };
    Ok(MainDiagnostic {
        chunk_name: chunk_name.to_vec(),
        outcome,
        error,
    })
}

impl fmt::Display for MainDiagnostic {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}: ", String::from_utf8_lossy(&self.chunk_name))?;
        if let Some(error) = &self.error {
            error.fmt(f)?;
            if let Some(traceback) = &error.traceback {
                write!(f, "\n{}", String::from_utf8_lossy(traceback))?;
            }
            Ok(())
        } else {
            write!(f, "{:?}", self.outcome)
        }
    }
}

/// Mixed compile and runtime errors, preserving structured categories.
/// Snapshot writing and restore failures both use `Runtime(Error::Vm(
/// VmError::Snapshot(..)))`. No string reclassification is performed.
///
/// ```
/// fn checkpoint() -> Result<Vec<u8>, moonseed::convenience::EmbedError> {
///     let chunk = moonseed::compile(b"return 42")?;
///     let mut rt = moonseed::Runtime::builder().build()?;
///     rt.load_main(&chunk)?;
///     Ok(rt.snapshot()?)
/// }
/// ```
///
/// Restore uses the existing explicit host reconstruction boundary:
/// ```
/// # let bytes = { let mut config = moonseed::Config::default(); config.effect_domain = 7; let mut rt = moonseed::Runtime::builder().config(config).build()?; rt.snapshot()? };
/// # let bytes = bytes.as_slice();
/// use moonseed::{*, convenience::*};
/// let mut env = HostEnv::new();
/// env.insert(String::from("application resource"));
/// let capabilities = HostCapabilities::sandbox().host_env(env);
/// let host = Host::new(HostRegistry::new()).libraries(Libraries::NONE).capabilities(capabilities).effect_domain(7);
/// let restored = Runtime::restore(bytes, &host)?;
/// # Ok::<(), EmbedError>(())
/// ```
/// Rebuild matching callbacks and userdata policies as needed, retain the
/// matching journal separately, and reacquire roots. Restore does not undo
/// external effects. Host reconstruction/codecs need their own time/size bounds.
#[derive(Debug)]
#[non_exhaustive]
pub enum EmbedError {
    /// Compiler failure, with its original source span/category.
    Compile(CompileError),
    /// API, Lua, VM or snapshot failure in the existing runtime representation.
    Runtime(Error),
}

impl From<CompileError> for EmbedError {
    fn from(error: CompileError) -> Self {
        Self::Compile(error)
    }
}
impl From<Error> for EmbedError {
    fn from(error: Error) -> Self {
        Self::Runtime(error)
    }
}
impl From<SnapshotError> for EmbedError {
    fn from(error: SnapshotError) -> Self {
        Self::Runtime(error.into())
    }
}
impl From<ApiError> for EmbedError {
    fn from(error: ApiError) -> Self {
        Self::Runtime(error.into())
    }
}
impl From<VmError> for EmbedError {
    fn from(error: VmError) -> Self {
        Self::Runtime(error.into())
    }
}
impl fmt::Display for EmbedError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Compile(error) => error.fmt(f),
            Self::Runtime(error) => error.fmt(f),
        }
    }
}
impl std::error::Error for EmbedError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(match self {
            Self::Compile(error) => error,
            Self::Runtime(error) => error,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Function, Host, HostRegistry, Libraries, NativePolicy, Value, compile};

    #[test]
    fn complete_call_exit_matches_driver_snapshot() {
        let mut rt = Runtime::builder()
            .libraries(Libraries::OS)
            .wait_function("read", NativePolicy::VmLocal, "asset")
            .build()
            .unwrap();
        let EvalOutcome::Done(f) = eval::<Function>(
            &mut rt,
            &compile(b"return function() read(); os.exit(0) end").unwrap(),
            &mut Journal::new(),
            1000,
        )
        .unwrap() else {
            panic!("function setup")
        };
        let mut journal = Journal::new();
        let CallOutcome::Waiting(key) = rt.call::<()>(&f, (), &mut journal, 1000).unwrap() else {
            panic!("wait")
        };
        let mut registry = HostRegistry::new();
        registry.function("read", NativePolicy::VmLocal, |_| {
            panic!("must not rerun wait")
        });
        let mut control = Runtime::restore(&rt.snapshot().unwrap(), &Host::new(registry)).unwrap();
        control
            .complete(key, Completion::Return(vec![Value::Integer(42)]))
            .unwrap();
        assert!(matches!(
            control.drive_call::<()>(&mut journal, 1000).unwrap(),
            CallOutcome::ExitRequested { .. }
        ));
        assert!(matches!(
            complete_call::<()>(
                &mut rt,
                key,
                Completion::Return(vec![Value::Integer(42)]),
                &mut journal,
                1000
            )
            .unwrap(),
            CallOutcome::ExitRequested { .. }
        ));
        assert_eq!(rt.snapshot().unwrap(), control.snapshot().unwrap());
    }
}