1
use super::*;
2
use nomiscript::{Compiler, HostFnSpec, Reader, SymbolTable, WasmType};
3
use wasmtime::{Caller, Linker, Store, Val};
4

            
5
4
fn plist_detail() -> EvalValue {
6
4
    EvalValue::List(vec![
7
4
        EvalValue::Symbol(":FIELD".to_string()),
8
4
        EvalValue::String("a".to_string()),
9
4
        EvalValue::Symbol(":N".to_string()),
10
4
        EvalValue::I32(3),
11
4
    ])
12
4
}
13

            
14
10
fn field(name: &str, message: &str) -> EvalValue {
15
10
    EvalValue::List(vec![
16
10
        EvalValue::Symbol(":FIELD".to_string()),
17
10
        EvalValue::String(name.to_string()),
18
10
        EvalValue::Symbol(":MESSAGE".to_string()),
19
10
        EvalValue::String(message.to_string()),
20
10
    ])
21
10
}
22

            
23
5
fn nested_detail() -> EvalValue {
24
5
    EvalValue::List(vec![
25
5
        field("splits.0.value", "must not be zero"),
26
5
        field("date", "required"),
27
5
    ])
28
5
}
29

            
30
16
fn link_failing_host_fns(linker: &mut Linker<()>) {
31
16
    linker
32
16
        .func_wrap_async("test", "fail", |mut caller: Caller<'_, ()>, ()| {
33
9
            Box::new(async move {
34
9
                let err = throw_condition(&mut caller, "boom", "from the host", &EvalValue::Nil);
35
9
                Err::<i32, _>(err.await)
36
9
            })
37
9
        })
38
        .unwrap();
39
16
    linker
40
16
        .func_wrap_async("test", "fail-nested", |mut caller: Caller<'_, ()>, ()| {
41
4
            Box::new(async move {
42
4
                let detail = nested_detail();
43
4
                let err = throw_condition(&mut caller, "form-invalid", "2 invalid", &detail);
44
4
                Err::<i32, _>(err.await)
45
4
            })
46
4
        })
47
        .unwrap();
48
16
    linker
49
16
        .func_wrap_async("test", "fail-bytes", |mut caller: Caller<'_, ()>, ()| {
50
1
            Box::new(async move {
51
1
                let detail = EvalValue::Bytes(vec![1]);
52
1
                let err = throw_condition(&mut caller, "boom", "m", &detail);
53
1
                Err::<i32, _>(err.await)
54
1
            })
55
1
        })
56
        .unwrap();
57
16
    linker
58
16
        .func_wrap_async("test", "fail-detail", |mut caller: Caller<'_, ()>, ()| {
59
3
            Box::new(async move {
60
3
                let detail = plist_detail();
61
3
                let err = throw_condition(&mut caller, "BOOM", "from the host", &detail);
62
3
                Err::<i32, _>(err.await)
63
3
            })
64
3
        })
65
        .unwrap();
