1
// Skipped under Miri: these tests compile+run wasm via wasmtime, whose
2
// Cranelift backend refuses to run under Miri.
3
#![cfg(not(miri))]
4

            
5
use nms::interpreter::Interpreter;
6
use scripting::nomiscript::{Number, Value};
7
use scripting::parser::EntityData;
8
use scripting::runtime::{EngineOpts, build_engine};
9
use scripting::{EntityHeaderArgs, MemorySerializer, ScriptExecutor, SplitArgs, TransactionArgs};
10
use scripting_format::{ContextType, EntityType, Operation};
11
use wasmtime::{Engine, Module};
12

            
13
4
fn index(n: i64) -> Value {
14
4
    Value::Number(Number::Index(n))
15
4
}
16

            
17
/// A true comparison / predicate result. Runtime booleans (`=`, `null?`, …)
18
/// carry `WasmType::Bool` and serialize as `T`, not `Number(1)`.
19
14
fn truthy() -> Value {
20
14
    Value::T
21
14
}
22

            
23
16
fn gc_engine() -> Engine {
24
16
    build_engine(EngineOpts::baseline()).unwrap()
25
16
}
26

            
27
2
fn wasm_export_names(wasm: &[u8], engine: &Engine) -> Vec<String> {
28
2
    let module = Module::new(engine, wasm).unwrap();
29
28
    module.exports().map(|e| e.name().to_string()).collect()
30
2
}
31

            
32
4
fn build_minimal_input(output_size: u32) -> Vec<u8> {
33
4
    let mut ser = MemorySerializer::new();
34
4
    ser.set_context(ContextType::BatchProcess, EntityType::Transaction);
35
4
    ser.finalize(output_size)
36
4
}
37

            
38
#[test]
39
1
fn test_compiled_wasm_has_standard_exports() {
40
1
    let wasm = rpc::compile_script("42").unwrap();
41
1
    let engine = gc_engine();
42
1
    let exports = wasm_export_names(&wasm, &engine);
43
1
    assert!(exports.contains(&"should_apply".to_string()));
44
1
    assert!(exports.contains(&"process".to_string()));
45
1
    assert!(exports.contains(&"memory".to_string()));
46
1
}
47

            
48
#[test]
49
1
fn test_groceries_wasm_has_standard_exports() {
50
1
    let wasm = include_bytes!("../../../web/static/wasm/groceries_markup.wasm");
51
1
    let exports = wasm_export_names(wasm, &Engine::default());
52
1
    assert!(exports.contains(&"should_apply".to_string()));
53
1
    assert!(exports.contains(&"process".to_string()));
54
1
    assert!(exports.contains(&"memory".to_string()));
55
1
}
56

            
57
#[test]
58
1
fn test_compile_and_load_roundtrip() {
59
1
    let interp = Interpreter::new(false).unwrap();
60
1
    let wasm = rpc::compile_script("(+ 1 2 3)").unwrap();
61
1
    let result = interp.run_wasm(&wasm).unwrap();
62
1
    assert_eq!(result, Some(Value::Number(Number::Index(6))));
63
1
}
64

            
65
#[test]
66
1
fn test_compile_and_load_roundtrip_string() {
67
1
    let interp = Interpreter::new(false).unwrap();
68
1
    let wasm = rpc::compile_script(r#""hello""#).unwrap();
69
1
    let result = interp.run_wasm(&wasm).unwrap();
70
1
    assert_eq!(result, Some(Value::String("hello".to_string())));
71
1
}
72

            
73
#[test]
74
1
fn test_top_level_error_throws_through_boundary_in_script_mode() {
75
    // End-to-end script-mode path NEW in Tier 3.2: a top-level `(error)`
76
    // lowers to `throw $nomi_error`; the boundary `try_table` the compiler
77
    // wraps `process` in catches the uncaught throw and bridges it to the
78
    // `__nomi_raise` host fn (registered in `define_host_functions`). Before
79
    // 3.2 `(error)` never worked on the ScriptExecutor/nms linker world — it
80
    // would fail to link. So compile-then-run reaching an *execution* Err
81
    // (not a compile Err, not a swallowed value) is what proves the throw →
82
    // boundary → host-bridge path is wired end-to-end. The code/message
83
    // *content* of the marker is classified one layer up (rpc / the
84
    // `err_code_and_message` unit tests); nms reports the classified code
85
    // and message (plan 0014 Stage 0, ISS-027).
86
1
    let interp = Interpreter::new(false).unwrap();
87
1
    let wasm = rpc::compile_script(r#"(error 'boom "the message")"#)
88
1
        .expect("(error) must compile + link in script mode post-3.2");
89
1
    let err = interp
90
1
        .run_wasm(&wasm)
91
1
        .expect_err("an uncaught top-level (error) must surface as an Err, not a returned value");
92
1
    assert_eq!(err.to_string(), "BOOM: the message");
93
1
}
94

            
95
#[test]
96
1
fn test_compile_and_load_roundtrip_defun() {
97
1
    let interp = Interpreter::new(false).unwrap();
98
1
    let wasm = rpc::compile_script("(defun add (a b) (+ a b)) (add 10 20)").unwrap();
99
1
    let result = interp.run_wasm(&wasm).unwrap();
100
1
    assert_eq!(result, Some(Value::Number(Number::Index(30))));
101
1
}
102

            
103
#[test]
104
1
fn test_nms_wasm_through_executor() {
105
1
    let wasm = rpc::compile_script("(+ 10 20)").unwrap();
106

            
107
1
    let input = build_minimal_input(4096);
108
1
    let executor = ScriptExecutor::with_engine(gc_engine());
109
1
    let entities = executor.execute(&wasm, &input, Some(4096)).unwrap();
110
1
    assert_eq!(
111
1
        entities.len(),
112
1
        1,
113
        "NMS WASM should produce one DebugValue entity"
114
    );
115
1
    assert_eq!(entities[0].entity_type, EntityType::DebugValue);
116
1
}
117

            
118
#[test]
119
1
fn test_groceries_wasm_through_executor_empty_input() {
120
1
    let wasm = include_bytes!("../../../web/static/wasm/groceries_markup.wasm");
121
1
    let input = build_minimal_input(4096);
122
1
    let executor = ScriptExecutor::try_new().expect("baseline engine");
123
1
    let entities = executor
124
1
        .execute(wasm.as_slice(), &input, Some(4096))
125
1
        .unwrap();
126
1
    assert!(
127
1
        entities.is_empty(),
128
        "groceries WASM with empty input should produce no entities"
129
    );
130
1
}
131

            
132
#[test]
133
1
fn test_groceries_wasm_tags_splits() {
134
1
    let wasm = include_bytes!("../../../web/static/wasm/groceries_markup.wasm");
135

            
136
1
    let mut ser = MemorySerializer::new();
137
1
    ser.set_context(ContextType::EntityCreate, EntityType::Transaction);
138

            
139
1
    let tx_id = [1u8; 16];
140
1
    let account1 = [2u8; 16];
141
1
    let account2 = [3u8; 16];
142
1
    let commodity = [4u8; 16];
143
1
    let split1_id = [5u8; 16];
144
1
    let split2_id = [6u8; 16];
145
1
    let tag_id = [7u8; 16];
146

            
147
1
    let tx_idx = ser.add_transaction(
148
1
        EntityHeaderArgs {
149
1
            id: tx_id,
150
1
            parent_idx: -1,
151
1
            is_primary: true,
152
1
            is_context: false,
153
1
        },
154
1
        TransactionArgs {
155
1
            post_date: 0,
156
1
            enter_date: 0,
157
1
            split_count: 2,
158
1
            tag_count: 1,
159
1
            is_multi_currency: false,
160
1
        },
161
1
    );
162
1
    ser.set_primary(tx_idx);
163
1
    let split1_idx = ser.add_split(
164
1
        EntityHeaderArgs {
165
1
            id: split1_id,
166
1
            parent_idx: tx_idx as i32,
167
1
            is_primary: false,
168
1
            is_context: false,
169
1
        },
170
1
        SplitArgs {
171
1
            account_id: account1,
172
1
            commodity_id: commodity,
173
1
            value_num: -5000,
174
1
            value_denom: 100,
175
1
            reconcile_state: 0,
176
1
            reconcile_date: 0,
177
1
            account_name: "Assets:Test",
178
1
        },
179
1
    );
180
1
    let split2_idx = ser.add_split(
181
1
        EntityHeaderArgs {
182
1
            id: split2_id,
183
1
            parent_idx: tx_idx as i32,
184
1
            is_primary: false,
185
1
            is_context: false,
186
1
        },
187
1
        SplitArgs {
188
1
            account_id: account2,
189
1
            commodity_id: commodity,
190
1
            value_num: 5000,
191
1
            value_denom: 100,
192
1
            reconcile_state: 0,
193
1
            reconcile_date: 0,
194
1
            account_name: "Assets:Test",
195
1
        },
196
1
    );
197
1
    ser.add_tag(tag_id, tx_idx as i32, false, false, "note", "groceries");
198

            
199
1
    let input = ser.finalize(4096);
200
1
    let executor = ScriptExecutor::try_new().expect("baseline engine");
201
1
    let entities = executor
202
1
        .execute(wasm.as_slice(), &input, Some(4096))
203
1
        .unwrap();
204

            
205
1
    assert_eq!(
206
1
        entities.len(),
207
1
        2,
208
        "expected 2 category tags (one per split)"
209
    );
210
1
    for entity in &entities {
211
2
        assert_eq!(entity.entity_type, EntityType::Tag);
212
2
        if let EntityData::Tag { name, value } = &entity.data {
213
2
            assert_eq!(name, "category");
214
2
            assert_eq!(value, "groceries");
215
        } else {
216
            panic!("expected Tag data, got {:?}", entity.data);
217
        }
218
    }
219

            
220
2
    let parents: Vec<i32> = entities.iter().map(|e| e.parent_idx).collect();
221
1
    assert!(parents.contains(&(split1_idx as i32)));
222
1
    assert!(parents.contains(&(split2_idx as i32)));
223
1
}
224

            
225
#[test]
226
1
fn test_entity_count_through_executor() {
227
1
    let _interp = Interpreter::new(false).unwrap();
228
1
    let wasm = rpc::compile_script("(entity-count)").unwrap();
229

            
230
1
    let mut ser = MemorySerializer::new();
231
1
    ser.set_context(ContextType::EntityCreate, EntityType::Transaction);
232
1
    let tx_id = [1u8; 16];
233
1
    let tx_idx = ser.add_transaction(
234
1
        EntityHeaderArgs {
235
1
            id: tx_id,
236
1
            parent_idx: -1,
237
1
            is_primary: true,
238
1
            is_context: false,
239
1
        },
240
1
        TransactionArgs {
241
1
            post_date: 0,
242
1
            enter_date: 0,
243
1
            split_count: 0,
244
1
            tag_count: 0,
245
1
            is_multi_currency: false,
246
1
        },
247
1
    );
248
1
    ser.set_primary(tx_idx);
249
1
    ser.add_split(
250
1
        EntityHeaderArgs {
251
1
            id: [2u8; 16],
252
1
            parent_idx: tx_idx as i32,
253
1
            is_primary: false,
254
1
            is_context: false,
255
1
        },
256
1
        SplitArgs {
257
1
            account_id: [3u8; 16],
258
1
            commodity_id: [4u8; 16],
259
1
            value_num: 100,
260
1
            value_denom: 1,
261
1
            reconcile_state: 0,
262
1
            reconcile_date: 0,
263
1
            account_name: "Assets:Test",
264
1
        },
265
1
    );
266

            
267
1
    let input = ser.finalize(4096);
268
1
    let executor = ScriptExecutor::with_engine(gc_engine());
269
1
    let entities = executor.execute(&wasm, &input, Some(4096)).unwrap();
270

            
271
1
    assert_eq!(entities.len(), 1, "should produce one DebugValue entity");
272
1
    assert_eq!(entities[0].entity_type, EntityType::DebugValue);
273
1
}
274

            
275
#[test]
276
1
fn test_entity_count_conditional_through_executor() {
277
1
    let _interp = Interpreter::new(false).unwrap();
278
1
    let script = r#"
279
1
        (if (= (entity-count) 4)
280
1
            "four-entities"
281
1
            "not-four")
282
1
    "#;
283
1
    let wasm = rpc::compile_script(script).unwrap();
284

            
285
1
    let mut ser = MemorySerializer::new();
286
1
    ser.set_context(ContextType::EntityCreate, EntityType::Transaction);
287
1
    let tx_id = [1u8; 16];
288
1
    let tx_idx = ser.add_transaction(
289
1
        EntityHeaderArgs {
290
1
            id: tx_id,
291
1
            parent_idx: -1,
292
1
            is_primary: true,
293
1
            is_context: false,
294
1
        },
295
1
        TransactionArgs {
296
1
            post_date: 0,
297
1
            enter_date: 0,
298
1
            split_count: 2,
299
1
            tag_count: 1,
300
1
            is_multi_currency: false,
301
1
        },
302
1
    );
303
1
    ser.set_primary(tx_idx);
304
1
    ser.add_split(
305
1
        EntityHeaderArgs {
306
1
            id: [5u8; 16],
307
1
            parent_idx: tx_idx as i32,
308
1
            is_primary: false,
309
1
            is_context: false,
310
1
        },
311
1
        SplitArgs {
312
1
            account_id: [2u8; 16],
313
1
            commodity_id: [4u8; 16],
314
1
            value_num: -5000,
315
1
            value_denom: 100,
316
1
            reconcile_state: 0,
317
1
            reconcile_date: 0,
318
1
            account_name: "Assets:Test",
319
1
        },
320
1
    );
321
1
    ser.add_split(
322
1
        EntityHeaderArgs {
323
1
            id: [6u8; 16],
324
1
            parent_idx: tx_idx as i32,
325
1
            is_primary: false,
326
1
            is_context: false,
327
1
        },
328
1
        SplitArgs {
329
1
            account_id: [3u8; 16],
330
1
            commodity_id: [4u8; 16],
331
1
            value_num: 5000,
332
1
            value_denom: 100,
333
1
            reconcile_state: 0,
334
1
            reconcile_date: 0,
335
1
            account_name: "Assets:Test",
336
1
        },
337
1
    );
338
1
    ser.add_tag([7u8; 16], tx_idx as i32, false, false, "note", "test");
339

            
340
1
    let input = ser.finalize(4096);
341
1
    let executor = ScriptExecutor::with_engine(gc_engine());
342
1
    let entities = executor.execute(&wasm, &input, Some(4096)).unwrap();
343

            
344
1
    assert_eq!(entities.len(), 1);
345
1
    assert_eq!(entities[0].entity_type, EntityType::DebugValue);
346
1
}
347

            
348
#[test]
349
1
fn test_runtime_do_loop_through_executor() {
350
1
    let _interp = Interpreter::new(false).unwrap();
351
1
    let script = r"
352
1
        (let* ((n (entity-count))
353
1
               (sum 0))
354
1
            (do ((i 0 (+ i 1)))
355
1
                ((>= i n) sum)
356
1
                (setf sum (+ sum 1))))
357
1
    ";
358
1
    let wasm = rpc::compile_script(script).unwrap();
359

            
360
1
    let mut ser = MemorySerializer::new();
361
1
    ser.set_context(ContextType::BatchProcess, EntityType::Transaction);
362
1
    let tx_id = [1u8; 16];
363
1
    let tx_idx = ser.add_transaction(
364
1
        EntityHeaderArgs {
365
1
            id: tx_id,
366
1
            parent_idx: -1,
367
1
            is_primary: true,
368
1
            is_context: false,
369
1
        },
370
1
        TransactionArgs {
371
1
            post_date: 0,
372
1
            enter_date: 0,
373
1
            split_count: 0,
374
1
            tag_count: 0,
375
1
            is_multi_currency: false,
376
1
        },
377
1
    );
378
1
    ser.set_primary(tx_idx);
379
1
    ser.add_split(
380
1
        EntityHeaderArgs {
381
1
            id: [2u8; 16],
382
1
            parent_idx: tx_idx as i32,
383
1
            is_primary: false,
384
1
            is_context: false,
385
1
        },
386
1
        SplitArgs {
387
1
            account_id: [3u8; 16],
388
1
            commodity_id: [4u8; 16],
389
1
            value_num: 100,
390
1
            value_denom: 1,
391
1
            reconcile_state: 0,
392
1
            reconcile_date: 0,
393
1
            account_name: "Assets:Test",
394
1
        },
395
1
    );
396
1
    ser.add_split(
397
1
        EntityHeaderArgs {
398
1
            id: [5u8; 16],
399
1
            parent_idx: tx_idx as i32,
400
1
            is_primary: false,
401
1
            is_context: false,
402
1
        },
403
1
        SplitArgs {
404
1
            account_id: [6u8; 16],
405
1
            commodity_id: [4u8; 16],
406
1
            value_num: -100,
407
1
            value_denom: 1,
408
1
            reconcile_state: 0,
409
1
            reconcile_date: 0,
410
1
            account_name: "Assets:Test",
411
1
        },
412
1
    );
413

            
414
1
    let input = ser.finalize(4096);
415
1
    let executor = ScriptExecutor::with_engine(gc_engine());
416
1
    let entities = executor.execute(&wasm, &input, Some(4096)).unwrap();
417

            
418
1
    assert_eq!(entities.len(), 1);
419
1
    assert_eq!(entities[0].entity_type, EntityType::DebugValue);
420
1
}
421

            
422
#[test]
423
1
fn test_primary_entity_idx_through_executor() {
424
1
    let _interp = Interpreter::new(false).unwrap();
425
1
    let wasm = rpc::compile_script("(primary-entity-idx)").unwrap();
426

            
427
1
    let mut ser = MemorySerializer::new();
428
1
    ser.set_context(ContextType::EntityCreate, EntityType::Transaction);
429
1
    let tx_id = [1u8; 16];
430
1
    let tx_idx = ser.add_transaction(
431
1
        EntityHeaderArgs {
432
1
            id: tx_id,
433
1
            parent_idx: -1,
434
1
            is_primary: true,
435
1
            is_context: false,
436
1
        },
437
1
        TransactionArgs {
438
1
            post_date: 0,
439
1
            enter_date: 0,
440
1
            split_count: 0,
441
1
            tag_count: 0,
442
1
            is_multi_currency: false,
443
1
        },
444
1
    );
445
1
    ser.set_primary(tx_idx);
446

            
447
1
    let input = ser.finalize(4096);
448
1
    let executor = ScriptExecutor::with_engine(gc_engine());
449
1
    let entities = executor.execute(&wasm, &input, Some(4096)).unwrap();
450

            
451
1
    assert_eq!(entities.len(), 1);
452
1
    assert_eq!(entities[0].entity_type, EntityType::DebugValue);
453
1
}
454

            
455
26
fn build_tx_with_splits() -> (MemorySerializer, u32, u32, u32) {
456
26
    let mut ser = MemorySerializer::new();
457
26
    ser.set_context(ContextType::EntityCreate, EntityType::Transaction);
458
26
    let tx_idx = ser.add_transaction(
459
26
        EntityHeaderArgs {
460
26
            id: [1u8; 16],
461
26
            parent_idx: -1,
462
26
            is_primary: true,
463
26
            is_context: false,
464
26
        },
465
26
        TransactionArgs {
466
26
            post_date: 1000,
467
26
            enter_date: 2000,
468
26
            split_count: 2,
469
26
            tag_count: 1,
470
26
            is_multi_currency: false,
471
26
        },
472
26
    );
473
26
    ser.set_primary(tx_idx);
474
26
    let s0 = ser.add_split(
475
26
        EntityHeaderArgs {
476
26
            id: [2u8; 16],
477
26
            parent_idx: tx_idx as i32,
478
26
            is_primary: false,
479
26
            is_context: false,
480
26
        },
481
26
        SplitArgs {
482
26
            account_id: [10u8; 16],
483
26
            commodity_id: [20u8; 16],
484
26
            value_num: -5000,
485
26
            value_denom: 100,
486
26
            reconcile_state: 0,
487
26
            reconcile_date: 0,
488
26
            account_name: "Assets:Test",
489
26
        },
490
26
    );
491
26
    let s1 = ser.add_split(
492
26
        EntityHeaderArgs {
493
26
            id: [3u8; 16],
494
26
            parent_idx: tx_idx as i32,
495
26
            is_primary: false,
496
26
            is_context: false,
497
26
        },
498
26
        SplitArgs {
499
26
            account_id: [11u8; 16],
500
26
            commodity_id: [20u8; 16],
501
26
            value_num: 5000,
502
26
            value_denom: 100,
503
26
            reconcile_state: 0,
504
26
            reconcile_date: 0,
505
26
            account_name: "Assets:Test",
506
26
        },
507
26
    );
508
26
    ser.add_tag([4u8; 16], tx_idx as i32, false, false, "note", "test");
509
26
    (ser, tx_idx, s0, s1)
510
26
}
511

            
512
#[test]
513
1
fn test_transaction_split_count_accessor() {
514
1
    let interp = Interpreter::new(false).unwrap();
515
1
    let wasm = rpc::compile_script(r"(= (transaction-split-count 0) 2)").unwrap();
516

            
517
1
    let (ser, ..) = build_tx_with_splits();
518
1
    let input = ser.finalize(4096);
519
1
    let result = interp
520
1
        .run_wasm_with_input(&wasm, &input)
521
1
        .unwrap()
522
1
        .expect("a result value");
523
1
    assert_eq!(result, truthy());
524
1
}
525

            
526
#[test]
527
1
fn test_transaction_tag_count_accessor() {
528
1
    let interp = Interpreter::new(false).unwrap();
529
1
    let wasm = rpc::compile_script(r"(= (transaction-tag-count 0) 1)").unwrap();
530

            
531
1
    let (ser, ..) = build_tx_with_splits();
532
1
    let input = ser.finalize(4096);
533
1
    let result = interp
534
1
        .run_wasm_with_input(&wasm, &input)
535
1
        .unwrap()
536
1
        .expect("a result value");
537
1
    assert_eq!(result, truthy());
538
1
}
539

            
540
#[test]
541
1
fn test_transaction_is_multi_currency_accessor() {
542
1
    let interp = Interpreter::new(false).unwrap();
543
1
    let wasm = rpc::compile_script(r"(null? (transaction-is-multi-currency 0))").unwrap();
544

            
545
1
    let (ser, ..) = build_tx_with_splits();
546
1
    let input = ser.finalize(4096);
547
1
    let result = interp
548
1
        .run_wasm_with_input(&wasm, &input)
549
1
        .unwrap()
550
1
        .expect("a result value");
551
1
    assert_eq!(result, truthy());
552
1
}
553

            
554
#[test]
555
1
fn test_transaction_post_date_accessor() {
556
1
    let interp = Interpreter::new(false).unwrap();
557
1
    let wasm = rpc::compile_script(r"(= (transaction-post-date 0) 1000/1)").unwrap();
558

            
559
1
    let (ser, ..) = build_tx_with_splits();
560
1
    let input = ser.finalize(4096);
561
1
    let result = interp
562
1
        .run_wasm_with_input(&wasm, &input)
563
1
        .unwrap()
564
1
        .expect("a result value");
565
1
    assert_eq!(result, truthy());
566
1
}
567

            
568
#[test]
569
1
fn test_split_value_accessor() {
570
1
    let interp = Interpreter::new(false).unwrap();
571
    // Split at index 1 has value_num=-5000, value_denom=100 → ratio -5000/100 = -50/1
572
1
    let wasm = rpc::compile_script(r"(= (split-value 1) -50/1)").unwrap();
573

            
574
1
    let (ser, ..) = build_tx_with_splits();
575
1
    let input = ser.finalize(4096);
576
1
    let result = interp
577
1
        .run_wasm_with_input(&wasm, &input)
578
1
        .unwrap()
579
1
        .expect("a result value");
580
1
    assert_eq!(result, truthy());
581
1
}
582

            
583
#[test]
584
1
fn test_split_value_num_accessor() {
585
1
    let interp = Interpreter::new(false).unwrap();
586
1
    let wasm = rpc::compile_script(r"(= (split-value-num 1) -5000/1)").unwrap();
587

            
588
1
    let (ser, ..) = build_tx_with_splits();
589
1
    let input = ser.finalize(4096);
590
1
    let result = interp
591
1
        .run_wasm_with_input(&wasm, &input)
592
1
        .unwrap()
593
1
        .expect("a result value");
594
1
    assert_eq!(result, truthy());
595
1
}
596

            
597
#[test]
598
1
fn test_split_value_denom_accessor() {
599
1
    let interp = Interpreter::new(false).unwrap();
600
1
    let wasm = rpc::compile_script(r"(= (split-value-denom 1) 100/1)").unwrap();
601

            
602
1
    let (ser, ..) = build_tx_with_splits();
603
1
    let input = ser.finalize(4096);
604
1
    let result = interp
605
1
        .run_wasm_with_input(&wasm, &input)
606
1
        .unwrap()
607
1
        .expect("a result value");
608
1
    assert_eq!(result, truthy());
609
1
}
610

            
611
#[test]
612
1
fn test_entity_type_with_constants() {
613
1
    let interp = Interpreter::new(false).unwrap();
614
1
    let wasm = rpc::compile_script(
615
1
        r"(and (= (entity-type 0) +entity-transaction+)
616
1
                    (= (entity-type 1) +entity-split+))",
617
1
    )
618
1
    .unwrap();
619

            
620
1
    let (ser, ..) = build_tx_with_splits();
621
1
    let input = ser.finalize(4096);
622
1
    let result = interp
623
1
        .run_wasm_with_input(&wasm, &input)
624
1
        .unwrap()
625
1
        .expect("a result value");
626
1
    assert_eq!(result, truthy());
627
1
}
628

            
629
#[test]
630
1
fn test_entity_parent_idx_accessor() {
631
1
    let interp = Interpreter::new(false).unwrap();
632
    // Split at index 1 should have parent_idx = 0 (the transaction)
633
1
    let wasm = rpc::compile_script(r"(= (entity-parent-idx 1) 0)").unwrap();
634

            
635
1
    let (ser, ..) = build_tx_with_splits();
636
1
    let input = ser.finalize(4096);
637
1
    let result = interp
638
1
        .run_wasm_with_input(&wasm, &input)
639
1
        .unwrap()
640
1
        .expect("a result value");
641
1
    assert_eq!(result, truthy());
642
1
}
643

            
644
#[test]
645
1
fn test_transaction_enter_date_accessor() {
646
1
    let interp = Interpreter::new(false).unwrap();
647
1
    let wasm = rpc::compile_script(r"(= (transaction-enter-date 0) 2000/1)").unwrap();
648

            
649
1
    let (ser, ..) = build_tx_with_splits();
650
1
    let input = ser.finalize(4096);
651
1
    let result = interp
652
1
        .run_wasm_with_input(&wasm, &input)
653
1
        .unwrap()
654
1
        .expect("a result value");
655
1
    assert_eq!(result, truthy());
656
1
}
657

            
658
#[test]
659
1
fn test_split_reconcile_state_accessor() {
660
1
    let interp = Interpreter::new(false).unwrap();
661
1
    let wasm = rpc::compile_script(r"(= (split-reconcile-state 1) 0)").unwrap();
662

            
663
1
    let (ser, ..) = build_tx_with_splits();
664
1
    let input = ser.finalize(4096);
665
1
    let result = interp
666
1
        .run_wasm_with_input(&wasm, &input)
667
1
        .unwrap()
668
1
        .expect("a result value");
669
1
    assert_eq!(result, truthy());
670
1
}
671

            
672
#[test]
673
1
fn test_split_reconcile_date_accessor() {
674
1
    let interp = Interpreter::new(false).unwrap();
675
1
    let wasm = rpc::compile_script(r"(= (split-reconcile-date 1) 0/1)").unwrap();
676

            
677
1
    let (ser, ..) = build_tx_with_splits();
678
1
    let input = ser.finalize(4096);
679
1
    let result = interp
680
1
        .run_wasm_with_input(&wasm, &input)
681
1
        .unwrap()
682
1
        .expect("a result value");
683
1
    assert_eq!(result, truthy());
684
1
}
685

            
686
#[test]
687
1
fn test_runtime_cons_car() {
688
1
    let interp = Interpreter::new(false).unwrap();
689
    // Build a runtime cons list from entity indices and get the first element
690
1
    let wasm = rpc::compile_script(
691
1
        r"(let ((idx (primary-entity-idx)))
692
1
                   (= (car (cons idx nil)) 0))",
693
1
    )
694
1
    .unwrap();
695

            
696
1
    let (ser, ..) = build_tx_with_splits();
697
1
    let input = ser.finalize(4096);
698
1
    let result = interp
699
1
        .run_wasm_with_input(&wasm, &input)
700
1
        .unwrap()
701
1
        .expect("a result value");
702
1
    assert_eq!(result, truthy());
703
1
}
704

            
705
#[test]
706
1
fn test_runtime_cons_null_cdr() {
707
1
    let interp = Interpreter::new(false).unwrap();
708
    // CDR of a single-element cons list should be null
709
1
    let wasm = rpc::compile_script(
710
1
        r"(let ((idx (primary-entity-idx)))
711
1
                   (null? (cdr (cons idx nil))))",
712
1
    )
