Skip to main content

scripting/runtime/
condition.rs

1//! Raising a catchable `$nomi_error` condition from a host fn.
2
3use std::convert::Infallible;
4
5use wasmtime::{AnyRef, AsContextMut, Caller, ExnRef, ExnRefPre, ExnType, Rooted, Val};
6
7use super::abi::alloc_string_ref;
8use super::decode::EvalValue;
9use super::encode::alloc_value;
10
11/// Throws a `$nomi_error` carrying `code` (upper-cased, as `handler-case` compares it),
12/// `message` and the structured `detail`, so the calling script's `handler-case` can catch it
13/// and read the detail with `error-detail`. Return the result from the host fn:
14/// `return Err(throw_condition(&mut caller, code, message, &detail).await)`. Any failure while
15/// building the condition is returned in its place.
16pub async fn throw_condition<T: Send>(
17    caller: &mut Caller<'_, T>,
18    code: &str,
19    message: &str,
20    detail: &EvalValue,
21) -> wasmtime::Error {
22    let exn = match build_exception(caller, &code.to_uppercase(), message, detail).await {
23        Ok(exn) => exn,
24        Err(err) => return err,
25    };
26    match caller.as_context_mut().throw::<Infallible>(exn) {
27        Err(thrown) => thrown,
28    }
29}
30
31async fn build_exception<T: Send>(
32    caller: &mut Caller<'_, T>,
33    code: &str,
34    message: &str,
35    detail: &EvalValue,
36) -> wasmtime::Result<Rooted<ExnRef>> {
37    let tag = caller
38        .get_export("nomi_error")
39        .and_then(wasmtime::Extern::into_tag)
40        .ok_or_else(|| wasmtime::Error::msg("module does not export `nomi_error`"))?;
41    let condition = condition_new(caller, code, message, detail).await?;
42    let tag_type = tag.ty(&*caller);
43    let pre = ExnRefPre::new(caller.as_context_mut(), ExnType::from_tag_type(&tag_type)?);
44    ExnRef::new_async(
45        caller.as_context_mut(),
46        &pre,
47        &tag,
48        &[Val::AnyRef(Some(condition))],
49    )
50    .await
51}
52
53async fn condition_new<T: Send>(
54    caller: &mut Caller<'_, T>,
55    code: &str,
56    message: &str,
57    detail: &EvalValue,
58) -> wasmtime::Result<Rooted<AnyRef>> {
59    let constructor = caller
60        .get_export("condition_new")
61        .and_then(wasmtime::Extern::into_func)
62        .ok_or_else(|| wasmtime::Error::msg("module does not export `condition_new`"))?;
63    let code = alloc_string_ref(caller, code.as_bytes())?;
64    let message = alloc_string_ref(caller, message.as_bytes())?;
65    let detail = alloc_value(caller, detail).await?;
66    let mut results = [Val::AnyRef(None)];
67    constructor
68        .call_async(
69            caller.as_context_mut(),
70            &[
71                Val::AnyRef(Some(code.to_anyref())),
72                Val::AnyRef(Some(message.to_anyref())),
73                Val::AnyRef(detail),
74            ],
75            &mut results,
76        )
77        .await?;
78    match results {
79        [Val::AnyRef(Some(condition))] => Ok(condition),
80        _ => Err(wasmtime::Error::msg("condition_new returned no condition")),
81    }
82}