Skip to main content

scripting/runtime/
raise.rs

1//! The boundary bridge's error: an uncaught script `$nomi_error` leaves the guest as a
2//! [`ScriptRaise`], which the classifier lifts into `EngineError::ScriptRaised`.
3
4use thiserror::Error;
5use wasmtime::{AnyRef, ArrayRef, AsContextMut, Caller, Rooted};
6
7use super::abi::read_string_arg;
8use super::decode::EvalValue;
9use super::structure::{InstanceMode, decode_dynamic_anyref};
10use super::type_handles::resolve_caller_type_handles;
11
12/// An uncaught in-guest condition. `detail` is the decoded detail value, `None` when absent.
13#[derive(Debug, Clone, PartialEq, Error)]
14#[error("__nomi_raise:{code}:{message}")]
15pub struct ScriptRaise {
16    pub code: String,
17    pub message: String,
18    pub detail: Option<EvalValue>,
19}
20
21/// The `__nomi_raise` host fn body shared by every linker: reads the
22/// condition's fields and always returns `Err`, carrying a [`ScriptRaise`]
23/// unless the code or message cannot be read.
24///
25/// # Errors
26/// Always; a missing code or an unreadable code or message replaces the raise.
27pub fn nomi_raise<T>(
28    caller: &mut Caller<'_, T>,
29    code: Option<Rooted<ArrayRef>>,
30    message: Option<Rooted<ArrayRef>>,
31    detail: Option<Rooted<AnyRef>>,
32) -> wasmtime::Result<()> {
33    let code = read_string_arg(caller, code)?
34        .ok_or_else(|| wasmtime::Error::msg("error: missing :code arg"))?;
35    let message = read_string_arg(caller, message)?.unwrap_or_default();
36    let detail = decoded_detail(caller, detail);
37    Err(wasmtime::Error::new(ScriptRaise {
38        code,
39        message,
40        detail,
41    }))
42}
43
44/// The decoded detail, which sits one list deeper in the envelope than a `:value`. A cyclic or too deep value
45/// decodes as contents with a depth placeholder; one that cannot be decoded (compound money) degrades to a placeholder
46/// so it never masks the code and message.
47fn decoded_detail<T>(
48    caller: &mut Caller<'_, T>,
49    detail: Option<Rooted<AnyRef>>,
50) -> Option<EvalValue> {
51    let any = detail?;
52    let decoded = resolve_caller_type_handles(caller).and_then(|handles| {
53        decode_dynamic_anyref(
54            caller.as_context_mut(),
55            any,
56            &handles,
57            InstanceMode::Contents,
58            1,
59        )
60    });
61    Some(decoded.unwrap_or_else(|err| EvalValue::String(format!("<undecodable detail: {err}>"))))
62}