1
use super::*;
2
use nomiscript::Number;
3
use uuid::Uuid;
4
use wasmtime::{AnyRef, AsContextMut, Caller, Engine, Linker, Rooted, Store, StructRef, Val};
5

            
6
mod bool_decode_tests;
7
mod carry_closure_tests;
8
mod carry_instance_tests;
9
mod carry_money_tests;
10
mod carry_tests;
11
mod classify_tests;
12
mod condition_tests;
13
mod encode_tests;
14
mod entity_depth_tests;
15
mod global_export_tests;
16
mod host_condition_tests;
17
mod raise_tests;
18
mod ratio_decode_tests;
19
mod struct_decode_tests;
20
mod symbol_decode_tests;
21
mod wire_depth_pin_tests;
22

            
23
10
fn printed(value: &EvalValue) -> String {
24
10
    nomiscript::format_value(&nomiscript::Value::from(value.clone()))
25
10
}
26

            
27
#[test]
28
1
fn err_code_uses_script_raised_symbol_verbatim() {
29
1
    let (code, msg) = err_code_and_message(&EngineError::ScriptRaised {
30
1
        code: "no-such-account".to_string(),
31
1
        message: "id=42".to_string(),
32
1
        detail: None,
33
1
    });
34
1
    assert_eq!(code, "no-such-account");
35
1
    assert_eq!(msg, "id=42");
36
1
}
37

            
38
#[test]
39
1
fn err_code_maps_commodity_mismatch_script_raise_to_symbol() {
40
    // Commodity mismatch now `throw`s `$nomi_error` in-guest (ADR-0026);
41
    // uncaught, the boundary wrapper bridges it to `__nomi_raise` and the
42
    // classifier yields `ScriptRaised`. The code is the reader-folded
43
    // (upper-cased) symbol `COMMODITY-MISMATCH`, like any script raise —
44
    // `err_code_and_message` passes a `ScriptRaised` code through verbatim.
45
1
    let (code, msg) = err_code_and_message(&EngineError::ScriptRaised {
46
1
        code: "COMMODITY-MISMATCH".to_string(),
47
1
        message: "USD vs EUR".to_string(),
48
1
        detail: None,
49
1
    });
50
1
    assert_eq!(code, "COMMODITY-MISMATCH");
51
1
    assert_eq!(msg, "USD vs EUR");
52
1
}
53

            
54
#[test]
55
1
fn err_code_falls_back_to_runtime_for_generic_traps() {
56
1
    let (code, msg) = err_code_and_message(&EngineError::Trap("oops".to_string()));
57
1
    assert_eq!(code, "runtime");
58
1
    assert_eq!(msg, "oops");
59
1
}
60

            
61
#[test]
62
1
fn err_code_maps_out_of_fuel_to_runtime_with_diagnostic_message() {
63
1
    let (code, msg) = err_code_and_message(&EngineError::OutOfFuel);
64
1
    assert_eq!(code, "runtime");
65
1
    assert_eq!(msg, "fuel exhausted");
66
1
}
67

            
68
3
fn store_with_fuel<T: Default>(engine: &Engine, fuel: u64) -> Store<T> {
69
3
    let mut store = Store::new(engine, T::default());
70
3
    store
71
3
        .set_fuel(fuel)
72
3
        .expect("set_fuel must succeed for fresh store");
73
3
    store.set_epoch_deadline(1);
74
3
    store
75
3
}
76

            
77
#[test]
78
1
fn baseline_engine_omits_fuel() {
79
1
    let opts = EngineOpts::baseline();
80
1
    assert!(!opts.fuel);
81
1
    let _engine = build_engine(opts).expect("baseline engine must build");
82
1
}
83

            
84
#[test]
85
1
fn with_fuel_engine_supports_set_fuel() {
86
1
    let engine = build_engine(EngineOpts::baseline().with_fuel()).unwrap();
87
1
    let mut store: Store<()> = Store::new(&engine, ());
88
1
    store
89
1
        .set_fuel(1_000)
90
1
        .expect("set_fuel works only when consume_fuel is on");
91
1
}
92

            
93
#[test]
94
1
fn module_cache_returns_same_module_for_same_bytecode() {
95
1
    let engine = build_engine(EngineOpts::baseline()).unwrap();
96
1
    let cache = ModuleCache::new();
97
1
    let wat = r#"(module (func (export "answer") (result i64) (i64.const 42)))"#;
98
1
    let bytes = wat::parse_str(wat).unwrap();
99
1
    assert_eq!(cache.len().unwrap(), 0);
100
1
    let _first = cache.get_or_compile(&engine, &bytes).unwrap();
101
1
    assert_eq!(cache.len().unwrap(), 1);
102
1
    let _second = cache.get_or_compile(&engine, &bytes).unwrap();
103
1
    assert_eq!(cache.len().unwrap(), 1);
104
1
}
105

            
106
#[test]
107
1
fn module_cache_clones_share_storage() {
108
1
    let engine = build_engine(EngineOpts::baseline()).unwrap();
109
1
    let cache_a = ModuleCache::new();
110
1
    let cache_b = cache_a.clone();
111
1
    let wat = r#"(module (func (export "answer") (result i64) (i64.const 42)))"#;
112
1
    let bytes = wat::parse_str(wat).unwrap();
113
1
    let _ = cache_a.get_or_compile(&engine, &bytes).unwrap();
114
1
    assert_eq!(cache_b.len().unwrap(), 1);
115
1
}
116

            
117
#[test]
118
1
fn runs_trivial_i64_export() {
119
1
    let engine = build_engine(EngineOpts::baseline().with_fuel()).unwrap();
120
1
    let module = compile_wat(
121
1
        &engine,
122
1
        r#"(module (func (export "answer") (result i64) (i64.const 42)))"#,
123
1
    )
124
1
    .unwrap();
125
1
    let mut store: Store<()> = store_with_fuel(&engine, 100_000);
126
1
    let result = call_i64_export(&engine, &mut store, &module, "answer").unwrap();
127
1
    assert_eq!(result, 42);
128
1
}
129

            
130
#[test]
131
1
fn missing_export_returns_typed_error() {
132
1
    let engine = build_engine(EngineOpts::baseline().with_fuel()).unwrap();
133
1
    let module = compile_wat(
134
1
        &engine,
135
1
        r#"(module (func (export "answer") (result i64) (i64.const 42)))"#,
136
1
    )
137
1
    .unwrap();
138
1
    let mut store: Store<()> = store_with_fuel(&engine, 100_000);
139
1
    let err = call_i64_export(&engine, &mut store, &module, "missing").unwrap_err();
140
1
    assert!(matches!(err, EngineError::MissingExport(name) if name == "missing"));
141
1
}
142

            
143
#[test]
144
1
fn fuel_exhaustion_yields_typed_error() {
145
1
    let engine = build_engine(EngineOpts::baseline().with_fuel()).unwrap();
146
1
    let module = compile_wat(
147
1
        &engine,
148
1
        r#"
149
1
            (module
150
1
              (func (export "spin") (result i64)
151
1
                (loop (br 0))
152
1
                (i64.const 0)))
153
1
            "#,
154
1
    )
155
1
    .unwrap();
156
1
    let mut store: Store<()> = store_with_fuel(&engine, 1_000);
157
1
    let err = call_i64_export(&engine, &mut store, &module, "spin").unwrap_err();
158
1
    assert!(matches!(err, EngineError::OutOfFuel), "got: {err:?}");
159
1
}
160

            
161
#[test]
162
1
fn epoch_interrupt_yields_typed_error() {
163
1
    let engine = build_engine(EngineOpts::baseline().with_fuel()).unwrap();
164
1
    let module = compile_wat(
165
1
        &engine,
166
1
        r#"
167
1
            (module
168
1
              (func (export "spin") (result i64)
169
1
                (loop (br 0))
170
1
                (i64.const 0)))
171
1
            "#,
172
1
    )
173
1
    .unwrap();
174
1
    let mut store: Store<()> = Store::new(&engine, ());
175
1
    store.set_fuel(1_000_000_000).unwrap();
176
1
    store.set_epoch_deadline(1);
177
1
    engine.increment_epoch();
178
1
    engine.increment_epoch();
179
1
    let err = call_i64_export(&engine, &mut store, &module, "spin").unwrap_err();
180
1
    assert!(
181
1
        matches!(err, EngineError::EpochInterrupt | EngineError::OutOfFuel),
182
        "got: {err:?}"
183
    );
184
1
}
185

            
186
#[test]
187
1
fn malformed_module_bytes_yield_compile_error() {
188
1
    let engine = build_engine(EngineOpts::baseline()).unwrap();
189
1
    let err = compile_module(&engine, b"not wasm bytes").unwrap_err();
190
1
    assert!(matches!(err, EngineError::Compile(_)));
191
1
}
192

            
193
#[tokio::test(flavor = "current_thread")]
194
1
async fn alloc_pair_chain_builds_list_head_in_order() {
195
    use wasmtime::I31;
196

            
197
    // Self-recursive $pair shape matching `CompileContext::new_skeleton`.
198
    // The module exports `pair_new` (the helper alloc_pair_chain re-enters
199
    // for each element) and a `go` entry that asks the test host fn for a
200
    // 3-element chain, then walks it to confirm the host-built structure.
201
1
    let wat = r#"
202
1
        (module
203
1
          (rec
204
1
            (type $pair (struct (field anyref) (field (ref null $pair)))))
205
1
          (import "test" "make_chain"
206
1
            (func $make_chain (result (ref null struct))))
207
1
          (func $pair_new (export "pair_new")
208
1
            (param $car anyref) (param $cdr (ref null $pair))
209
1
            (result (ref null $pair))
210
1
            (struct.new $pair (local.get $car) (local.get $cdr)))
211
1
          (func $length (param $head (ref null $pair)) (result i32)
212
1
            (local $count i32)
213
1
            (block $exit
214
1
              (loop $more
215
1
                (br_if $exit (ref.is_null (local.get $head)))
216
1
                (local.set $count (i32.add (local.get $count) (i32.const 1)))
217
1
                (local.set $head
218
1
                  (struct.get $pair 1 (local.get $head)))
219
1
                (br $more)))
220
1
            (local.get $count))
221
1
          (func (export "go") (result i32)
222
1
            (local $head (ref null $pair))
223
1
            (local.set $head
224
1
              (ref.cast (ref null $pair) (call $make_chain)))
225
1
            (call $length (local.get $head))))
226
1
        "#;
227

            
228
1
    let engine = build_engine(EngineOpts::baseline()).unwrap();
229
1
    let module = compile_wat(&engine, wat).unwrap();
230
1
    let mut linker: Linker<()> = Linker::new(&engine);
231
1
    linker
232
1
        .func_wrap_async("test", "make_chain", |mut caller: Caller<'_, ()>, ()| {
233
1
            Box::new(async move {
234
1
                let items: Vec<Option<Rooted<AnyRef>>> = (0..3)
235
3
                    .map(|i| {
236
3
                        Some(AnyRef::from_i31(
237
3
                            caller.as_context_mut(),
238
3
                            I31::wrapping_u32(i),
239
3
                        ))
240
3
                    })
241
                    .collect();
242
1
                alloc_pair_chain(&mut caller, items).await
243
1
            })
244
1
        })
