Lines
97.83 %
Functions
78.35 %
Branches
100 %
//! The one registration path for async natives.
//!
//! A native's `Err` that carries a [`HostCondition`] is thrown into the script as a
//! `$nomi_error`, so `handler-case` can catch it. Every other failure (infrastructure,
//! argument errors, fuel, epoch) passes through unchanged and stays a host trap.
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use scripting::runtime::{EvalValue, HostCondition, throw_condition};
use wasmtime::{Caller, Linker, WasmRet, WasmTyList};
use crate::session::SessionData;
/// What a native body returns: a future borrowing the caller for its duration.
pub(crate) type NativeFuture<'a, R> =
Pin<Box<dyn Future<Output = wasmtime::Result<R>> + Send + 'a>>;
/// Registers `body` as the `nomi.<name>` host fn.
pub(crate) fn register_native<P, R, F>(
linker: &mut Linker<SessionData>,
name: &str,
body: F,
) -> wasmtime::Result<()>
where
P: WasmTyList + Send + 'static,
R: Send,
wasmtime::Result<R>: WasmRet,
F: for<'a, 'b> Fn(&'a mut Caller<'b, SessionData>, P) -> NativeFuture<'a, R>
+ Send
+ Sync
+ 'static,
{
let body = Arc::new(body);
linker.func_wrap_async(
"nomi",
name,
move |mut caller: Caller<'_, SessionData>, params: P| {
let body = Arc::clone(&body);
Box::new(async move {
match body(&mut caller, params).await {
Ok(value) => Ok(value),
Err(err) => Err(lift_condition(&mut caller, err).await),
}
})
},
)?;
Ok(())
async fn lift_condition(
caller: &mut Caller<'_, SessionData>,
err: wasmtime::Error,
) -> wasmtime::Error {
let Some(condition) = err
.chain()
.find_map(|cause| cause.downcast_ref::<HostCondition>())
else {
return err;
};
let (code, message) = (condition.code.clone(), condition.message.clone());
let detail = condition.detail.clone().unwrap_or(EvalValue::Nil);
let thrown = throw_condition(caller, &code, &message, &detail).await;
prefer_thrown(thrown, err)
/// The thrown condition, or a trap met while building it (fuel, epoch); `original` only when
/// the build itself failed.
fn prefer_thrown(thrown: wasmtime::Error, original: wasmtime::Error) -> wasmtime::Error {
match thrown.is::<wasmtime::ThrownException>() || thrown.is::<wasmtime::Trap>() {
true => thrown,
false => original,
#[cfg(test)]
#[path = "native_tests.rs"]
mod tests;