713
1
    .unwrap();
714

            
715
1
    let (ser, ..) = build_tx_with_splits();
716
1
    let input = ser.finalize(4096);
717
1
    let result = interp
718
1
        .run_wasm_with_input(&wasm, &input)
719
1
        .unwrap()
720
1
        .expect("a result value");
721
1
    assert_eq!(result, truthy());
722
1
}
723

            
724
#[test]
725
1
fn test_runtime_do_loop_cons_list() {
726
1
    let interp = Interpreter::new(false).unwrap();
727
    // Build a list of split entity indices by filtering entity-type = split(1)
728
    // Entities: 0=tx, 1=split, 2=split, 3=tag → splits at indices 1, 2
729
1
    let wasm = rpc::compile_script(
730
1
        r"(do ((i 0 (+ i 1))
731
1
                     (result nil (if (= (entity-type i) +entity-split+)
732
1
                                     (cons i result)
733
1
                                     result)))
734
1
                    ((>= i (entity-count)) (car result)))",
735
1
    )
736
1
    .unwrap();
737

            
738
1
    let (ser, ..) = build_tx_with_splits();
739
1
    let input = ser.finalize(4096);
740
1
    let result = interp
741
1
        .run_wasm_with_input(&wasm, &input)
742
1
        .unwrap()