245
        .unwrap();
246
1
    let mut store: Store<()> = Store::new(&engine, ());
247
1
    store.set_epoch_deadline(1_000);
248
1
    let instance = linker.instantiate_async(&mut store, &module).await.unwrap();
249
1
    let go = instance.get_func(&mut store, "go").unwrap();
250
1
    let mut results = [Val::I32(0)];
251
1
    go.call_async(&mut store, &[], &mut results).await.unwrap();
252
1
    assert_eq!(results[0].i32(), Some(3));
253
1
}
254

            
255
#[tokio::test(flavor = "current_thread")]
256
1
async fn alloc_pair_chain_errors_without_pair_new_export() {
257
    use wasmtime::Func;
258

            
259
    // No `pair_new` export — the host fn must surface the missing-export
260
    // contract violation rather than panic or silently succeed.
261
1
    let wat = r#"
262
1
        (module
263
1
          (import "test" "try_chain"
264
1
            (func $try))
265
1
          (func (export "go") (call $try)))
266
1
        "#;
267
1
    let engine = build_engine(EngineOpts::baseline()).unwrap();
268
1
    let module = compile_wat(&engine, wat).unwrap();
269
1
    let mut linker: Linker<()> = Linker::new(&engine);
270
1
    linker
271
1
        .func_wrap_async("test", "try_chain", |mut caller: Caller<'_, ()>, ()| {
272
1
            Box::new(async move {
273
1
                let empty: Vec<Option<Rooted<AnyRef>>> = Vec::new();
274
1
                let result = alloc_pair_chain(&mut caller, empty).await;
275
1
                match result {
276
                    Err(e) => {
277
1
                        let msg = e.to_string();
278
1
                        assert!(
279
1
                            msg.contains("pair_new"),
280
                            "expected pair_new-missing error, got: {msg}"
281
                        );
282
1
                        Ok(())
283
                    }
284
                    Ok(_) => Err(wasmtime::Error::msg(
285
                        "alloc_pair_chain unexpectedly succeeded without pair_new",
286
                    )),
287
                }
288
1
            })
289
1
        })
290
        .unwrap();
291
1
    let mut store: Store<()> = Store::new(&engine, ());
292
1
    store.set_epoch_deadline(1_000);
293
1
    let instance = linker.instantiate_async(&mut store, &module).await.unwrap();
294
1
    let go: Func = instance.get_func(&mut store, "go").unwrap();
295
1
    let mut results: [Val; 0] = [];
296
1
    go.call_async(&mut store, &[], &mut results).await.unwrap();
297
1
}
298

            
299
#[tokio::test(flavor = "current_thread")]
300
1
async fn alloc_commodity_ref_builds_atomic_via_reentry() {
301
    // ADR-0028 E0: the host builds a commodity by re-entering the module's
302
    // exported `commodity_new`, which writes a NULL unit-term (= atomic).
303
    // The `$commodity` shape matches `CompileContext::new_skeleton` (5
304
    // fields, the 5th a `(ref null $unit_term)`). `go` asks the host for a
305
    // 7/2 commodity with UUID hi=1/lo=2, then reads numer, hi, lo, and
306
    // whether the term is null.
307
1
    let wat = r#"
308
1
        (module
309
1
          (type $unit_term (array (mut i64)))
310
1
          (type $commodity
311
1
            (struct (field i64) (field i64) (field i64) (field i64)
312
1
                    (field (ref null $unit_term))))
313
1
          (import "test" "make_commodity"
314
1
            (func $make_commodity (result (ref null struct))))
315
1
          (func $commodity_new (export "commodity_new")
316
1
            (param $n i64) (param $d i64) (param $hi i64) (param $lo i64)
317
1
            (result (ref $commodity))
318
1
            (struct.new $commodity
319
1
              (local.get $n) (local.get $d) (local.get $hi) (local.get $lo)
320
1
              (ref.null $unit_term)))
321
1
          (func (export "go") (result i64 i64 i64 i32)
322
1
            (local $c (ref $commodity))
323
1
            (local.set $c
324
1
              (ref.cast (ref $commodity) (call $make_commodity)))
325
1
            (struct.get $commodity 0 (local.get $c))
326
1
            (struct.get $commodity 2 (local.get $c))
327
1
            (struct.get $commodity 3 (local.get $c))
328
1
            (ref.is_null (struct.get $commodity 4 (local.get $c)))))
329
1
        "#;
330

            
331
1
    let engine = build_engine(EngineOpts::baseline()).unwrap();
332
1
    let module = compile_wat(&engine, wat).unwrap();
333
1
    let mut linker: Linker<()> = Linker::new(&engine);
334
1
    linker
335
        .func_wrap_async(
336
1
            "test",
337
1
            "make_commodity",
338
1
            |mut caller: Caller<'_, ()>, ()| {
339
1
                Box::new(async move {
340
1
                    let id = Uuid::from_u128((1u128 << 64) | 2u128);
341
1
                    Ok(Some(alloc_commodity_ref(&mut caller, 7, 2, id).await?))
342
1
                })
343
1
            },
344
        )
345
        .unwrap();
346
1
    let mut store: Store<()> = Store::new(&engine, ());
347
1
    store.set_epoch_deadline(1_000);
348
1
    let instance = linker.instantiate_async(&mut store, &module).await.unwrap();
349
1
    let go = instance.get_func(&mut store, "go").unwrap();
350
1
    let mut results = [Val::I64(0), Val::I64(0), Val::I64(0), Val::I32(0)];
351
1
    go.call_async(&mut store, &[], &mut results).await.unwrap();
352
1
    assert_eq!(results[0].i64(), Some(7), "numer");
353
1
    assert_eq!(results[1].i64(), Some(1), "commodity_hi");
354
1
    assert_eq!(results[2].i64(), Some(2), "commodity_lo");
355
1
    assert_eq!(results[3].i32(), Some(1), "atomic ⇒ null unit-term");
356
1
}
357

            
358
#[tokio::test(flavor = "current_thread")]
359
1
async fn alloc_commodity_ref_errors_without_commodity_new_export() {
360
    use wasmtime::Func;
361

            
362
    // No `commodity_new` export — the host fn must surface the missing-
363
    // export contract violation rather than panic or silently succeed.
364
1
    let wat = r#"
365
1
        (module
366
1
          (import "test" "try_make"
367
1
            (func $try))
368
1
          (func (export "go") (call $try)))
369
1
        "#;
370
1
    let engine = build_engine(EngineOpts::baseline()).unwrap();
371
1
    let module = compile_wat(&engine, wat).unwrap();
372
1
    let mut linker: Linker<()> = Linker::new(&engine);
373
1
    linker
374
1
        .func_wrap_async("test", "try_make", |mut caller: Caller<'_, ()>, ()| {
375
1
            Box::new(async move {
376
1
                let id = Uuid::from_u128(0);
377
1
                match alloc_commodity_ref(&mut caller, 1, 1, id).await {
378
                    Err(e) => {
379
1
                        let msg = e.to_string();
380
1
                        assert!(
381
1
                            msg.contains("commodity_new"),
382
                            "expected commodity_new-missing error, got: {msg}"
383
                        );
384
1
                        Ok(())
385
                    }
386
                    Ok(_) => Err(wasmtime::Error::msg(
387
                        "alloc_commodity_ref unexpectedly succeeded without commodity_new",
388
                    )),
389
                }
390
1
            })
391
1
        })
