1
//! The one registration path for async natives.
2
//!
3
//! A native's `Err` that carries a [`HostCondition`] is thrown into the script as a
4
//! `$nomi_error`, so `handler-case` can catch it. Every other failure (infrastructure,
5
//! argument errors, fuel, epoch) passes through unchanged and stays a host trap.
6

            
7
use std::future::Future;
8
use std::pin::Pin;
9
use std::sync::Arc;
10

            
11
use scripting::runtime::{EvalValue, HostCondition, throw_condition};
12
use wasmtime::{Caller, Linker, WasmRet, WasmTyList};
13

            
14
use crate::session::SessionData;
15

            
16
/// What a native body returns: a future borrowing the caller for its duration.
17
pub(crate) type NativeFuture<'a, R> =
18
    Pin<Box<dyn Future<Output = wasmtime::Result<R>> + Send + 'a>>;
19

            
20
/// Registers `body` as the `nomi.<name>` host fn.
21
16068888
pub(crate) fn register_native<P, R, F>(
22
16068888
    linker: &mut Linker<SessionData>,
23
16068888
    name: &str,
24
16068888
    body: F,
25
16068888
) -> wasmtime::Result<()>
26
16068888
where
27
16068888
    P: WasmTyList + Send + 'static,
28
16068888
    R: Send,
29
16068888
    wasmtime::Result<R>: WasmRet,
30
16068888
    F: for<'a, 'b> Fn(&'a mut Caller<'b, SessionData>, P) -> NativeFuture<'a, R>
31
16068888
        + Send
32
16068888
        + Sync
33
16068888
        + 'static,
34
{
35
16068888
    let body = Arc::new(body);
36
16068888
    linker.func_wrap_async(
37
16068888
        "nomi",
38
16068888
        name,
39
230619
        move |mut caller: Caller<'_, SessionData>, params: P| {
40
230619
            let body = Arc::clone(&body);
41
230619
            Box::new(async move {
42
230619
                match body(&mut caller, params).await {
43
209264
                    Ok(value) => Ok(value),
44
21195
                    Err(err) => Err(lift_condition(&mut caller, err).await),
45
                }
46
230459
            })
47
230619
        },
48
    )?;
49
16068888
    Ok(())
50
16068888
}
51

            
52
21195
async fn lift_condition(
53
21195
    caller: &mut Caller<'_, SessionData>,
54
21195
    err: wasmtime::Error,
55
21195
) -> wasmtime::Error {
56
21195
    let Some(condition) = err
57
21195
        .chain()
58
31435
        .find_map(|cause| cause.downcast_ref::<HostCondition>())
59
    else {
60
10401
        return err;
61
    };
62
10794
    let (code, message) = (condition.code.clone(), condition.message.clone());
63
10794
    let detail = condition.detail.clone().unwrap_or(EvalValue::Nil);
64
10794
    let thrown = throw_condition(caller, &code, &message, &detail).await;
65
10794
    prefer_thrown(thrown, err)
66
21195
}
67

            
68
/// The thrown condition, or a trap met while building it (fuel, epoch); `original` only when
69
/// the build itself failed.
70
10797
fn prefer_thrown(thrown: wasmtime::Error, original: wasmtime::Error) -> wasmtime::Error {
71
10797
    match thrown.is::<wasmtime::ThrownException>() || thrown.is::<wasmtime::Trap>() {
72
10795
        true => thrown,
73
2
        false => original,
74
    }
75
10797
}
76

            
77
#[cfg(test)]
78
#[path = "native_tests.rs"]
79
mod tests;