743
1
        .expect("a result value");
744
    // Last split added = index 2, so car(result) = 2
745
1
    assert_eq!(result, Value::Number(Number::Index(2)));
746
1
}
747

            
748
#[test]
749
1
fn test_create_tag_output() {
750
1
    let _interp = Interpreter::new(false).unwrap();
751
1
    let wasm = rpc::compile_script(r#"(create-tag 0 "note" "test-value")"#).unwrap();
752

            
753
1
    let (ser, tx_idx, ..) = build_tx_with_splits();
754
1
    let input = ser.finalize(4096);
755
1
    let executor = ScriptExecutor::with_engine(gc_engine());
756
1
    let entities = executor.execute(&wasm, &input, Some(4096)).unwrap();
757

            
758
1
    assert_eq!(entities.len(), 1, "expected one tag entity");
759
1
    assert_eq!(entities[0].entity_type, EntityType::Tag);
760
1
    assert_eq!(entities[0].parent_idx, tx_idx as i32);
761
1
    if let EntityData::Tag { name, value } = &entities[0].data {
762
1
        assert_eq!(name, "note");
763
1
        assert_eq!(value, "test-value");
764
    } else {
765
        panic!("expected Tag data, got {:?}", entities[0].data);
766
    }
767
1
}
768

            
769
#[test]
770
1
fn test_create_tag_with_runtime_parent() {
771
1
    let _interp = Interpreter::new(false).unwrap();
772
    let wasm =
773
1
        rpc::compile_script(r#"(create-tag (primary-entity-idx) "category" "food")"#).unwrap();
774

            
775
1
    let (ser, tx_idx, ..) = build_tx_with_splits();
776
1
    let input = ser.finalize(4096);
777
1
    let executor = ScriptExecutor::with_engine(gc_engine());
778
1
    let entities = executor.execute(&wasm, &input, Some(4096)).unwrap();
779

            
780
1
    assert_eq!(entities.len(), 1, "expected one tag entity");
781
1
    assert_eq!(entities[0].entity_type, EntityType::Tag);
782
1
    assert_eq!(entities[0].parent_idx, tx_idx as i32);
783
1
    if let EntityData::Tag { name, value } = &entities[0].data {
784
1
        assert_eq!(name, "category");
785
1
        assert_eq!(value, "food");
786
    } else {
787
        panic!("expected Tag data, got {:?}", entities[0].data);
788
    }
789
1
}
790

            
791
#[test]
792
1
fn test_create_tag_as_side_effect() {
793
1
    let _interp = Interpreter::new(false).unwrap();
794
    // create-tag used as intermediate expression, not last
795
1
    let wasm = rpc::compile_script(
796
1
        r#"(let ((idx (primary-entity-idx)))
797
1
                   (create-tag idx "side" "effect")
798
1
                   42)"#,
799
1
    )
800
1
    .unwrap();
801

            
802
1
    let (ser, tx_idx, ..) = build_tx_with_splits();
803
1
    let input = ser.finalize(4096);
804
1
    let executor = ScriptExecutor::with_engine(gc_engine());
805
1
    let entities = executor.execute(&wasm, &input, Some(4096)).unwrap();
806

            
807
    // Should have both the tag and the debug value (42)
808
1
    assert_eq!(entities.len(), 2, "expected tag + debug value");
809
1
    let tag = entities.iter().find(|e| e.entity_type == EntityType::Tag);
810
1
    assert!(tag.is_some(), "expected a tag entity in output");
811
1
    let tag = tag.unwrap();
812
1
    assert_eq!(tag.parent_idx, tx_idx as i32);
813
1
    if let EntityData::Tag { name, value } = &tag.data {
814
1
        assert_eq!(name, "side");
815
1
        assert_eq!(value, "effect");
816
    } else {
817
        panic!("expected Tag data");
818
    }
819
1
}
820

            
821
#[test]
822
1
fn test_create_tag_then_string_result_both_decode() {
823
    // Mixed output stream: a create-tag (tag strings grow DOWN from the buffer
824
    // end, read by the entity parser via strings_offset) followed by a STRING
825
    // program result (decoded inline from its own entity). Both must survive in
826
    // one buffer — the regression for the single-path output unification.
827
1
    let interp = Interpreter::new(false).unwrap();
828
1
    let wasm = rpc::compile_script(
829
1
        r#"(let ((idx (primary-entity-idx)))
830
1
                   (create-tag idx "k" "v")
831
1
                   "done")"#,
832
1
    )
833
1
    .unwrap();
834

            
835
1
    let (ser, tx_idx, ..) = build_tx_with_splits();
836
1
    let input = ser.finalize(4096);
837
1
    let entities = ScriptExecutor::with_engine(gc_engine())
838
1
        .execute(&wasm, &input, Some(4096))
839
1
        .unwrap();
840

            
841
1
    let tag = entities
842
1
        .iter()
843
1
        .find(|e| e.entity_type == EntityType::Tag)
844
1
        .expect("tag entity present");
845
1
    assert_eq!(tag.parent_idx, tx_idx as i32);
846
1
    let EntityData::Tag { name, value } = &tag.data else {
847
        panic!("expected Tag data");
848
    };
849
1
    assert_eq!(name, "k");
850
1
    assert_eq!(value, "v");
851

            
852
    // The interpreter eval path must still decode the trailing string result,
853
    // selecting the DebugValue entity past the create-tag.
854
1
    let result = interp
855
1
        .run_wasm_with_input(&wasm, &input)
856
1
        .unwrap()
857
1
        .expect("a result value");
858
1
    assert_eq!(result, Value::String("done".to_string()));
859
1
}
860

            
861
#[test]
862
1
fn test_runtime_dolist_over_cons_list() {
863
1
    let interp = Interpreter::new(false).unwrap();
864
    // Build a cons list of split indices via DO, then iterate with DOLIST counting elements
865
1
    let wasm = rpc::compile_script(
866
1
        r"(let* ((splits (do ((i 0 (+ i 1))
867
1
                                  (result nil (if (= (entity-type i) +entity-split+)
868
1
                                                  (cons i result)
869
1
                                                  result)))
870
1
                                 ((>= i (entity-count)) result)))