392
        .unwrap();
393
1
    let mut store: Store<()> = Store::new(&engine, ());
394
1
    store.set_epoch_deadline(1_000);
395
1
    let instance = linker.instantiate_async(&mut store, &module).await.unwrap();
396
1
    let go: Func = instance.get_func(&mut store, "go").unwrap();
397
1
    let mut results: [Val; 0] = [];
398
1
    go.call_async(&mut store, &[], &mut results).await.unwrap();
399
1
}
400

            
401
#[test]
402
1
fn unit_term_algebra_merges_sorts_and_cancels() {
403
    use nomiscript::{Compiler, Reader, SymbolTable};
404

            
405
15
    fn ar(a: Rooted<AnyRef>) -> Val {
406
15
        Val::AnyRef(Some(a))
407
15
    }
408

            
409
    // Compile a trivial program just to obtain the skeleton, which exports
410
    // the unit-term helpers. Then exercise the sorted-merge directly: it is
411
    // the riskiest hand-written wasm in ADR-0028 E1/E2.
412
1
    let engine = build_engine(EngineOpts::baseline().with_fuel()).unwrap();
413
1
    let mut compiler = Compiler::new();
414
1
    let mut symbols = SymbolTable::with_builtins();
415
1
    let program = Reader::parse("0").unwrap();
416
1
    let (bytes, _) = compiler
417
1
        .compile_eval_with_type(&program, &mut symbols)
418
1
        .expect("eval compile");
419
1
    let module = compile_module(&engine, &bytes).expect("module");
420
1
    let mut linker: Linker<()> = Linker::new(&engine);
421
1
    link_nomi_raise_stub(&mut linker, &engine);
422
1
    let mut store: Store<()> = Store::new(&engine, ());
423
1
    store.set_fuel(100_000_000).unwrap();
424
1
    store.set_epoch_deadline(1);
425
1
    let instance = linker.instantiate(&mut store, &module).unwrap();
426

            
427
7
    let call_ref = |store: &mut Store<()>, name: &str, args: &[Val]| -> Rooted<AnyRef> {
428
7
        let f = instance.get_func(&mut *store, name).unwrap();
429
7
        let mut res = [Val::AnyRef(None)];
430
7
        f.call(&mut *store, args, &mut res).unwrap();
431
7
        match &res[0] {
432
7
            Val::AnyRef(Some(a)) => *a,
433
            other => panic!("{name} returned {other:?}"),
434
        }
435
7
    };
436
7
    let read_term = |store: &mut Store<()>, t: Rooted<AnyRef>| -> Vec<i64> {
437
7
        let arr = t.unwrap_array(&mut *store).unwrap();
438
7
        let len = arr.len(&mut *store).unwrap();
439
7
        (0..len)
440
24
            .map(|i| arr.get(&mut *store, i).unwrap().i64().unwrap())
441
            .collect()
442
7
    };
443
2
    let singleton = |store: &mut Store<()>, hi: i64, lo: i64| -> Rooted<AnyRef> {
444
2
        call_ref(store, "unit_singleton", &[Val::I64(hi), Val::I64(lo)])
445
2
    };
446

            
447
1
    let usd = singleton(&mut store, 10, 20);
448
1
    let eur = singleton(&mut store, 30, 40);
449
1
    assert_eq!(read_term(&mut store, usd), vec![10, 20, 1]);
450
1
    assert_eq!(read_term(&mut store, eur), vec![30, 40, 1]);
451

            
452
    // Disjoint merge is sorted by (hi,lo), order-independent.
453
1
    let usd_eur = call_ref(&mut store, "unit_mul", &[ar(usd), ar(eur)]);
454
1
    assert_eq!(read_term(&mut store, usd_eur), vec![10, 20, 1, 30, 40, 1]);
455
1
    let eur_usd = call_ref(&mut store, "unit_mul", &[ar(eur), ar(usd)]);
456
1
    assert_eq!(read_term(&mut store, eur_usd), vec![10, 20, 1, 30, 40, 1]);
457

            
458
    // Matching key sums exponents.
459
1
    let usd2 = call_ref(&mut store, "unit_mul", &[ar(usd), ar(usd)]);
460
1
    assert_eq!(read_term(&mut store, usd2), vec![10, 20, 2]);
461

            
462
    // Cancellation drops the zero-exponent entry → empty (dimensionless).
463
1
    let canceled = call_ref(&mut store, "unit_div", &[ar(usd), ar(usd)]);
464
1
    assert_eq!(read_term(&mut store, canceled), Vec::<i64>::new());
465

            
466
    // negate flips exponents.
467
1
    let neg_usd = call_ref(&mut store, "unit_negate", &[ar(usd)]);
468
1
    assert_eq!(read_term(&mut store, neg_usd), vec![10, 20, -1]);
469

            
470
3
    let eq = |store: &mut Store<()>, a: Rooted<AnyRef>, b: Rooted<AnyRef>| -> i32 {
471
3
        let f = instance.get_func(&mut *store, "unit_eq").unwrap();
472
3
        let mut res = [Val::I32(0)];
473
3
        f.call(&mut *store, &[ar(a), ar(b)], &mut res).unwrap();
474
3
        res[0].i32().unwrap()
475
3
    };
476
1
    assert_eq!(eq(&mut store, usd, usd), 1);
477
1
    assert_eq!(eq(&mut store, usd, eur), 0);
478
    // Same multiset, built two ways, compares equal.
479
1
    assert_eq!(eq(&mut store, usd_eur, eur_usd), 1);
480
1
}
481

            
482
#[tokio::test(flavor = "current_thread")]
483
1
async fn compound_money_arithmetic_end_to_end() {
484
    use nomiscript::{Compiler, HostFnSpec, Reader, SymbolTable, WasmType};
485

            
486
    // Two distinct currencies, each produced atomic at 3/1 by a host fn.
487
    const USD: u128 = 0x1111_1111_1111_1111_2222_2222_2222_2222;
488
    const EUR: u128 = 0x3333_3333_3333_3333_4444_4444_4444_4444;
489

            
490
12
    async fn run(src: &str) -> Result<EvalValue, String> {
491
12
        let specs = vec![
492
12
            HostFnSpec::new("usd", "test", "usd").returns(WasmType::Commodity),
493
12
            HostFnSpec::new("eur", "test", "eur").returns(WasmType::Commodity),
494
12
            HostFnSpec::new("sink", "test", "sink")
495
12
                .with_params(vec![WasmType::Commodity])
496
12
                .returns(WasmType::I32),
497
        ];
498
12
        let program = Reader::parse(src).unwrap();
499
12
        let mut compiler = Compiler::with_host_fns(specs.clone());
500
12
        let mut symbols = SymbolTable::with_builtins();
501
12
        symbols.register_host_fns(&specs);
502
12
        let (bytes, result_ty) = compiler
503
12
            .compile_eval_with_type(&program, &mut symbols)
504
            .map_err(|e| e.to_string())?;
505
12
        let engine = build_engine(EngineOpts::baseline().with_fuel()).unwrap();
506
12
        let module = compile_module(&engine, &bytes).map_err(|e| format!("{e:?}"))?;
507
12
        let mut linker: Linker<()> = Linker::new(&engine);
508
12
        link_nomi_raise_stub(&mut linker, &engine);
509
12
        linker
510
22
            .func_wrap_async("test", "usd", |mut caller: Caller<'_, ()>, ()| {
511
22
                Box::new(async move {
512
                    Ok(Some(
513
22
                        alloc_commodity_ref(&mut caller, 3, 1, Uuid::from_u128(USD)).await?,
514
                    ))
515
22
                })
516
22
            })
517
            .unwrap();
518
12
        linker
519
12
            .func_wrap_async("test", "eur", |mut caller: Caller<'_, ()>, ()| {
520
1
                Box::new(async move {
521
                    Ok(Some(
522
1
                        alloc_commodity_ref(&mut caller, 3, 1, Uuid::from_u128(EUR)).await?,
523
                    ))
524
1
                })
525
1
            })
526
            .unwrap();
527
        // The sink only reaches its body for ATOMIC args — a compound arg is
528
        // rejected by the `commodity_assert_atomic` guard before this runs.
529
12
        linker
530
            .func_wrap_async(
531
12
                "test",
532
12
                "sink",
533
3
                |mut caller: Caller<'_, ()>, (arg,): (Option<Rooted<StructRef>>,)| {
534
3
                    Box::new(async move {
535
3
                        read_commodity_arg(&mut caller, arg)?;
536
3
                        Ok(0i32)
537
3
                    })
538
3
                },
