Lines
99.04 %
Functions
100 %
Branches
use super::*;
use nomiscript::{Compiler, HostFnSpec, Reader, SymbolTable, WasmType};
use wasmtime::{Caller, Linker, Store, Val};
fn plist_detail() -> EvalValue {
EvalValue::List(vec![
EvalValue::Symbol(":FIELD".to_string()),
EvalValue::String("a".to_string()),
EvalValue::Symbol(":N".to_string()),
EvalValue::I32(3),
])
}
fn field(name: &str, message: &str) -> EvalValue {
EvalValue::String(name.to_string()),
EvalValue::Symbol(":MESSAGE".to_string()),
EvalValue::String(message.to_string()),
fn nested_detail() -> EvalValue {
field("splits.0.value", "must not be zero"),
field("date", "required"),
fn link_failing_host_fns(linker: &mut Linker<()>) {
linker
.func_wrap_async("test", "fail", |mut caller: Caller<'_, ()>, ()| {
Box::new(async move {
let err = throw_condition(&mut caller, "boom", "from the host", &EvalValue::Nil);
Err::<i32, _>(err.await)
})
.unwrap();
.func_wrap_async("test", "fail-nested", |mut caller: Caller<'_, ()>, ()| {
let detail = nested_detail();
let err = throw_condition(&mut caller, "form-invalid", "2 invalid", &detail);
.func_wrap_async("test", "fail-bytes", |mut caller: Caller<'_, ()>, ()| {
let detail = EvalValue::Bytes(vec![1]);
let err = throw_condition(&mut caller, "boom", "m", &detail);
.func_wrap_async("test", "fail-detail", |mut caller: Caller<'_, ()>, ()| {
let detail = plist_detail();
let err = throw_condition(&mut caller, "BOOM", "from the host", &detail);
async fn run(src: &str) -> Result<EvalValue, EngineError> {
let specs = vec![
HostFnSpec::new("fail", "test", "fail").returns(WasmType::I32),
HostFnSpec::new("fail-detail", "test", "fail-detail").returns(WasmType::I32),
HostFnSpec::new("fail-nested", "test", "fail-nested").returns(WasmType::I32),
HostFnSpec::new("fail-bytes", "test", "fail-bytes").returns(WasmType::I32),
];
let program = Reader::parse(src).unwrap();
let mut compiler = Compiler::with_host_fns(specs.clone());
let mut symbols = SymbolTable::with_builtins();
symbols.register_host_fns(&specs);
let (bytes, result_ty) = compiler
.compile_eval_with_type(&program, &mut symbols)
let engine = build_engine(EngineOpts::baseline()).unwrap();
let module = compile_module(&engine, &bytes).unwrap();
let mut linker: Linker<()> = Linker::new(&engine);
link_nomi_raise_stub(&mut linker, &engine);
linker.allow_shadowing(true);
.func_wrap(
"nomi",
"__nomi_raise",
|mut caller: Caller<'_, ()>,
code: Option<wasmtime::Rooted<wasmtime::ArrayRef>>,
message: Option<wasmtime::Rooted<wasmtime::ArrayRef>>,
detail: Option<wasmtime::Rooted<wasmtime::AnyRef>>|
-> wasmtime::Result<()> { nomi_raise(&mut caller, code, message, detail) },
)
link_failing_host_fns(&mut linker);
let mut store: Store<()> = Store::new(&engine, ());
store.set_epoch_deadline(1_000);
let instance = linker.instantiate_async(&mut store, &module).await.unwrap();
let func = instance.get_func(&mut store, "nomi-eval").unwrap();
let mut results = [Val::AnyRef(None)];
func.call_async(&mut store, &[], &mut results)
.await
.map_err(|e| classify_runtime_error(&e))?;
let Val::AnyRef(any) = results[0] else {
panic!("nomi-eval returned non-anyref");
};
let handles = resolve_type_handles(&mut store, &instance).unwrap();
Ok(decode_eval_result(&mut store, any, result_ty, &handles).unwrap())
fn raised(code: &str, message: &str, detail: Option<EvalValue>) -> Result<EvalValue, EngineError> {
Err(EngineError::ScriptRaised {
code: code.to_string(),
message: message.to_string(),
detail,
fn text(value: &str) -> Result<EvalValue, EngineError> {
Ok(EvalValue::String(value.to_string()))
#[tokio::test(flavor = "current_thread")]
async fn a_host_thrown_condition_is_caught_by_its_code() {
let caught = run("(handler-case (fail) (boom (e) (error-message e)))").await;
assert_eq!(caught, text("from the host"));
async fn a_lower_case_host_code_is_upper_cased_for_dispatch() {
let caught = run("(handler-case (fail) (boom (e) (error-code e)))").await;
assert_eq!(caught, Ok(EvalValue::Symbol("BOOM".to_string())));
async fn a_host_thrown_condition_is_caught_by_the_catch_all_clause() {
let caught = run("(handler-case (fail) (t (e) (error-message e)))").await;
async fn an_uncaught_host_condition_reaches_the_raise_bridge() {
assert_eq!(run("(fail)").await, raised("BOOM", "from the host", None));
async fn a_clause_for_another_code_does_not_catch_it() {
let missed = run("(handler-case (fail) (other (e) 1))").await;
assert_eq!(missed, raised("BOOM", "from the host", None));
async fn a_host_detail_is_read_back_by_error_detail() {
let caught = run("(handler-case (fail-detail) (boom (e) (getf (error-detail e) :n)))").await;
assert_eq!(caught, Ok(EvalValue::I32(3)));
async fn a_host_condition_without_detail_has_a_nil_one() {
let caught = run("(handler-case (fail) (boom (e) (error-detail e)))").await;
assert_eq!(caught, Ok(EvalValue::Nil));
async fn an_uncaught_host_detail_reaches_the_bridge_decoded() {
assert_eq!(
run("(fail-detail)").await,
raised("BOOM", "from the host", Some(plist_detail()))
);
async fn a_host_throw_runs_the_unwind_protect_cleanup_then_propagates() {
let src =
"(handler-case (unwind-protect (fail) (print \"cleanup\")) (boom (e) (error-message e)))";
assert_eq!(run(src).await, text("from the host"));
async fn an_inner_clause_miss_falls_through_to_the_outer_handler() {
let src = "(handler-case (handler-case (fail) (other (e) \"inner\")) (boom (e) \"outer\"))";
assert_eq!(run(src).await, text("outer"));
async fn a_handler_inside_the_clause_of_another_catches_a_second_host_throw() {
let src = "(handler-case (fail) (boom (e) (handler-case (fail-detail) (boom (f) (error-message f)))))";
async fn instantiate_wat(
wat: &str,
engine: &wasmtime::Engine,
linker: &Linker<()>,
) -> (Store<()>, wasmtime::Instance) {
let module = compile_wat(engine, wat).unwrap();
let mut store: Store<()> = Store::new(engine, ());
(store, instance)
async fn throw_from_wat(exports: &str) -> String {
let wat = format!(
r#"(module (import "test" "t" (func $t)) {exports} (func (export "go") (call $t)))"#
.func_wrap_async("test", "t", |mut caller: Caller<'_, ()>, ()| {
Err::<(), _>(throw_condition(&mut caller, "x", "y", &EvalValue::Nil).await)
let (mut store, instance) = instantiate_wat(&wat, &engine, &linker).await;
let go = instance.get_func(&mut store, "go").unwrap();
let err = go.call_async(&mut store, &[], &mut []).await.unwrap_err();
err.root_cause().to_string()
async fn a_module_without_the_tag_reports_the_missing_export() {
assert!(throw_from_wat("").await.contains("nomi_error"));
const TAG_ONLY: &str = r#"(tag (export "nomi_error") (param anyref))"#;
async fn a_module_without_condition_new_reports_the_missing_export() {
assert!(throw_from_wat(TAG_ONLY).await.contains("condition_new"));
async fn a_condition_new_returning_null_is_reported() {
let exports = format!(
r#"{TAG_ONLY} (func (export "condition_new") (param anyref anyref anyref) (result anyref)
(ref.null any))"#
assert!(
throw_from_wat(&exports)
.contains("returned no condition")
async fn a_nested_plist_detail_keeps_its_structure_when_caught() {
let src = "(handler-case (fail-nested)
(form-invalid (e) (getf (car (cdr (error-detail e))) :message)))";
assert_eq!(run(src).await, text("required"));
let first = "(handler-case (fail-nested)
(form-invalid (e) (getf (car (error-detail e)) :field)))";
assert_eq!(run(first).await, text("splits.0.value"));
let count = "(handler-case (fail-nested) (form-invalid (e) (length (error-detail e))))";
assert_eq!(run(count).await, Ok(EvalValue::I32(2)));
async fn a_nested_plist_detail_reaches_the_bridge_with_the_same_nesting() {
run("(fail-nested)").await,
raised("FORM-INVALID", "2 invalid", Some(nested_detail()))
async fn an_unencodable_detail_is_a_clear_error_not_a_dropped_detail() {
let Err(EngineError::Trap(message)) = run("(fail-bytes)").await else {
panic!("expected a trap naming the unencodable detail");
assert!(message.contains("bytes or a commodity"), "{message}");