871
1
                    (count 0))
872
1
                   (dolist (s splits)
873
1
                       (setf count (+ count 1)))
874
1
                   count)",
875
1
    )
876
1
    .unwrap();
877

            
878
1
    let (ser, ..) = build_tx_with_splits();
879
1
    let input = ser.finalize(4096);
880
1
    let result = interp
881
1
        .run_wasm_with_input(&wasm, &input)
882
1
        .unwrap()
883
1
        .expect("a result value");
884
    // 2 splits in the input (indices 1, 2)
885
1
    assert_eq!(result, index(2));
886
1
}
887

            
888
#[test]
889
1
fn test_delete_entity_output() {
890
1
    let _interp = Interpreter::new(false).unwrap();
891
1
    let wasm = rpc::compile_script(r"(delete-entity 0)").unwrap();
892

            
893
1
    let (ser, _tx_idx, ..) = build_tx_with_splits();
894
1
    let input = ser.finalize(4096);
895
1
    let executor = ScriptExecutor::with_engine(gc_engine());
896
1
    let entities = executor.execute(&wasm, &input, Some(4096)).unwrap();
897

            
898
1
    assert_eq!(entities.len(), 1, "expected one delete entity");
899
1
    assert_eq!(entities[0].entity_type, EntityType::Transaction);
900
1
    assert_eq!(entities[0].operation, Operation::Delete);
901
1
    assert_eq!(entities[0].id, [1u8; 16]);
902
1
    assert_eq!(entities[0].parent_idx, -1);
903
1
}
904

            
905
#[test]
906
1
fn test_delete_entity_with_runtime_idx() {
907
1
    let _interp = Interpreter::new(false).unwrap();
908
1
    let wasm = rpc::compile_script(r"(delete-entity (primary-entity-idx))").unwrap();
909

            
910
1
    let (ser, ..) = build_tx_with_splits();
911
1
    let input = ser.finalize(4096);
912
1
    let executor = ScriptExecutor::with_engine(gc_engine());
913
1
    let entities = executor.execute(&wasm, &input, Some(4096)).unwrap();
914

            
915
1
    assert_eq!(entities.len(), 1);
916
1
    assert_eq!(entities[0].entity_type, EntityType::Transaction);
917
1
    assert_eq!(entities[0].operation, Operation::Delete);
918
1
    assert_eq!(entities[0].id, [1u8; 16]);
919
1
}
920

            
921
#[test]
922
1
fn test_delete_entity_split() {
923
1
    let _interp = Interpreter::new(false).unwrap();
924
1
    let wasm = rpc::compile_script(r"(delete-entity 1)").unwrap();
925

            
926
1
    let (ser, ..) = build_tx_with_splits();
927
1
    let input = ser.finalize(4096);
928
1
    let executor = ScriptExecutor::with_engine(gc_engine());
929
1
    let entities = executor.execute(&wasm, &input, Some(4096)).unwrap();
930

            
931
1
    assert_eq!(entities.len(), 1);
932
1
    assert_eq!(entities[0].entity_type, EntityType::Split);
933
1
    assert_eq!(entities[0].operation, Operation::Delete);
934
1
    assert_eq!(entities[0].id, [2u8; 16]);
935
1
}
936

            
937
#[test]
938
1
fn test_should_apply_default() {
939
1
    let _interp = Interpreter::new(false).unwrap();
940
1
    let wasm = rpc::compile_script(r"42").unwrap();
941
1
    let module = Module::new(&gc_engine(), &wasm).unwrap();
942

            
943
25
    let exports: Vec<_> = module.exports().map(|e| e.name().to_string()).collect();
944
1
    assert!(exports.contains(&"should_apply".to_string()));
945
1
    assert!(exports.contains(&"process".to_string()));
946
1
}
947

            
948
#[test]
949
1
fn test_should_apply_custom() {
950
1
    let _interp = Interpreter::new(false).unwrap();
951
1
    let wasm = rpc::compile_script(
952
1
        r#"(defun should-apply ()
953
1
                   (= (primary-entity-type) +entity-transaction+))
954
1
               (create-tag 0 "test" "value")"#,
955
1
    )