539
            )
540
            .unwrap();
541
12
        let mut store: Store<()> = Store::new(&engine, ());
542
12
        store.set_fuel(1_000_000_000).unwrap();
543
12
        store.set_epoch_deadline(1);
544
12
        let instance = linker
545
12
            .instantiate_async(&mut store, &module)
546
12
            .await
547
            .map_err(|e| format!("{e:?}"))?;
548
12
        let func = instance.get_func(&mut store, "nomi-eval").unwrap();
549
12
        let mut results = [Val::AnyRef(None)];
550
12
        func.call_async(&mut store, &[], &mut results)
551
12
            .await
552
2
            .map_err(|e| e.to_string())?;
553
10
        let any = match &results[0] {
554
10
            Val::AnyRef(a) => *a,
555
            _ => return Err("nomi-eval returned non-anyref".to_string()),
556
        };
557
10
        let handles = resolve_type_handles(&mut store, &instance).map_err(|e| e.to_string())?;
558
10
        decode_eval_result(&mut store, any, result_ty, &handles).map_err(|e| e.to_string())
559
12
    }
560

            
561
    // money ÷ money, same currency → dimensionless → decodes as a Number.
562
1
    assert_eq!(
563
1
        run("(/ (usd) (usd))").await,
564
1
        Ok(EvalValue::Ratio { numer: 1, denom: 1 })
565
    );
566
    // money + money, same currency → atomic money (the null-term fast path).
567
1
    match run("(+ (usd) (usd))").await {
568
1
        Ok(EvalValue::Commodity { numer, denom, .. }) => assert_eq!((numer, denom), (6, 1)),
569
        other => panic!("expected atomic commodity 6/1, got {other:?}"),
570
    }
571
    // money + money, different currency → COMMODITY-MISMATCH throw.
572
1
    assert!(run("(+ (usd) (eur))").await.is_err());
573
    // money × money → compound, no host wire form yet → decode error.
574
1
    assert!(
575
1
        run("(* (usd) (usd))")
576
1
            .await
577
            .unwrap_err()
578
1
            .contains("compound")
579
    );
580
    // an ATOMIC money passes the host-border guard.
581
1
    assert_eq!(run("(sink (usd))").await, Ok(EvalValue::I32(0)));
582
    // a COMPOUND money is rejected at the host border by the guard.
583
1
    assert!(run("(sink (* (usd) (usd)))").await.is_err());
584
    // a COMPOUND money riding a $pair cell is rejected by the pair-car
585
    // renderer too — it must NOT slip through as id-zero atomic money
586
    // (the pair-decode border is field-4-aware, same as the top-level one).
587
1
    assert!(
588
1
        run("(list (* (usd) (usd)))")
589
1
            .await
590
            .unwrap_err()
591
1
            .contains("compound")
592
    );
593
    // an atomic money in a list cell still renders (sanity: the field-4
594
    // gate doesn't reject the null-term atomic case).
595
1
    assert!(run("(list (usd))").await.is_ok());
596
    // dimensionless × atomic → a `[(usd,1)]` singleton term that
597
    // `commodity_new_with_term` canonicalizes back to ATOMIC usd: it decodes
598
    // as an atomic commodity (3/1) and passes the host-border atomic guard.
599
1
    match run("(* (/ (usd) (usd)) (usd))").await {
600
1
        Ok(EvalValue::Commodity { numer, denom, .. }) => assert_eq!((numer, denom), (3, 1)),
601
        other => panic!("expected atomic commodity 3/1, got {other:?}"),
602
    }
603
1
    assert_eq!(
604
1
        run("(sink (* (/ (usd) (usd)) (usd)))").await,
605
1
        Ok(EvalValue::I32(0))
606
    );
607
    // ADR-0033 Phase 6: a Commodity riding a dynamically widened AnyRef
608
    // result (here, `or`'s Bool-vs-Commodity arm mismatch) decodes through
609
    // the SAME `decode_commodity` a fixed-type Commodity result uses. The
610
    // test operand must be a genuine RUNTIME Bool (`(sink (usd))` is a host
611
    // fn call, never constant-folded) — a literal comparison like `(= 1 2)`
612
    // folds away at compile time, so the whole form resolves to the fixed
613
    // `Commodity` type directly and never reaches the dynamic path at all.
614
1
    match run("(or (> (sink (usd)) 5) (usd))").await {
615
1
        Ok(EvalValue::Commodity { numer, denom, .. }) => assert_eq!((numer, denom), (3, 1)),
616
1
        other => {
617
1
            panic!("expected atomic commodity 3/1 through the dynamic AnyRef path, got {other:?}")
618
1
        }
619
1
    }
620
1
    // ADR-0033 Phase 6 review fix: `decode_dynamic_anyref` — `decode_car`'s
621
1
    // AnyRef-element counterpart, reached from INSIDE a `$pair` chain
622
1
    // rather than a bare top-level result — has its own per-kind dispatch
623
1
    // and needs its own coverage. Mixing a Commodity car with a String car
624
1
    // forces the chain's element to AnyRef, exercising
625
1
    // `AnyRefKind::Commodity` there via `decode_commodity`, the same
626
1
    // renderer a fixed `PairRef(Commodity)` list already uses.
627
1
    assert_eq!(
628
1
        printed(&run(r#"(list (usd) "x")"#).await.unwrap()),
629
1
        "((:commodity 3 :id \"11111111-1111-1111-2222-222222222222\") \"x\")"
630
1
    );
631
1
}
632

            
633
/// Compiles+runs `form` (an `ent` call site that must widen the entity away
634
/// from its fixed type — either the top-level `(or (> (flag) 5) (ent))`, or
635
/// a `$pair`-element position like `(list (ent) "x")`) where `ent` allocates
636
/// an entity of `kind` (re-entering the compiled module's own
637
/// `alloc_<kind>` export via `alloc_entity_via_export`, from `fields` — each
638
/// a plain `StringRef`, which covers every entity whose same-shaped
639
/// sibling is also all-string) and decodes the widened result. Shared by
640
/// every ADR-0033 Phase 6 "entity riding a dynamic AnyRef" test below,
641
/// including the ones exercising `decode_dynamic_anyref` (a car inside a
642
/// chain) rather than `decode_dynamic_anyref` (a bare top-level result).
643
7
async fn run_entity_widened_to_anyref(
644
7
    kind: nomiscript::EntityKind,
645
7
    alloc_export: &str,
646
7
    fields: &[&[u8]],
647
7
    form: &str,
648
7
) -> EvalValue {
649
7
    try_entity_widened_to_anyref(kind, alloc_export, fields, form)
650
7
        .await
651
        .unwrap()
652
7
}
653

            
654
/// [`run_entity_widened_to_anyref`], surfacing the decode result.
655
9
async fn try_entity_widened_to_anyref(
656
9
    kind: nomiscript::EntityKind,
657
9
    alloc_export: &str,
658
9
    fields: &[&[u8]],
659
9
    form: &str,
660
9
) -> wasmtime::Result<EvalValue> {
661
    use nomiscript::{Compiler, HostFnSpec, Reader, SymbolTable, WasmType};
662

            
663
9
    let specs = vec![
664
        // A runtime I32 source: the widening test must be a genuine host fn
665
        // call, never constant-folded — `(= 1 2)` would fold away at
666
        // compile time and resolve the whole form to the fixed EntityRef
667
        // type directly, never reaching the dynamic AnyRef path.
668
9
        HostFnSpec::new("flag", "test", "flag").returns(WasmType::I32),
669
9
        HostFnSpec::new("ent", "test", "ent").returns(WasmType::EntityRef(kind)),
670
    ];
671
9
    let program = Reader::parse(form).unwrap();
672
9
    let mut compiler = Compiler::with_host_fns(specs.clone());
673
9
    let mut symbols = SymbolTable::with_builtins();
674
9
    symbols.register_host_fns(&specs);
675
9
    let (bytes, result_ty) = compiler
676
9
        .compile_eval_with_type(&program, &mut symbols)
677
9
        .unwrap();
678
9
    assert_ne!(
679
9
        result_ty,
680
9
        Some(WasmType::EntityRef(kind)),
681
        "test setup regression: {form:?} must widen away from the fixed EntityRef type"
682
    );
683
9
    let engine = build_engine(EngineOpts::baseline().with_fuel()).unwrap();
684
9
    let module = compile_module(&engine, &bytes).unwrap();
685
9
    let mut linker: Linker<()> = Linker::new(&engine);
686
9
    link_nomi_raise_stub(&mut linker, &engine);
687
9
    linker
688
9
        .func_wrap_async("test", "flag", |_: Caller<'_, ()>, ()| {
689
5
            Box::new(async move { Ok(0i32) })
690
5
        })
691
        .unwrap();
692
9
    let alloc_export = alloc_export.to_string();
693
43
    let field_bytes: Vec<Vec<u8>> = fields.iter().map(|f| f.to_vec()).collect();
694
9
    linker
695
9
        .func_wrap_async("test", "ent", move |mut caller: Caller<'_, ()>, ()| {
696
9
            let alloc_export = alloc_export.clone();
697
9
            let field_bytes = field_bytes.clone();
698
9
            Box::new(async move {
699
9
                let mut args = Vec::with_capacity(field_bytes.len());
700
9
                for field in &field_bytes {
701
43
                    let r = alloc_string_ref(&mut caller, field)?;
702
43
                    args.push(Val::AnyRef(Some(r.to_anyref())));
703
                }
704
9
                alloc_entity_via_export(&mut caller, &alloc_export, &args)
705
9
                    .await
706
9
                    .map(Some)
707
9
            })
708
9
        })
