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

            
4
use thiserror::Error;
5
use wasmtime::{AnyRef, ArrayRef, AsContextMut, Caller, Rooted};
6

            
7
use super::abi::read_string_arg;
8
use super::decode::EvalValue;
9
use super::structure::{InstanceMode, decode_dynamic_anyref};
10
use 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}")]
15
pub 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.
27
66047
pub fn nomi_raise<T>(
28
66047
    caller: &mut Caller<'_, T>,
29
66047
    code: Option<Rooted<ArrayRef>>,
30
66047
    message: Option<Rooted<ArrayRef>>,
31
66047
    detail: Option<Rooted<AnyRef>>,
32
66047
) -> wasmtime::Result<()> {
33
66047
    let code = read_string_arg(caller, code)?
34
        .ok_or_else(|| wasmtime::Error::msg("error: missing :code arg"))?;
35
66047
    let message = read_string_arg(caller, message)?.unwrap_or_default();
36
66047
    let detail = decoded_detail(caller, detail);
37
66047
    Err(wasmtime::Error::new(ScriptRaise {
38
66047
        code,
39
66047
        message,
40
66047
        detail,
41
66047
    }))
42
66047
}
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.
47
66047
fn decoded_detail<T>(
48
66047
    caller: &mut Caller<'_, T>,
49
66047
    detail: Option<Rooted<AnyRef>>,
50
66047
) -> Option<EvalValue> {
51
66047
    let any = detail?;
52
9547
    let decoded = resolve_caller_type_handles(caller).and_then(|handles| {
53
9547
        decode_dynamic_anyref(
54
9547
            caller.as_context_mut(),
55
9547
            any,
56
9547
            &handles,
57
9547
            InstanceMode::Contents,
58
9547
            1,
59
9547
        )
60
9547
    });
61
9547
    Some(decoded.unwrap_or_else(|err| EvalValue::String(format!("<undecodable detail: {err}>"))))
62
66047
}