956
1
    .unwrap();
957

            
958
1
    let (ser, ..) = build_tx_with_splits();
959
1
    let input = ser.finalize(4096);
960
1
    let executor = ScriptExecutor::with_engine(gc_engine());
961
1
    let entities = executor.execute(&wasm, &input, Some(4096)).unwrap();
962
1
    assert!(
963
1
        !entities.is_empty(),
964
        "should_apply should return true for transactions"
965
    );
966
1
}
967

            
968
#[test]
969
1
fn test_should_apply_rejects() {
970
1
    let _interp = Interpreter::new(false).unwrap();
971
1
    let wasm = rpc::compile_script(
972
1
        r"(defun should-apply ()
973
1
                   (= (primary-entity-type) +entity-account+))
974
1
               42",
975
1
    )
976
1
    .unwrap();
977

            
978
1
    let (ser, ..) = build_tx_with_splits();
979
1
    let input = ser.finalize(4096);
980
1
    let executor = ScriptExecutor::with_engine(gc_engine());
981
1
    let entities = executor.execute(&wasm, &input, Some(4096)).unwrap();
982
1
    assert!(
983
1
        entities.is_empty(),
984
        "should_apply should return false for non-accounts"
985
    );
986
1
}
987

            
988
#[test]
989
1
fn test_get_input_entities() {
990
1
    let interp = Interpreter::new(false).unwrap();
991
    // Count entities by iterating the cons list from get-input-entities
992
1
    let wasm = rpc::compile_script(
993
1
        r"(let ((count 0))
994
1
                   (dolist (e (get-input-entities))
995
1
                       (setf count (+ count 1)))
996
1
                   count)",
997
1
    )