709
        .unwrap();
710
9
    let mut store: Store<()> = Store::new(&engine, ());
711
9
    store.set_fuel(1_000_000_000).unwrap();
712
9
    store.set_epoch_deadline(1);
713
9
    let instance = linker.instantiate_async(&mut store, &module).await.unwrap();
714
9
    let func = instance.get_func(&mut store, "nomi-eval").unwrap();
715
9
    let mut results = [Val::AnyRef(None)];
716
9
    func.call_async(&mut store, &[], &mut results)
717
9
        .await
718
        .unwrap();
719
9
    let any = match &results[0] {
720
9
        Val::AnyRef(a) => *a,
721
        _ => panic!("nomi-eval returned non-anyref"),
722
    };
723
9
    let handles = resolve_type_handles(&mut store, &instance).unwrap();
724
9
    decode_eval_result(&mut store, any, result_ty, &handles)
725
9
}
726

            
727
/// ADR-0033 Phase 6: an entity riding a dynamically widened AnyRef result
728
/// (a Bool-vs-EntityRef `or` mismatch) decodes through the SAME
729
/// `decode_entity` plist a fixed-type EntityRef result uses — for a kind
730
/// whose wasm struct shape no OTHER entity kind shares (`SshKey` is six
731
/// strings; unique among `ENTITY_LAYOUTS`), so `matches_ty` classifies it
732
/// unambiguously.
733
#[tokio::test(flavor = "current_thread")]
734
1
async fn sshkey_widened_to_anyref_decodes_via_render_entity() {
735
1
    let decoded = run_entity_widened_to_anyref(
736
1
        nomiscript::EntityKind::SshKey,
737
1
        "alloc_ssh_key",
738
1
        &[
739
1
            b"key-1",
740
1
            b"AA:BB",
741
1
            b"laptop",
742
1
            b"ed25519",
743
1
            b"2024-01-01",
744
1
            b"2025-01-01",
745
1
        ],
746
1
        "(or (> (flag) 5) (ent))",
747
1
    )
748
1
    .await;
749
1
    assert_eq!(
750
1
        printed(&decoded),
751
1
        "(:sshkey :id \"key-1\" :fingerprint \"AA:BB\" :name \"laptop\" \
752
1
             :key-type \"ed25519\" :created-at \"2024-01-01\" :last-used-at \"2025-01-01\")"
753
1
    );
754
1
}
755

            
756
/// `decode_car`'s OWN `PairElement::Entity` arm — reached only when a list's
757
/// cars share ONE compile-time `EntityRef(kind)` type, so the whole list
758
/// stays fixed-typed (`PairRef(Entity(kind))`) rather than widening to
759
/// AnyRef. Distinct from `decode_dynamic_anyref`'s `AnyRefKind::Entity` arm
760
/// (covered above, reached via a widened single-entity car): both call the
761
/// SAME `decode_entity`, but `decode_car`'s dispatch line to it was
762
/// otherwise never exercised.
763
#[tokio::test(flavor = "current_thread")]
764
1
async fn homogeneous_entity_list_decodes_via_decode_car_entity_arm() {
765
    use nomiscript::{
766
        Compiler, EntityKind, HostFnSpec, PairElement, Reader, SymbolTable, WasmType,
767
    };
768

            
769
1
    let kind = EntityKind::SshKey;
770
1
    let specs = vec![
771
1
        HostFnSpec::new("ent1", "test", "ent1").returns(WasmType::EntityRef(kind)),
772
1
        HostFnSpec::new("ent2", "test", "ent2").returns(WasmType::EntityRef(kind)),
773
    ];
774
1
    let program = Reader::parse("(list (ent1) (ent2))").unwrap();
775
1
    let mut compiler = Compiler::with_host_fns(specs.clone());
776
1
    let mut symbols = SymbolTable::with_builtins();
777
1
    symbols.register_host_fns(&specs);
778
1
    let (bytes, result_ty) = compiler
779
1
        .compile_eval_with_type(&program, &mut symbols)
780
1
        .unwrap();
781
1
    assert_eq!(
782
1
        result_ty,
783
1
        Some(WasmType::PairRef(PairElement::Entity(kind))),
784
        "test setup regression: a homogeneous entity list must stay fixed-typed"
785
    );
786
1
    let engine = build_engine(EngineOpts::baseline().with_fuel()).unwrap();
787
1
    let module = compile_module(&engine, &bytes).unwrap();
788
1
    let mut linker: Linker<()> = Linker::new(&engine);
789
1
    link_nomi_raise_stub(&mut linker, &engine);
790
1
    let fields_one: Vec<Vec<u8>> = [
791
1
        b"key-1".to_vec(),
792
1
        b"AA:BB".to_vec(),
793
1
        b"laptop".to_vec(),
794
1
        b"ed25519".to_vec(),
795
1
        b"2024".to_vec(),
796
1
        b"2025".to_vec(),
797
1
    ]
798
1
    .to_vec();
799
1
    let fields_two: Vec<Vec<u8>> = [
800
1
        b"key-2".to_vec(),
801
1
        b"CC:DD".to_vec(),
802
1
        b"phone".to_vec(),
803
1
        b"rsa".to_vec(),
804
1
        b"2023".to_vec(),
805
1
        b"2024".to_vec(),
806
1
    ]
807
1
    .to_vec();
808
1
    linker
809
1
        .func_wrap_async("test", "ent1", move |mut caller: Caller<'_, ()>, ()| {
810
1
            let fields = fields_one.clone();
811
1
            Box::new(async move {
812
1
                let mut args = Vec::with_capacity(fields.len());
813
1
                for field in &fields {
814
6
                    let r = alloc_string_ref(&mut caller, field)?;
815
6
                    args.push(Val::AnyRef(Some(r.to_anyref())));
816
                }
817
1
                alloc_entity_via_export(&mut caller, "alloc_ssh_key", &args)
818
1
                    .await
819
1
                    .map(Some)
820
1
            })
821
1
        })
822
        .unwrap();
823
1
    linker
824
1
        .func_wrap_async("test", "ent2", move |mut caller: Caller<'_, ()>, ()| {
825
1
            let fields = fields_two.clone();
826
1
            Box::new(async move {
827
1
                let mut args = Vec::with_capacity(fields.len());
828
1
                for field in &fields {
829
6
                    let r = alloc_string_ref(&mut caller, field)?;
830
6
                    args.push(Val::AnyRef(Some(r.to_anyref())));
831
                }
832
1
                alloc_entity_via_export(&mut caller, "alloc_ssh_key", &args)
833
1
                    .await
834
1
                    .map(Some)
835
1
            })
836
1
        })
837
        .unwrap();
838
1
    let mut store: Store<()> = Store::new(&engine, ());
839
1
    store.set_fuel(1_000_000_000).unwrap();
840
1
    store.set_epoch_deadline(1);
841
1
    let instance = linker.instantiate_async(&mut store, &module).await.unwrap();
842
1
    let func = instance.get_func(&mut store, "nomi-eval").unwrap();
843
1
    let mut results = [Val::AnyRef(None)];
844
1
    func.call_async(&mut store, &[], &mut results)
845
1
        .await
846
        .unwrap();
847
1
    let any = match &results[0] {
848
1
        Val::AnyRef(a) => *a,
849
        _ => panic!("nomi-eval returned non-anyref"),
850
    };
851
1
    let handles = resolve_type_handles(&mut store, &instance).unwrap();
852
1
    let decoded = decode_eval_result(&mut store, any, result_ty, &handles).unwrap();