66
16
}
67

            
68
16
async fn run(src: &str) -> Result<EvalValue, EngineError> {
69
16
    let specs = vec![
70
16
        HostFnSpec::new("fail", "test", "fail").returns(WasmType::I32),
71
16
        HostFnSpec::new("fail-detail", "test", "fail-detail").returns(WasmType::I32),
72
16
        HostFnSpec::new("fail-nested", "test", "fail-nested").returns(WasmType::I32),
73
16
        HostFnSpec::new("fail-bytes", "test", "fail-bytes").returns(WasmType::I32),
74
    ];
75
16
    let program = Reader::parse(src).unwrap();
76
16
    let mut compiler = Compiler::with_host_fns(specs.clone());
77
16
    let mut symbols = SymbolTable::with_builtins();
78
16
    symbols.register_host_fns(&specs);
79
16
    let (bytes, result_ty) = compiler
80
16
        .compile_eval_with_type(&program, &mut symbols)
81
16
        .unwrap();
82
16
    let engine = build_engine(EngineOpts::baseline()).unwrap();
83
16
    let module = compile_module(&engine, &bytes).unwrap();
84
16
    let mut linker: Linker<()> = Linker::new(&engine);
85
16
    link_nomi_raise_stub(&mut linker, &engine);
86
16
    linker.allow_shadowing(true);
87
16
    linker
88
        .func_wrap(
89
16
            "nomi",
90
16
            "__nomi_raise",
91
            |mut caller: Caller<'_, ()>,
92
             code: Option<wasmtime::Rooted<wasmtime::ArrayRef>>,
93
             message: Option<wasmtime::Rooted<wasmtime::ArrayRef>>,
94
             detail: Option<wasmtime::Rooted<wasmtime::AnyRef>>|
95
4
             -> wasmtime::Result<()> { nomi_raise(&mut caller, code, message, detail) },
96
        )
97
        .unwrap();
98
16
    link_failing_host_fns(&mut linker);
99
16
    let mut store: Store<()> = Store::new(&engine, ());
100
16
    store.set_epoch_deadline(1_000);
101
16
    let instance = linker.instantiate_async(&mut store, &module).await.unwrap();
102
16
    let func = instance.get_func(&mut store, "nomi-eval").unwrap();
103
16
    let mut results = [Val::AnyRef(None)];
104
16
    func.call_async(&mut store, &[], &mut results)
105
16
        .await
106
5
        .map_err(|e| classify_runtime_error(&e))?;
107
11
    let Val::AnyRef(any) = results[0] else {
108
        panic!("nomi-eval returned non-anyref");
109
    };
110
11
    let handles = resolve_type_handles(&mut store, &instance).unwrap();
111
11
    Ok(decode_eval_result(&mut store, any, result_ty, &handles).unwrap())
112
16
}
113

            
114
4
fn raised(code: &str, message: &str, detail: Option<EvalValue>) -> Result<EvalValue, EngineError> {
115
4
    Err(EngineError::ScriptRaised {
116
4
        code: code.to_string(),
117
4
        message: message.to_string(),
118
4
        detail,
119
4
    })
120
4
}
121

            
122
7
fn text(value: &str) -> Result<EvalValue, EngineError> {
123
7
    Ok(EvalValue::String(value.to_string()))
124
7
}
125

            
126
#[tokio::test(flavor = "current_thread")]
127
1
async fn a_host_thrown_condition_is_caught_by_its_code() {
128
1
    let caught = run("(handler-case (fail) (boom (e) (error-message e)))").await;
129
1
    assert_eq!(caught, text("from the host"));
130
1
}
131

            
132
#[tokio::test(flavor = "current_thread")]
133
1
async fn a_lower_case_host_code_is_upper_cased_for_dispatch() {
134
1
    let caught = run("(handler-case (fail) (boom (e) (error-code e)))").await;
135
1
    assert_eq!(caught, Ok(EvalValue::Symbol("BOOM".to_string())));
136
1
}
137

            
138
#[tokio::test(flavor = "current_thread")]
139
1
async fn a_host_thrown_condition_is_caught_by_the_catch_all_clause() {
140
1
    let caught = run("(handler-case (fail) (t (e) (error-message e)))").await;
141
1
    assert_eq!(caught, text("from the host"));
142
1
}
143

            
144
#[tokio::test(flavor = "current_thread")]
145
1
async fn an_uncaught_host_condition_reaches_the_raise_bridge() {
146
1
    assert_eq!(run("(fail)").await, raised("BOOM", "from the host", None));
147
1
}
148

            
149
#[tokio::test(flavor = "current_thread")]
150
1
async fn a_clause_for_another_code_does_not_catch_it() {
151
1
    let missed = run("(handler-case (fail) (other (e) 1))").await;
152
1
    assert_eq!(missed, raised("BOOM", "from the host", None));
153
1
}
154

            
155
#[tokio::test(flavor = "current_thread")]
156
1
async fn a_host_detail_is_read_back_by_error_detail() {
157
1
    let caught = run("(handler-case (fail-detail) (boom (e) (getf (error-detail e) :n)))").await;
158
1
    assert_eq!(caught, Ok(EvalValue::I32(3)));
159
1
}
160

            
161
#[tokio::test(flavor = "current_thread")]
162
1
async fn a_host_condition_without_detail_has_a_nil_one() {
163
1
    let caught = run("(handler-case (fail) (boom (e) (error-detail e)))").await;
164
1
    assert_eq!(caught, Ok(EvalValue::Nil));
165
1
}
166

            
167
#[tokio::test(flavor = "current_thread")]
168
1
async fn an_uncaught_host_detail_reaches_the_bridge_decoded() {
169
1
    assert_eq!(
170
1
        run("(fail-detail)").await,
171
1
        raised("BOOM", "from the host", Some(plist_detail()))
172
1
    );
173
1
}
174

            
175
#[tokio::test(flavor = "current_thread")]
176
1
async fn a_host_throw_runs_the_unwind_protect_cleanup_then_propagates() {
177
    let src =
178
1
        "(handler-case (unwind-protect (fail) (print \"cleanup\")) (boom (e) (error-message e)))";
179
1
    assert_eq!(run(src).await, text("from the host"));
180
1
}
181

            
182
#[tokio::test(flavor = "current_thread")]
183
1
async fn an_inner_clause_miss_falls_through_to_the_outer_handler() {
184
1
    let src = "(handler-case (handler-case (fail) (other (e) \"inner\")) (boom (e) \"outer\"))";
185
1
    assert_eq!(run(src).await, text("outer"));
186
1
}
187

            
188
#[tokio::test(flavor = "current_thread")]
189
1
async fn a_handler_inside_the_clause_of_another_catches_a_second_host_throw() {
190
1
    let src = "(handler-case (fail) (boom (e) (handler-case (fail-detail) (boom (f) (error-message f)))))";
191
1
    assert_eq!(run(src).await, text("from the host"));
192
1
}
193

            
194
3
async fn instantiate_wat(
195
3
    wat: &str,
196
3
    engine: &wasmtime::Engine,
197
3
    linker: &Linker<()>,
198
3
) -> (Store<()>, wasmtime::Instance) {
199
3
    let module = compile_wat(engine, wat).unwrap();
200
3
    let mut store: Store<()> = Store::new(engine, ());
201
3
    store.set_epoch_deadline(1_000);
202
3
    let instance = linker.instantiate_async(&mut store, &module).await.unwrap();
203
3
    (store, instance)
204
3
}
205

            
206
3
async fn throw_from_wat(exports: &str) -> String {
207
3
    let engine = build_engine(EngineOpts::baseline()).unwrap();
208
3
    let wat = format!(
209
3
        r#"(module (import "test" "t" (func $t)) {exports} (func (export "go") (call $t)))"#
210
    );
211
3
    let mut linker: Linker<()> = Linker::new(&engine);
212
3
    linker
213
3
        .func_wrap_async("test", "t", |mut caller: Caller<'_, ()>, ()| {
214
3
            Box::new(async move {
215
3
                Err::<(), _>(throw_condition(&mut caller, "x", "y", &EvalValue::Nil).await)
216
3
            })
217
3
        })
