use crate::{
ApiError, CallOutcome, CompileError, CompiledChunk, Completion, Error, ExitStatus,
FromLuaMulti, Journal, LuaError, Runtime, SnapshotError, StepOutcome, VmError, WaitKey,
};
use std::fmt;
#[derive(Clone, Debug)]
#[must_use]
#[non_exhaustive]
pub enum EvalOutcome<R> {
Done(R),
OutOfFuel,
Waiting(WaitKey),
ExitRequested {
status: ExitStatus,
close: bool,
},
}
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()),
}
}
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)
}
#[derive(Clone, Debug)]
pub struct MainDiagnostic {
pub chunk_name: Vec<u8>,
pub outcome: StepOutcome,
pub error: Option<LuaError>,
}
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)
}
}
}
#[derive(Debug)]
#[non_exhaustive]
pub enum EmbedError {
Compile(CompileError),
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());
}
}