853
1
    assert_eq!(
854
1
        printed(&decoded),
855
1
        "((:sshkey :id \"key-1\" :fingerprint \"AA:BB\" :name \"laptop\" \
856
1
             :key-type \"ed25519\" :created-at \"2024\" :last-used-at \"2025\") \
857
1
             (:sshkey :id \"key-2\" :fingerprint \"CC:DD\" :name \"phone\" \
858
1
             :key-type \"rsa\" :created-at \"2023\" :last-used-at \"2024\"))"
859
1
    );
860
1
}
861

            
862
/// `Account` and `Transaction` are BOTH a four-`StringRef` struct. The
863
/// compiler registers the entity structs as one recursion group, so the
864
/// two are distinct types under iso-recursive identity and `matches_ty`
865
/// tells them apart (plan 0014 Stage 1, ISS-058): each decodes as its own
866
/// plist, never as the other's or as a placeholder.
867
#[tokio::test(flavor = "current_thread")]
868
1
async fn account_and_transaction_widened_to_anyref_decode_as_their_own_kind() {
869
1
    let account = run_entity_widened_to_anyref(
870
1
        nomiscript::EntityKind::Account,
871
1
        "alloc_account",
872
1
        &[b"a-1", b"Checking", b"", b"ASSET"],
873
1
        "(or (> (flag) 5) (ent))",
874
1
    )
875
1
    .await;
876
1
    let transaction = run_entity_widened_to_anyref(
877
1
        nomiscript::EntityKind::Transaction,
878
1
        "alloc_transaction",
879
1
        &[b"t-1", b"note", b"12.00", b"2024-01-01"],
880
1
        "(or (> (flag) 5) (ent))",
881
1
    )
882
1
    .await;
883
1
    assert_eq!(
884
1
        printed(&account),
885
1
        "(:account :id \"a-1\" :name \"Checking\" :parent \"\" :type \"ASSET\")"
886
    );
887
1
    assert_eq!(
888
1
        printed(&transaction),
889
1
        "(:transaction :id \"t-1\" :note \"note\" :amount \"12.00\" :post-date \"2024-01-01\")"
890
1
    );
891
1
}
892

            
893
/// The other same-shaped pair, the Commodity entity and Tag (three strings
894
/// each), likewise.
895
#[tokio::test(flavor = "current_thread")]
896
1
async fn commodity_entity_and_tag_widened_to_anyref_decode_as_their_own_kind() {
897
1
    let commodity = run_entity_widened_to_anyref(
898
1
        nomiscript::EntityKind::Commodity,
899
1
        "alloc_commodity_entity",
900
1
        &[b"c-1", b"USD", b"US Dollar"],
901
1
        "(or (> (flag) 5) (ent))",
902
1
    )
903
1
    .await;
904
1
    let tag = run_entity_widened_to_anyref(
905
1
        nomiscript::EntityKind::Tag,
906
1
        "alloc_tag_entity",
907
1
        &[b"g-1", b"category", b"groceries", b"food"],
908
1
        "(or (> (flag) 5) (ent))",
909
1
    )
910
1
    .await;
911
1
    assert_eq!(
912
1
        printed(&commodity),
913
1
        "(:commodity :id \"c-1\" :symbol \"USD\" :name \"US Dollar\")"
914
    );
915
1
    assert_eq!(
916
1
        printed(&tag),
917
1
        "(:tag :id \"g-1\" :name \"category\" :value \"groceries\" :description \"food\")"
918
1
    );
919
1
}
920

            
921
/// ADR-0033 Phase 6 review fix: `decode_dynamic_anyref` — `decode_car`'s
922
/// AnyRef-element counterpart, reached from INSIDE a `$pair` chain rather
923
/// than a bare top-level result — has its own `AnyRefKind::Entity` arm and
924
/// needs its own coverage, distinct from `decode_dynamic_anyref`'s (a
925
/// top-level result never walks a chain). Mixing an SshKey car with a
926
/// String car forces the chain's element to AnyRef.
927
#[tokio::test(flavor = "current_thread")]
928
1
async fn sshkey_widened_to_anyref_inside_a_list_decodes_via_decode_dynamic_anyref() {
929
1
    let decoded = run_entity_widened_to_anyref(
930
1
        nomiscript::EntityKind::SshKey,
931
1
        "alloc_ssh_key",
932
1
        &[b"key-1", b"AA:BB", b"laptop", b"ed25519", b"2024", b"2025"],
933
1
        r#"(list (ent) "x")"#,
934
1
    )
935
1
    .await;
936
1
    assert_eq!(
937
1
        printed(&decoded),
938
1
        "((:sshkey :id \"key-1\" :fingerprint \"AA:BB\" :name \"laptop\" \
939
1
             :key-type \"ed25519\" :created-at \"2024\" :last-used-at \"2025\") \"x\")"
940
1
    );
941
1
}
942

            
943
/// A closure riding a dynamically widened AnyRef result decodes as the site
944
/// of its source.
945
#[tokio::test(flavor = "current_thread")]
946
1
async fn closure_widened_to_anyref_decodes_as_its_site() {
947
    use nomiscript::{Compiler, HostFnSpec, Reader, SymbolTable, WasmType};
948

            
949
1
    let specs = vec![HostFnSpec::new("flag", "test", "flag").returns(WasmType::I32)];
950
1
    let program = Reader::parse("(let ((f (lambda (x) x))) (or (> (flag) 5) f))").unwrap();
951
1
    let mut compiler = Compiler::with_host_fns(specs.clone());
952
1
    let mut symbols = SymbolTable::with_builtins();
953
1
    symbols.register_host_fns(&specs);
954
1
    let (bytes, result_ty) = compiler
955
1
        .compile_eval_with_type(&program, &mut symbols)
956
1
        .unwrap();
957
1
    assert_eq!(
958
1
        result_ty,
959
1
        Some(WasmType::AnyRef),
960
        "test setup regression: the form must actually widen to AnyRef"
961
    );
962
1
    let engine = build_engine(EngineOpts::baseline().with_fuel()).unwrap();
963
1
    let module = compile_module(&engine, &bytes).unwrap();
964
1
    let mut linker: Linker<()> = Linker::new(&engine);
965
1
    link_nomi_raise_stub(&mut linker, &engine);
966
1
    linker
967
1
        .func_wrap_async("test", "flag", |_: Caller<'_, ()>, ()| {
968
1
            Box::new(async move { Ok(0i32) })
969
1
        })
970
        .unwrap();
971
1
    let mut store: Store<()> = Store::new(&engine, ());
972
1
    store.set_fuel(1_000_000_000).unwrap();
973
1
    store.set_epoch_deadline(1);
974
1
    let instance = linker.instantiate_async(&mut store, &module).await.unwrap();
975
1
    let func = instance.get_func(&mut store, "nomi-eval").unwrap();
976
1
    let mut results = [Val::AnyRef(None)];
977
1
    func.call_async(&mut store, &[], &mut results)
978
1
        .await
979
        .unwrap();
980
1
    let any = match &results[0] {
981
1
        Val::AnyRef(a) => *a,
982
        _ => panic!("nomi-eval returned non-anyref"),
983
    };
984
1
    let handles = resolve_type_handles(&mut store, &instance).unwrap();
985
1
    let decoded = decode_eval_result(&mut store, any, result_ty, &handles).unwrap();
986
1
    assert_eq!(decoded, EvalValue::Closure { site: Some(0) });