998
1
    .unwrap();
999

            
1
    let (ser, ..) = build_tx_with_splits();
1
    let input = ser.finalize(4096);
1
    let result = interp
1
        .run_wasm_with_input(&wasm, &input)
1
        .unwrap()
1
        .expect("a result value");
    // 4 entities: 1 transaction + 2 splits + 1 tag
1
    assert_eq!(result, index(4));
1
}
// Large constant-init DO loop (> MAX_STATIC_LOOP_ITERS=64): must fall back to runtime WASM
// path rather than attempting compile-time unrolling that would hang the compiler.
#[test]
1
fn test_do_large_constant_loop_compiles_and_runs() {
1
    let interp = Interpreter::new(false).unwrap();
    let wasm =
1
        rpc::compile_script("(do ((i 0 (+ i 1)) (sum 0 (+ sum i))) ((= i 100) sum))").unwrap();
1
    let input = build_minimal_input(4096);
1
    let result = interp
1
        .run_wasm_with_input(&wasm, &input)
1
        .unwrap()
1
        .expect("a result value");
1
    assert_eq!(result, index(4950));
1
}
#[test]
1
fn test_do_star_large_constant_loop_compiles_and_runs() {
1
    let interp = Interpreter::new(false).unwrap();
    // DO* steps sequentially: acc's step sees the already-incremented i, so sum = 1+2+...+100
    let wasm =
1
        rpc::compile_script("(do* ((i 0 (+ i 1)) (acc 0 (+ acc i))) ((= i 100) acc))").unwrap();
1
    let input = build_minimal_input(4096);
1
    let result = interp
1
        .run_wasm_with_input(&wasm, &input)
1
        .unwrap()
1
        .expect("a result value");
1
    assert_eq!(result, index(5050));
1
}