218
        .unwrap();
219
3
    let (mut store, instance) = instantiate_wat(&wat, &engine, &linker).await;
220
3
    let go = instance.get_func(&mut store, "go").unwrap();
221
3
    let err = go.call_async(&mut store, &[], &mut []).await.unwrap_err();
222
3
    err.root_cause().to_string()
223
3
}
224

            
225
#[tokio::test(flavor = "current_thread")]
226
1
async fn a_module_without_the_tag_reports_the_missing_export() {
227
1
    assert!(throw_from_wat("").await.contains("nomi_error"));
228
1
}
229

            
230
const TAG_ONLY: &str = r#"(tag (export "nomi_error") (param anyref))"#;
231

            
232
#[tokio::test(flavor = "current_thread")]
233
1
async fn a_module_without_condition_new_reports_the_missing_export() {
234
1
    assert!(throw_from_wat(TAG_ONLY).await.contains("condition_new"));
235
1
}
236

            
237
#[tokio::test(flavor = "current_thread")]
238
1
async fn a_condition_new_returning_null_is_reported() {
239
1
    let exports = format!(
240
1
        r#"{TAG_ONLY} (func (export "condition_new") (param anyref anyref anyref) (result anyref)
241
            (ref.null any))"#
242
    );
243
1
    assert!(
244
1
        throw_from_wat(&exports)
245
1
            .await
246
1
            .contains("returned no condition")
247
1
    );
248
1
}
249

            
250
#[tokio::test(flavor = "current_thread")]
251
1
async fn a_nested_plist_detail_keeps_its_structure_when_caught() {
252
1
    let src = "(handler-case (fail-nested)
253
1
                 (form-invalid (e) (getf (car (cdr (error-detail e))) :message)))";
254
1
    assert_eq!(run(src).await, text("required"));
255
1
    let first = "(handler-case (fail-nested)
256
1
                   (form-invalid (e) (getf (car (error-detail e)) :field)))";
257
1
    assert_eq!(run(first).await, text("splits.0.value"));
258
1
    let count = "(handler-case (fail-nested) (form-invalid (e) (length (error-detail e))))";
259
1
    assert_eq!(run(count).await, Ok(EvalValue::I32(2)));
260
1
}
261

            
262
#[tokio::test(flavor = "current_thread")]
263
1
async fn a_nested_plist_detail_reaches_the_bridge_with_the_same_nesting() {
264
1
    assert_eq!(
265
1
        run("(fail-nested)").await,
266
1
        raised("FORM-INVALID", "2 invalid", Some(nested_detail()))
267
1
    );
268
1
}
269

            
270
#[tokio::test(flavor = "current_thread")]
271
1
async fn an_unencodable_detail_is_a_clear_error_not_a_dropped_detail() {
272
1
    let Err(EngineError::Trap(message)) = run("(fail-bytes)").await else {
273
        panic!("expected a trap naming the unencodable detail");
274
    };
275
1
    assert!(message.contains("bytes or a commodity"), "{message}");
276
1
}