987
1
}
988

            
989
/// `decode_dynamic_anyref` — reached from INSIDE a `$pair` chain, not from a
990
/// bare top-level result — classifies a same-shaped entity kind too (plan
991
/// 0014 Stage 1, ISS-058): an Account car beside a string renders as its
992
/// own plist.
993
#[tokio::test(flavor = "current_thread")]
994
1
async fn same_shaped_entity_widened_to_anyref_inside_a_list_decodes_by_kind() {
995
1
    let decoded = run_entity_widened_to_anyref(
996
1
        nomiscript::EntityKind::Account,
997
1
        "alloc_account",
998
1
        &[b"a-1", b"Checking", b"", b"ASSET"],
999
1
        r#"(list (ent) "x")"#,
1
    )
1
    .await;
1
    assert_eq!(
1
        printed(&decoded),
1
        "((:account :id \"a-1\" :name \"Checking\" :parent \"\" :type \"ASSET\") \"x\")"
1
    );
1
}
/// The eval-mode `CompileContext` declares `nomi.__nomi_raise` for
/// `(error 'code "msg")` lowering even when no `(error)` form is
/// present in the program. The host side lives in the rpc crate;
/// for the scripting-crate runtime tests we link a never-called
/// stub so `instantiate()` resolves the import.
93
fn link_nomi_raise_stub(linker: &mut Linker<()>, engine: &wasmtime::Engine) {
93
    linker
        .func_new(
93
            "nomi",
93
            "__nomi_raise",
93
            wasmtime::FuncType::new(
93
                engine,
93
                [
93
                    wasmtime::ValType::Ref(wasmtime::RefType::ARRAYREF),
93
                    wasmtime::ValType::Ref(wasmtime::RefType::ARRAYREF),
93
                    wasmtime::ValType::Ref(wasmtime::RefType::ANYREF),
93
                ],
93
                [],
93
            ),
2
            |_, _, _| {
2
                Err(wasmtime::Error::msg(
2
                    "__nomi_raise stub: not linked in this test",
2
                ))
2
            },
        )
        .unwrap();
93
    link_log_stub(linker, engine);
93
    link_nomi_catch_each_stub(linker, engine);
93
}
/// `env.log` `(i32 level, i32 ptr, i32 len) -> ()` stub. Eval-mode modules
/// import `env.log` (PRINT / DISPLAY / NEWLINE / DEBUG lower to it); a test
/// linker that instantiates an eval module must define it or instantiation
/// fails with "unknown import". Production wires it via `scripting::host`
/// (script mode) / `rpc::natives::env_io` (eval mode); this no-op stub
/// suffices for tests that don't assert on logged output.
93
fn link_log_stub(linker: &mut Linker<()>, engine: &wasmtime::Engine) {
93
    linker
        .func_new(
93
            "env",
93
            "log",
93
            wasmtime::FuncType::new(
93
                engine,
93
                [
93
                    wasmtime::ValType::I32,
93
                    wasmtime::ValType::I32,
93
                    wasmtime::ValType::I32,
93
                ],
93
                [],
93
            ),
1
            |_, _, _| Ok(()),
        )
        .unwrap();
93
    linker
        .func_new(
93
            "env",
93
            "log_value",
93
            wasmtime::FuncType::new(
93
                engine,
93
                [wasmtime::ValType::Ref(wasmtime::RefType::ANYREF)],
93
                [wasmtime::ValType::I32],
93
            ),
            |_, _, results| {
                results[0] = Val::I32(0);
                Ok(())
            },
        )
        .unwrap();
93
}
/// Companion to `link_nomi_raise_stub`. The eval compile context now
/// declares `__nomi_catch_each` up-front (so its import index is
/// stable before any user host fn is wired — matches `__nomi_raise`'s
/// shape), so even programs that don't use `(catch-each ...)` still
/// need the import resolvable at instantiation time. The stub traps
/// on call so a regression that accidentally invokes catch-each in
/// these unit tests surfaces loudly rather than silently no-oping.
93
fn link_nomi_catch_each_stub(linker: &mut Linker<()>, engine: &wasmtime::Engine) {
    let abstract_struct =
93
        wasmtime::ValType::Ref(wasmtime::RefType::new(true, wasmtime::HeapType::Struct));
93
    let funcref = wasmtime::ValType::Ref(wasmtime::RefType::FUNCREF);
93
    let anyref = wasmtime::ValType::Ref(wasmtime::RefType::ANYREF);
93
    linker
        .func_new(
93
            "nomi",
93
            "__nomi_catch_each",
93
            wasmtime::FuncType::new(
93
                engine,
93
                [funcref, anyref, abstract_struct.clone()],
93
                [abstract_struct],
93
            ),
            |_, _, _| {
                Err(wasmtime::Error::msg(
                    "__nomi_catch_each stub: not linked in this test",
                ))
            },
        )
        .unwrap();
93
}
/// End-to-end: nomiscript Compiler emits eval-mode bytecode that
/// returns the form's final value via nomi-eval's `(ref null any)`
/// return slot, the runtime instantiates it (no capture host fns
/// linked — they retired in A6.c), and `decode_eval_result` walks
/// the anyref into the structured `EvalValue` the rest of the host
/// renders from.
41
fn run_nomiscript_eval(program: &nomiscript::Program) -> Option<EvalValue> {
    use nomiscript::{Compiler, SymbolTable};
41
    let engine = build_engine(EngineOpts::baseline().with_fuel()).unwrap();
41
    let mut compiler = Compiler::new();
41
    let mut symbols = SymbolTable::with_builtins();
41
    let (bytes, result_ty) = compiler
41
        .compile_eval_with_type(program, &mut symbols)
41
        .expect("eval compile");
41
    let module = compile_module(&engine, &bytes).expect("module");
41
    let mut linker: Linker<()> = Linker::new(&engine);
41
    link_nomi_raise_stub(&mut linker, &engine);
41
    let mut store: Store<()> = Store::new(&engine, ());
41
    store.set_fuel(10_000_000).unwrap();
41
    store.set_epoch_deadline(1);
41
    let instance = linker.instantiate(&mut store, &module).unwrap();
41
    let func = instance.get_func(&mut store, "nomi-eval").unwrap();
41
    let mut results = [Val::AnyRef(None)];
41
    func.call(&mut store, &[], &mut results).unwrap();
41
    let any = match &results[0] {
41
        Val::AnyRef(a) => *a,
        _ => panic!("nomi-eval returned non-anyref"),
    };
41
    let handles = resolve_type_handles(&mut store, &instance).expect("type handles");
41
    Some(decode_eval_result(&mut store, any, result_ty, &handles).expect("decode"))
41
}
/// ADR-0033 Phase 3 probe, pinned as a regression: a module carrying the new
/// `$t` global section instantiates (wasmtime accepts the Tags-then-Globals-
/// then-Exports section order), the exported `t` global round-trips through
/// `Global::get`, and it is recognised by `Rooted::ref_eq` identity — never a
/// type test — against the same value decoded from an eval result.
#[test]
1
fn the_t_global_section_instantiates_and_is_recognised_by_identity() {
    use nomiscript::{Compiler, Expr, SymbolTable};
1
    let engine = build_engine(EngineOpts::baseline().with_fuel()).unwrap();
1
    let mut compiler = Compiler::new();
1
    let mut symbols = SymbolTable::with_builtins();
1
    let program = nomiscript::Program::new(vec![Expr::T]);
1
    let (bytes, result_ty) = compiler
1
        .compile_eval_with_type(&program, &mut symbols)
1
        .expect("eval compile");
1
    let module = compile_module(&engine, &bytes).expect("module accepted by wasmtime");
1
    let mut linker: Linker<()> = Linker::new(&engine);
1
    link_nomi_raise_stub(&mut linker, &engine);
1
    let mut store: Store<()> = Store::new(&engine, ());
1
    store.set_fuel(10_000_000).unwrap();
1
    store.set_epoch_deadline(1);
1
    let instance = linker
1
        .instantiate(&mut store, &module)
1
        .expect("module instantiates with the global section in place");
    let handles =
1
        resolve_type_handles(&mut store, &instance).expect("module exports the `t` global");
1
    let t = handles.t;
    // The same singleton fetched a second time is the SAME rooted value by
    // identity (it's read from one immutable module global).
1
    let t_again = t_singleton(&mut store, &instance).expect("t global");
1
    assert!(wasmtime::Rooted::<wasmtime::AnyRef>::ref_eq(&store, &t, &t_again).unwrap());
1
    let func = instance.get_func(&mut store, "nomi-eval").unwrap();
1
    let mut results = [Val::AnyRef(None)];
1
    func.call(&mut store, &[], &mut results).unwrap();
1
    let any = match &results[0] {
1
        Val::AnyRef(a) => a.expect("a `t` literal result is a non-null anyref"),
        _ => panic!("nomi-eval returned non-anyref"),
    };
1
    assert!(
1
        wasmtime::Rooted::<wasmtime::AnyRef>::ref_eq(&store, &any, &t).unwrap(),
        "a compiled `t` literal must decode to the SAME object as the exported \
         `t` global, by reference identity"
    );
1
    assert_eq!(
1
        decode_eval_result(&mut store, Some(any), result_ty, &handles).unwrap(),
1
        EvalValue::T
    );
1
}
#[test]
1
fn nomiscript_eval_captures_integer_literal() {
    use nomiscript::{Expr, Program};
    // ADR-0028: an integer literal is an Index (I32), decoding as `I32`,
    // not the dimensionless `Ratio` it conflated with before the flip.
1
    let program = Program::new(vec![Expr::Number(Number::Index(7))]);
1
    assert_eq!(run_nomiscript_eval(&program), Some(EvalValue::I32(7)));
1
}
#[test]
1
fn nomiscript_eval_captures_arithmetic_result() {
    use nomiscript::{Expr, Program};
    // All-integer (Index) arithmetic stays in the Index stratum: `(+ 1 2)`
    // decodes as `I32(3)`.
1
    let program = Program::new(vec![Expr::List(vec![
1
        Expr::Symbol("+".into()),
1
        Expr::Number(Number::Index(1)),
1
        Expr::Number(Number::Index(2)),
1
    ])]);
1
    assert_eq!(run_nomiscript_eval(&program), Some(EvalValue::I32(3)));
1
}
#[test]
1
fn nomiscript_eval_captures_fractional_result() {
    use nomiscript::{Expr, Fraction, Program};
    // A Scalar operand keeps rational division: `(/ 1/2 2/1) → 1/4`, decoding
    // as `Ratio`. (All-integer `(/ 1 4)` would be Index `0`.)
1
    let program = Program::new(vec![Expr::List(vec![
1
        Expr::Symbol("/".into()),
1
        Expr::Number(Number::Scalar(Fraction::new(1, 2))),
1
        Expr::Number(Number::Scalar(Fraction::new(2, 1))),
1
    ])]);
1
    assert_eq!(
1
        run_nomiscript_eval(&program),
1
        Some(EvalValue::Ratio { numer: 1, denom: 4 })
    );
1
}
#[test]
1
fn nomiscript_eval_captures_nil_for_empty_program() {
1
    let program = nomiscript::Program::default();
1
    assert_eq!(run_nomiscript_eval(&program), Some(EvalValue::Nil));
1
}
#[test]
1
fn nomiscript_eval_decodes_bool_as_bool() {
    use nomiscript::{Expr, Program};
1
    let program = Program::new(vec![Expr::T]);
    // `t` carries `WasmType::Bool` (i31-boxed); the decoder surfaces a
    // truthy bool as `Bool(true)` (a falsy one would be `Nil`), not the
    // raw integer the old i32-conflated path produced.
1
    assert_eq!(run_nomiscript_eval(&program), Some(EvalValue::T));
1
}
/// Drift-detector: compile-eval each script source, run it, and
/// verify the static `result_ty` hint reported by
/// `compile_eval_with_type` matches the decoded `EvalValue`'s
/// variant. Catches eval-vs-codegen drift across the compiler —
/// the exact bug class that produced the tag-sync test regressions.
/// Add a row whenever a new WasmType or Expr-shape is supported.
#[test]
1
fn nomiscript_eval_type_hint_matches_value_variant() {
    use nomiscript::{Compiler, Program, Reader, SymbolTable, WasmType};
1
    let cases: &[(&str, Option<WasmType>)] = &[
1
        // ADR-0028: integer literals + all-integer arithmetic are Index
1
        // (I32); a fractional literal is Scalar (Ratio).
1
        ("42", Some(WasmType::I32)),
1
        ("(+ 1 2)", Some(WasmType::I32)),
1
        ("(/ 1 4)", Some(WasmType::I32)),
1
        ("(/ 1/2 2/1)", Some(WasmType::Ratio)),
1
        ("(= 1 1)", Some(WasmType::Bool)),
1
        ("(< 1 2)", Some(WasmType::Bool)),
1
        ("t", Some(WasmType::Bool)),
1
        ("\"hello\"", Some(WasmType::StringRef)),
1
        ("(let ((x 1)) (+ x 1))", Some(WasmType::I32)),
1
        ("(let ((x 1)) \"tail\")", Some(WasmType::StringRef)),
1
        ("(if (= 1 1) 2 3)", Some(WasmType::I32)),
1
    ];
1
    for (src, expected_ty) in cases {
11
        let program: Program = Reader::parse(src).expect("parse");
11
        let engine = build_engine(EngineOpts::baseline().with_fuel()).unwrap();
11
        let mut compiler = Compiler::new();
11
        let mut symbols = SymbolTable::with_builtins();
11
        let (bytes, result_ty) = compiler
11
            .compile_eval_with_type(&program, &mut symbols)
            .unwrap_or_else(|e| panic!("compile {src:?}: {e}"));
11
        assert_eq!(
11
            &result_ty, expected_ty,
            "compile_eval_with_type reported wrong static type for {src:?}",
        );
11
        let module = compile_module(&engine, &bytes).expect("module");
11
        let mut linker: Linker<()> = Linker::new(&engine);
11
        link_nomi_raise_stub(&mut linker, &engine);
11
        let mut store: Store<()> = Store::new(&engine, ());
11
        store.set_fuel(10_000_000).unwrap();
11
        store.set_epoch_deadline(1);
11
        let instance = linker.instantiate(&mut store, &module).unwrap();
11
        let func = instance.get_func(&mut store, "nomi-eval").unwrap();
11
        let mut results = [Val::AnyRef(None)];
11
        func.call(&mut store, &[], &mut results)
            .unwrap_or_else(|e| panic!("run {src:?}: {e}"));
11
        let any = match &results[0] {
11
            Val::AnyRef(a) => *a,
            _ => panic!("nomi-eval returned non-anyref for {src:?}"),
        };
11
        let handles = resolve_type_handles(&mut store, &instance).expect("type handles");
11
        let decoded = decode_eval_result(&mut store, any, result_ty, &handles)
            .unwrap_or_else(|e| panic!("decode {src:?}: {e}"));
        // The mapping below is the canonical EvalValue ↔ WasmType
        // contract. Any drift fails here.
11
        let ok = matches!(
11
            (&result_ty, &decoded),
            (None, EvalValue::Nil)
                    | (Some(WasmType::I32), EvalValue::I32(_))
                    // A Bool decodes to Bool(true) when truthy or Nil when falsy.
                    | (Some(WasmType::Bool), EvalValue::T | EvalValue::Nil)
                    | (Some(WasmType::Ratio), EvalValue::Ratio { .. })
                    | (Some(WasmType::Commodity), EvalValue::Commodity { .. })
                    | (
                        Some(WasmType::StringRef),
                        EvalValue::String(_) | EvalValue::Bytes(_)
                    ),
        );
11
        assert!(
11
            ok,
            "type/value drift for {src:?}: hint={result_ty:?}, decoded={decoded:?}",
        );
    }
1
}
#[tokio::test(flavor = "current_thread")]
1
async fn decode_entity_emits_named_field_list() {
    // Build a $commodity-shaped struct (3 string fields, matching the
    // Commodity layout's id/symbol/name slots) via WAT, then decode it with
    // `decode_entity` — the same call the host eval path makes for a returned
    // entity. Proves the spec-driven decoder reads each slot by name.
1
    let wat = r#"
1
        (module
1
          (type $i8 (array (mut i8)))
1
          (type $commodity (struct
1
            (field (ref null $i8))
1
            (field (ref null $i8))
1
            (field (ref null $i8))))
1
          (data $id "uuid-123")
1
          (data $sym "USD")
1
          (data $name "US Dollar")
1
          (func (export "go") (result (ref null struct))
1
            (struct.new $commodity
1
              (array.new_data $i8 $id  (i32.const 0) (i32.const 8))
1
              (array.new_data $i8 $sym (i32.const 0) (i32.const 3))
1
              (array.new_data $i8 $name (i32.const 0) (i32.const 9)))))
1
        "#;
1
    let engine = build_engine(EngineOpts::baseline()).unwrap();
1
    let module = compile_wat(&engine, wat).unwrap();
1
    let linker: Linker<()> = Linker::new(&engine);
1
    let mut store: Store<()> = Store::new(&engine, ());
1
    store.set_epoch_deadline(1_000);
1
    let instance = linker.instantiate_async(&mut store, &module).await.unwrap();
1
    let go = instance.get_func(&mut store, "go").unwrap();
1
    let mut results = [Val::AnyRef(None)];
1
    go.call_async(&mut store, &[], &mut results).await.unwrap();
1
    let any = match results[0] {
1
        Val::AnyRef(Some(a)) => a,
        other => panic!("go did not return a struct: {other:?}"),
    };
1
    let decoded = super::structure::decode_entity(
1
        store.as_context_mut(),
1
        &any,
1
        nomiscript::EntityKind::Commodity,
1
        0,
1
    )
1
    .unwrap();
1
    assert_eq!(
1
        printed(&decoded),
1
        "(:commodity :id \"uuid-123\" :symbol \"USD\" :name \"US Dollar\")"
1
    );
1
}
#[tokio::test(flavor = "current_thread")]
1
async fn read_entity_string_field_reads_named_slot() {
    // Same Commodity-shaped struct; prove the field reader resolves a named
    // slot from the layout (id = slot 0, name = slot 2) — the call
    // `draft-split` makes to turn an entity ref into a stable uuid string.
1
    let wat = r#"
1
        (module
1
          (type $i8 (array (mut i8)))
1
          (type $commodity (struct
1
            (field (ref null $i8))
1
            (field (ref null $i8))
1
            (field (ref null $i8))))
1
          (data $id "uuid-123")
1
          (data $sym "USD")
1
          (data $name "US Dollar")
1
          (func (export "go") (result (ref null struct))
1
            (struct.new $commodity
1
              (array.new_data $i8 $id  (i32.const 0) (i32.const 8))
1
              (array.new_data $i8 $sym (i32.const 0) (i32.const 3))
1
              (array.new_data $i8 $name (i32.const 0) (i32.const 9)))))
1
        "#;
1
    let engine = build_engine(EngineOpts::baseline()).unwrap();
1
    let module = compile_wat(&engine, wat).unwrap();
1
    let linker: Linker<()> = Linker::new(&engine);
1
    let mut store: Store<()> = Store::new(&engine, ());
1
    store.set_epoch_deadline(1_000);
1
    let instance = linker.instantiate_async(&mut store, &module).await.unwrap();
1
    let go = instance.get_func(&mut store, "go").unwrap();
1
    let mut results = [Val::AnyRef(None)];
1
    go.call_async(&mut store, &[], &mut results).await.unwrap();
1
    let entity = match results[0] {
1
        Val::AnyRef(Some(a)) => a.unwrap_struct(&mut store).unwrap(),
        other => panic!("go did not return a struct: {other:?}"),
    };
    let id =
1
        read_entity_string_field_ctx(&mut store, entity, nomiscript::EntityKind::Commodity, "id")
1
            .unwrap();
1
    assert_eq!(id, "uuid-123");
1
    let name = read_entity_string_field_ctx(
1
        &mut store,
1
        entity,
1
        nomiscript::EntityKind::Commodity,
1
        "name",
1
    )
1
    .unwrap();
1
    assert_eq!(name, "US Dollar");
    // A field that isn't a String slot in the layout is rejected.
1
    let bad = read_entity_string_field_ctx(
1
        &mut store,
1
        entity,
1
        nomiscript::EntityKind::Commodity,
1
        "nonexistent",
1
    );
1
    assert!(bad.is_err());
1
}