packr 0.7.1

A WebAssembly package runtime with extended WIT support for recursive types
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
//! Basic WASM execution tests
//!
//! These tests verify that we can load and run WASM modules through the Runtime.

use packr::abi::{Value, ValueType};
use packr::Runtime;
use std::path::Path;

/// A minimal WAT module that exports an `add` function
const ADD_MODULE: &str = r#"
(module
    (func $add (param $a i32) (param $b i32) (result i32)
        local.get $a
        local.get $b
        i32.add
    )
    (export "add" (func $add))
)
"#;

#[test]
fn run_add_module() {
    // Parse WAT to WASM bytes
    let wasm_bytes = wat::parse_str(ADD_MODULE).expect("failed to parse WAT");

    // Create the runtime and load the module
    let runtime = Runtime::new();
    let module = runtime
        .load_module(&wasm_bytes)
        .expect("failed to load module");

    // Instantiate and run
    let mut instance = module.instantiate().expect("failed to instantiate");

    // Call the add function
    let result = instance
        .call_i32_i32_to_i32("add", 2, 3)
        .expect("failed to call add");
    assert_eq!(result, 5);

    // Try a few more values
    assert_eq!(instance.call_i32_i32_to_i32("add", 0, 0).unwrap(), 0);
    assert_eq!(instance.call_i32_i32_to_i32("add", -1, 1).unwrap(), 0);
    assert_eq!(instance.call_i32_i32_to_i32("add", 100, 200).unwrap(), 300);
}

/// A module that uses i64 instead
const ADD64_MODULE: &str = r#"
(module
    (func $add64 (param $a i64) (param $b i64) (result i64)
        local.get $a
        local.get $b
        i64.add
    )
    (export "add64" (func $add64))
)
"#;

#[test]
fn run_add64_module() {
    let wasm_bytes = wat::parse_str(ADD64_MODULE).expect("failed to parse WAT");

    let runtime = Runtime::new();
    let module = runtime
        .load_module(&wasm_bytes)
        .expect("failed to load module");
    let mut instance = module.instantiate().expect("failed to instantiate");

    let result = instance
        .call_i64_i64_to_i64("add64", 1_000_000_000_000, 2_000_000_000_000)
        .expect("failed to call add64");
    assert_eq!(result, 3_000_000_000_000);
}

/// Test calling a non-existent function
#[test]
fn call_missing_function() {
    let wasm_bytes = wat::parse_str(ADD_MODULE).expect("failed to parse WAT");

    let runtime = Runtime::new();
    let module = runtime
        .load_module(&wasm_bytes)
        .expect("failed to load module");
    let mut instance = module.instantiate().expect("failed to instantiate");

    let err = instance.call_i32_i32_to_i32("nonexistent", 1, 2);
    assert!(err.is_err());
}

// ============================================================================
// Memory access tests
// ============================================================================

/// A module with memory - sums bytes in a range
const SUM_BYTES_MODULE: &str = r#"
(module
    (memory (export "memory") 1)

    ;; Sum bytes from ptr to ptr+len
    (func $sum_bytes (param $ptr i32) (param $len i32) (result i32)
        (local $sum i32)
        (local $end i32)

        ;; end = ptr + len
        (local.set $end (i32.add (local.get $ptr) (local.get $len)))

        ;; while ptr < end
        (block $break
            (loop $continue
                ;; if ptr >= end, break
                (br_if $break (i32.ge_u (local.get $ptr) (local.get $end)))

                ;; sum += *ptr
                (local.set $sum
                    (i32.add
                        (local.get $sum)
                        (i32.load8_u (local.get $ptr))))

                ;; ptr++
                (local.set $ptr (i32.add (local.get $ptr) (i32.const 1)))

                (br $continue)
            )
        )

        (local.get $sum)
    )
    (export "sum_bytes" (func $sum_bytes))
)
"#;

#[test]
fn memory_read_write() {
    let wasm_bytes = wat::parse_str(SUM_BYTES_MODULE).expect("failed to parse WAT");

    let runtime = Runtime::new();
    let module = runtime
        .load_module(&wasm_bytes)
        .expect("failed to load module");
    let mut instance = module.instantiate().expect("failed to instantiate");

    // Write some bytes to memory
    let data = [1u8, 2, 3, 4, 5];
    instance
        .write_memory(0, &data)
        .expect("failed to write memory");

    // Call sum_bytes(0, 5) - should return 1+2+3+4+5 = 15
    let result = instance
        .call_i32_i32_to_i32("sum_bytes", 0, 5)
        .expect("failed to call sum_bytes");
    assert_eq!(result, 15);

    // Read the bytes back
    let read_back = instance.read_memory(0, 5).expect("failed to read memory");
    assert_eq!(read_back, data);
}

#[test]
fn memory_string_roundtrip() {
    let wasm_bytes = wat::parse_str(SUM_BYTES_MODULE).expect("failed to parse WAT");

    let runtime = Runtime::new();
    let module = runtime
        .load_module(&wasm_bytes)
        .expect("failed to load module");
    let mut instance = module.instantiate().expect("failed to instantiate");

    // Write a string to memory
    let message = "Hello, WebAssembly!";
    instance
        .write_memory(100, message.as_bytes())
        .expect("failed to write string");

    // Read it back
    let read_back = instance
        .read_memory(100, message.len())
        .expect("failed to read string");

    let read_string = String::from_utf8(read_back).expect("invalid utf8");
    assert_eq!(read_string, message);

    // Sum the bytes (just to prove the module can read our string)
    let sum: i32 = message.as_bytes().iter().map(|&b| b as i32).sum();
    let result = instance
        .call_i32_i32_to_i32("sum_bytes", 100, message.len() as i32)
        .expect("failed to call sum_bytes");
    assert_eq!(result, sum);
}

/// A module that reverses bytes in place
const REVERSE_MODULE: &str = r#"
(module
    (memory (export "memory") 1)

    ;; Reverse bytes from ptr to ptr+len in place
    (func $reverse (param $ptr i32) (param $len i32)
        (local $left i32)
        (local $right i32)
        (local $tmp i32)

        (local.set $left (local.get $ptr))
        (local.set $right (i32.sub (i32.add (local.get $ptr) (local.get $len)) (i32.const 1)))

        (block $break
            (loop $continue
                ;; if left >= right, break
                (br_if $break (i32.ge_u (local.get $left) (local.get $right)))

                ;; swap *left and *right
                (local.set $tmp (i32.load8_u (local.get $left)))
                (i32.store8 (local.get $left) (i32.load8_u (local.get $right)))
                (i32.store8 (local.get $right) (local.get $tmp))

                ;; left++, right--
                (local.set $left (i32.add (local.get $left) (i32.const 1)))
                (local.set $right (i32.sub (local.get $right) (i32.const 1)))

                (br $continue)
            )
        )
    )
    (export "reverse" (func $reverse))
)
"#;

#[test]
fn memory_reverse_string() {
    let wasm_bytes = wat::parse_str(REVERSE_MODULE).expect("failed to parse WAT");

    let runtime = Runtime::new();
    let module = runtime
        .load_module(&wasm_bytes)
        .expect("failed to load module");
    let mut instance = module.instantiate().expect("failed to instantiate");

    // Write a string
    let message = "Hello";
    instance
        .write_memory(0, message.as_bytes())
        .expect("failed to write");

    // Call the WASM reverse function
    instance
        .call_i32_i32("reverse", 0, message.len() as i32)
        .expect("failed to call reverse");

    // Read back the reversed string
    let result = instance.read_memory(0, 5).expect("read back");
    assert_eq!(result, b"olleH");
}

// ============================================================================
// Graph ABI tests
// ============================================================================

/// An echo module using the Pack ABI guest-allocates convention.
/// Calling convention: (in_ptr, in_len, out_ptr_ptr, out_len_ptr) -> status
/// Guest copies input to a fixed output location and writes ptr/len to provided slots.
const ECHO_MODULE: &str = r#"
(module
    (memory (export "memory") 1)

    ;; Fixed output buffer location (after result slots at 16KB+8)
    (global $output_offset i32 (i32.const 16392))

    ;; Echo: copy input to output buffer and write ptr/len to result slots
    ;; Returns 0 on success
    (func $echo (param $in_ptr i32) (param $in_len i32) (param $out_ptr_ptr i32) (param $out_len_ptr i32) (result i32)
        ;; Copy input to output buffer
        (memory.copy (global.get $output_offset) (local.get $in_ptr) (local.get $in_len))

        ;; Write output pointer to the ptr slot
        (i32.store (local.get $out_ptr_ptr) (global.get $output_offset))

        ;; Write output length to the len slot
        (i32.store (local.get $out_len_ptr) (local.get $in_len))

        ;; Return 0 (success)
        (i32.const 0)
    )
    (export "echo" (func $echo))
)
"#;

#[test]
fn graph_abi_echo_roundtrip() {
    let wasm_bytes = wat::parse_str(ECHO_MODULE).expect("failed to parse WAT");

    let runtime = Runtime::new();
    let module = runtime
        .load_module(&wasm_bytes)
        .expect("failed to load module");
    let mut instance = module.instantiate().expect("failed to instantiate");

    // Test with a simple integer
    let input = Value::S64(42);
    let output = instance
        .call_with_value("echo", &input)
        .expect("failed to call echo");
    assert_eq!(output, input);
}

#[test]
fn graph_abi_echo_string() {
    let wasm_bytes = wat::parse_str(ECHO_MODULE).expect("failed to parse WAT");

    let runtime = Runtime::new();
    let module = runtime
        .load_module(&wasm_bytes)
        .expect("failed to load module");
    let mut instance = module.instantiate().expect("failed to instantiate");

    let input = Value::String("Hello, Graph ABI!".to_string());
    let output = instance
        .call_with_value("echo", &input)
        .expect("failed to call echo");
    assert_eq!(output, input);
}

#[test]
fn graph_abi_echo_list() {
    let wasm_bytes = wat::parse_str(ECHO_MODULE).expect("failed to parse WAT");

    let runtime = Runtime::new();
    let module = runtime
        .load_module(&wasm_bytes)
        .expect("failed to load module");
    let mut instance = module.instantiate().expect("failed to instantiate");

    let input = Value::List {
        elem_type: ValueType::S64,
        items: vec![Value::S64(1), Value::S64(2), Value::S64(3)],
    };
    let output = instance
        .call_with_value("echo", &input)
        .expect("failed to call echo");
    assert_eq!(output, input);
}

#[test]
fn graph_abi_echo_variant() {
    let wasm_bytes = wat::parse_str(ECHO_MODULE).expect("failed to parse WAT");

    let runtime = Runtime::new();
    let module = runtime
        .load_module(&wasm_bytes)
        .expect("failed to load module");
    let mut instance = module.instantiate().expect("failed to instantiate");

    // This is like a simple S-expression node
    let input = Value::Variant {
        type_name: "node".to_string(),
        case_name: "sym".to_string(),
        tag: 1,
        payload: vec![Value::String("symbol".to_string())],
    };
    let output = instance
        .call_with_value("echo", &input)
        .expect("failed to call echo");
    assert_eq!(output, input);
}

#[test]
fn graph_abi_echo_nested() {
    let wasm_bytes = wat::parse_str(ECHO_MODULE).expect("failed to parse WAT");

    let runtime = Runtime::new();
    let module = runtime
        .load_module(&wasm_bytes)
        .expect("failed to load module");
    let mut instance = module.instantiate().expect("failed to instantiate");

    // A nested structure like (list (sym "a") (num 42))
    let input = Value::List {
        elem_type: ValueType::Variant("node".to_string()),
        items: vec![
            Value::Variant {
                type_name: "node".to_string(),
                case_name: "sym".to_string(),
                tag: 0,
                payload: vec![Value::String("list".to_string())],
            },
            Value::List {
                elem_type: ValueType::Variant("node".to_string()),
                items: vec![
                    Value::Variant {
                        type_name: "node".to_string(),
                        case_name: "sym".to_string(),
                        tag: 0,
                        payload: vec![Value::String("a".to_string())],
                    },
                    Value::Variant {
                        type_name: "node".to_string(),
                        case_name: "num".to_string(),
                        tag: 1,
                        payload: vec![Value::S64(42)],
                    },
                ],
            },
        ],
    };
    let output = instance
        .call_with_value("echo", &input)
        .expect("failed to call echo");
    assert_eq!(output, input);
}

// ============================================================================
// Rust package tests
// ============================================================================

/// Load the Rust-compiled echo package
fn load_rust_echo_package() -> Vec<u8> {
    let wasm_path = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("packages/echo/target/wasm32-unknown-unknown/release/echo_package.wasm");
    std::fs::read(&wasm_path).unwrap_or_else(|e| {
        panic!(
            "Failed to read Rust package at {}: {}. Run: cd packages/echo && cargo build --target wasm32-unknown-unknown --release",
            wasm_path.display(),
            e
        )
    })
}

#[test]
fn rust_package_echo_roundtrip() {
    let wasm_bytes = load_rust_echo_package();

    let runtime = Runtime::new();
    let module = runtime
        .load_module(&wasm_bytes)
        .expect("failed to load Rust package");
    let mut instance = module.instantiate().expect("failed to instantiate");

    // Test with a simple integer
    let input = Value::S64(42);
    let output = instance
        .call_with_value("echo", &input)
        .expect("failed to call echo");
    assert_eq!(output, input);
}

#[test]
fn rust_package_echo_complex() {
    let wasm_bytes = load_rust_echo_package();

    let runtime = Runtime::new();
    let module = runtime
        .load_module(&wasm_bytes)
        .expect("failed to load Rust package");
    let mut instance = module.instantiate().expect("failed to instantiate");

    // Test with a nested structure
    let input = Value::List {
        elem_type: ValueType::String, // Mixed types, use String as placeholder
        items: vec![
            Value::String("hello".to_string()),
            Value::Variant {
                type_name: "node".to_string(),
                case_name: "list".to_string(),
                tag: 2,
                payload: vec![Value::List {
                    elem_type: ValueType::S64,
                    items: vec![Value::S64(1), Value::S64(2), Value::S64(3)],
                }],
            },
            Value::Option {
                inner_type: ValueType::Bool,
                value: Some(Box::new(Value::Bool(true))),
            },
        ],
    };

    let output = instance
        .call_with_value("echo", &input)
        .expect("failed to call echo");
    assert_eq!(output, input);
}

#[test]
fn rust_package_transform_doubles_s64() {
    let wasm_bytes = load_rust_echo_package();

    let runtime = Runtime::new();
    let module = runtime
        .load_module(&wasm_bytes)
        .expect("failed to load Rust package");
    let mut instance = module.instantiate().expect("failed to instantiate");

    // Test transform doubles S64
    let input = Value::S64(21);
    let output = instance
        .call_with_value("transform", &input)
        .expect("failed to call transform");
    assert_eq!(output, Value::S64(42));
}

#[test]
fn rust_package_transform_nested() {
    let wasm_bytes = load_rust_echo_package();

    let runtime = Runtime::new();
    let module = runtime
        .load_module(&wasm_bytes)
        .expect("failed to load Rust package");
    let mut instance = module.instantiate().expect("failed to instantiate");

    // Test transform on nested structure - doubles all S64 values
    let input = Value::List {
        elem_type: ValueType::Variant("node".to_string()),
        items: vec![
            Value::S64(10),
            Value::S64(20),
            Value::Variant {
                type_name: "node".to_string(),
                case_name: "num".to_string(),
                tag: 1,
                payload: vec![Value::S64(50)],
            },
        ],
    };

    let expected = Value::List {
        elem_type: ValueType::Variant("node".to_string()),
        items: vec![
            Value::S64(20), // 10 * 2
            Value::S64(40), // 20 * 2
            Value::Variant {
                type_name: "node".to_string(),
                case_name: "num".to_string(),
                tag: 1,
                payload: vec![Value::S64(100)], // 50 * 2
            },
        ],
    };

    let output = instance
        .call_with_value("transform", &input)
        .expect("failed to call transform");
    assert_eq!(output, expected);
}

#[test]
fn rust_package_transform_preserves_strings() {
    let wasm_bytes = load_rust_echo_package();

    let runtime = Runtime::new();
    let module = runtime
        .load_module(&wasm_bytes)
        .expect("failed to load Rust package");
    let mut instance = module.instantiate().expect("failed to instantiate");

    // Strings should pass through unchanged
    let input = Value::String("hello world".to_string());
    let output = instance
        .call_with_value("transform", &input)
        .expect("failed to call transform");
    assert_eq!(output, input);
}

// ============================================================================
// Host imports tests
// ============================================================================

use packr::runtime::HostImports;

/// Load the Rust-compiled logger package (uses host imports)
fn load_rust_logger_package() -> Vec<u8> {
    let wasm_path = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("packages/logger/target/wasm32-unknown-unknown/release/logger_package.wasm");
    std::fs::read(&wasm_path).unwrap_or_else(|e| {
        panic!(
            "Failed to read logger package at {}: {}. Run: cd packages/logger && cargo build --target wasm32-unknown-unknown --release",
            wasm_path.display(),
            e
        )
    })
}

#[test]
fn host_imports_logging() {
    let wasm_bytes = load_rust_logger_package();

    let runtime = Runtime::new();
    let module = runtime
        .load_module(&wasm_bytes)
        .expect("failed to load logger package");

    // Instantiate with host imports
    let imports = HostImports::new();
    let mut instance = module
        .instantiate_with_imports(imports)
        .expect("failed to instantiate with imports");

    // Call process with a value - this should log messages
    let input = Value::S64(42);
    let output = instance
        .call_with_value("process", &input)
        .expect("failed to call process");

    // The transform doubles S64 values
    assert_eq!(output, Value::S64(84));

    // Check that we captured log messages
    let logs = instance.get_logs();
    assert!(!logs.is_empty(), "Expected log messages");

    // Verify specific log messages
    assert!(
        logs.iter().any(|m| m.contains("starting")),
        "Expected 'starting' log"
    );
    assert!(
        logs.iter().any(|m| m.contains("got S64")),
        "Expected S64 type log"
    );
    assert!(
        logs.iter().any(|m| m.contains("done")),
        "Expected 'done' log"
    );
}

#[test]
fn host_imports_logging_with_string() {
    let wasm_bytes = load_rust_logger_package();

    let runtime = Runtime::new();
    let module = runtime
        .load_module(&wasm_bytes)
        .expect("failed to load logger package");

    let imports = HostImports::new();
    let mut instance = module
        .instantiate_with_imports(imports)
        .expect("failed to instantiate with imports");

    // Call with a string value
    let input = Value::String("test message".to_string());
    let output = instance
        .call_with_value("process", &input)
        .expect("failed to call process");

    // Strings pass through unchanged
    assert_eq!(output, input);

    let logs = instance.get_logs();
    assert!(
        logs.iter().any(|m| m.contains("got String")),
        "Expected String type log"
    );
    assert!(
        logs.iter().any(|m| m.contains("test message")),
        "Expected the actual string in logs"
    );
}

#[test]
fn host_imports_transform_nested() {
    let wasm_bytes = load_rust_logger_package();

    let runtime = Runtime::new();
    let module = runtime
        .load_module(&wasm_bytes)
        .expect("failed to load logger package");

    let imports = HostImports::new();
    let mut instance = module
        .instantiate_with_imports(imports)
        .expect("failed to instantiate with imports");

    // Test with a list of S64 values
    let input = Value::List {
        elem_type: ValueType::S64,
        items: vec![Value::S64(10), Value::S64(20), Value::S64(30)],
    };

    let expected = Value::List {
        elem_type: ValueType::S64,
        items: vec![Value::S64(20), Value::S64(40), Value::S64(60)],
    };

    let output = instance
        .call_with_value("process", &input)
        .expect("failed to call process");

    assert_eq!(output, expected);

    // Verify logging happened
    let logs = instance.get_logs();
    assert!(
        logs.iter().any(|m| m.contains("got List")),
        "Expected List type log"
    );
}

#[test]
fn host_imports_clear_logs() {
    let wasm_bytes = load_rust_logger_package();

    let runtime = Runtime::new();
    let module = runtime
        .load_module(&wasm_bytes)
        .expect("failed to load logger package");

    let imports = HostImports::new();
    let mut instance = module
        .instantiate_with_imports(imports)
        .expect("failed to instantiate with imports");

    // First call
    let input = Value::S64(1);
    let _ = instance.call_with_value("process", &input).unwrap();

    let logs1 = instance.get_logs();
    assert!(!logs1.is_empty());

    // Clear logs
    instance.clear_logs();
    assert!(instance.get_logs().is_empty(), "Logs should be cleared");

    // Second call
    let _ = instance.call_with_value("process", &input).unwrap();
    let logs2 = instance.get_logs();
    assert!(!logs2.is_empty());

    // Should only have logs from second call
    assert!(
        logs2.len() < logs1.len() * 2,
        "Should only have logs from second call"
    );
}

// ============================================================================
// S-expression evaluator tests
// ============================================================================

/// Load the Rust-compiled sexpr package
fn load_rust_sexpr_package() -> Vec<u8> {
    let wasm_path = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("packages/sexpr/target/wasm32-unknown-unknown/release/sexpr_package.wasm");
    std::fs::read(&wasm_path).unwrap_or_else(|e| {
        panic!(
            "Failed to read sexpr package at {}: {}. Run: cd packages/sexpr && cargo build --target wasm32-unknown-unknown --release",
            wasm_path.display(),
            e
        )
    })
}

/// Helper to create an SExpr value for testing
#[allow(dead_code)]
mod sexpr {
    use packr::abi::Value;

    pub fn sym(s: &str) -> Value {
        Value::Variant {
            type_name: "expr".to_string(),
            case_name: "sym".to_string(),
            tag: 0,
            payload: vec![Value::String(s.to_string())],
        }
    }

    pub fn num(n: i64) -> Value {
        Value::Variant {
            type_name: "expr".to_string(),
            case_name: "num".to_string(),
            tag: 1,
            payload: vec![Value::S64(n)],
        }
    }

    pub fn float(f: f64) -> Value {
        Value::Variant {
            type_name: "expr".to_string(),
            case_name: "float".to_string(),
            tag: 2,
            payload: vec![Value::F64(f)],
        }
    }

    pub fn boolean(b: bool) -> Value {
        Value::Variant {
            type_name: "expr".to_string(),
            case_name: "bool".to_string(),
            tag: 4,
            payload: vec![Value::Bool(b)],
        }
    }

    pub fn nil() -> Value {
        Value::Variant {
            type_name: "expr".to_string(),
            case_name: "nil".to_string(),
            tag: 5,
            payload: vec![],
        }
    }

    pub fn cons(head: Value, tail: Value) -> Value {
        Value::Variant {
            type_name: "expr".to_string(),
            case_name: "cons".to_string(),
            tag: 6,
            payload: vec![Value::Tuple(vec![head, tail])],
        }
    }

    pub fn list(items: Vec<Value>) -> Value {
        let mut result = nil();
        for item in items.into_iter().rev() {
            result = cons(item, result);
        }
        result
    }

    pub fn err(msg: &str) -> Value {
        Value::Variant {
            type_name: "expr".to_string(),
            case_name: "err".to_string(),
            tag: 7,
            payload: vec![Value::String(msg.to_string())],
        }
    }
}

#[test]
fn sexpr_eval_simple_addition() {
    let wasm_bytes = load_rust_sexpr_package();

    let runtime = Runtime::new();
    let module = runtime
        .load_module(&wasm_bytes)
        .expect("failed to load sexpr package");
    let mut instance = module.instantiate().expect("failed to instantiate");

    // (+ 1 2 3) => 6
    let input = sexpr::list(vec![
        sexpr::sym("+"),
        sexpr::num(1),
        sexpr::num(2),
        sexpr::num(3),
    ]);

    let output = instance
        .call_with_value("evaluate", &input)
        .expect("failed to call evaluate");

    assert_eq!(output, sexpr::num(6));
}

#[test]
fn sexpr_eval_nested_arithmetic() {
    let wasm_bytes = load_rust_sexpr_package();

    let runtime = Runtime::new();
    let module = runtime
        .load_module(&wasm_bytes)
        .expect("failed to load sexpr package");
    let mut instance = module.instantiate().expect("failed to instantiate");

    // (* (+ 2 3) (- 10 4)) => 5 * 6 = 30
    let input = sexpr::list(vec![
        sexpr::sym("*"),
        sexpr::list(vec![sexpr::sym("+"), sexpr::num(2), sexpr::num(3)]),
        sexpr::list(vec![sexpr::sym("-"), sexpr::num(10), sexpr::num(4)]),
    ]);

    let output = instance
        .call_with_value("evaluate", &input)
        .expect("failed to call evaluate");

    assert_eq!(output, sexpr::num(30));
}

#[test]
fn sexpr_eval_comparison() {
    let wasm_bytes = load_rust_sexpr_package();

    let runtime = Runtime::new();
    let module = runtime
        .load_module(&wasm_bytes)
        .expect("failed to load sexpr package");
    let mut instance = module.instantiate().expect("failed to instantiate");

    // (< 5 10) => true
    let input = sexpr::list(vec![sexpr::sym("<"), sexpr::num(5), sexpr::num(10)]);

    let output = instance
        .call_with_value("evaluate", &input)
        .expect("failed to call evaluate");

    assert_eq!(output, sexpr::boolean(true));
}

#[test]
fn sexpr_eval_if_true() {
    let wasm_bytes = load_rust_sexpr_package();

    let runtime = Runtime::new();
    let module = runtime
        .load_module(&wasm_bytes)
        .expect("failed to load sexpr package");
    let mut instance = module.instantiate().expect("failed to instantiate");

    // (if (> 10 5) 42 0) => 42
    let input = sexpr::list(vec![
        sexpr::sym("if"),
        sexpr::list(vec![sexpr::sym(">"), sexpr::num(10), sexpr::num(5)]),
        sexpr::num(42),
        sexpr::num(0),
    ]);

    let output = instance
        .call_with_value("evaluate", &input)
        .expect("failed to call evaluate");

    assert_eq!(output, sexpr::num(42));
}

#[test]
fn sexpr_eval_if_false() {
    let wasm_bytes = load_rust_sexpr_package();

    let runtime = Runtime::new();
    let module = runtime
        .load_module(&wasm_bytes)
        .expect("failed to load sexpr package");
    let mut instance = module.instantiate().expect("failed to instantiate");

    // (if (< 10 5) 42 0) => 0
    let input = sexpr::list(vec![
        sexpr::sym("if"),
        sexpr::list(vec![sexpr::sym("<"), sexpr::num(10), sexpr::num(5)]),
        sexpr::num(42),
        sexpr::num(0),
    ]);

    let output = instance
        .call_with_value("evaluate", &input)
        .expect("failed to call evaluate");

    assert_eq!(output, sexpr::num(0));
}

#[test]
fn sexpr_eval_list_operations() {
    let wasm_bytes = load_rust_sexpr_package();

    let runtime = Runtime::new();
    let module = runtime
        .load_module(&wasm_bytes)
        .expect("failed to load sexpr package");
    let mut instance = module.instantiate().expect("failed to instantiate");

    // (car (list 1 2 3)) => 1
    let input = sexpr::list(vec![
        sexpr::sym("car"),
        sexpr::list(vec![
            sexpr::sym("list"),
            sexpr::num(1),
            sexpr::num(2),
            sexpr::num(3),
        ]),
    ]);

    let output = instance
        .call_with_value("evaluate", &input)
        .expect("failed to call evaluate");

    assert_eq!(output, sexpr::num(1));
}

#[test]
fn sexpr_eval_length() {
    let wasm_bytes = load_rust_sexpr_package();

    let runtime = Runtime::new();
    let module = runtime
        .load_module(&wasm_bytes)
        .expect("failed to load sexpr package");
    let mut instance = module.instantiate().expect("failed to instantiate");

    // (length (list 1 2 3 4 5)) => 5
    let input = sexpr::list(vec![
        sexpr::sym("length"),
        sexpr::list(vec![
            sexpr::sym("list"),
            sexpr::num(1),
            sexpr::num(2),
            sexpr::num(3),
            sexpr::num(4),
            sexpr::num(5),
        ]),
    ]);

    let output = instance
        .call_with_value("evaluate", &input)
        .expect("failed to call evaluate");

    assert_eq!(output, sexpr::num(5));
}

#[test]
fn sexpr_eval_complex_expression() {
    let wasm_bytes = load_rust_sexpr_package();

    let runtime = Runtime::new();
    let module = runtime
        .load_module(&wasm_bytes)
        .expect("failed to load sexpr package");
    let mut instance = module.instantiate().expect("failed to instantiate");

    // (if (and (> 10 5) (< 3 7))
    //     (+ (* 2 3) (/ 10 2))
    //     0)
    // => (6 + 5) = 11
    let input = sexpr::list(vec![
        sexpr::sym("if"),
        sexpr::list(vec![
            sexpr::sym("and"),
            sexpr::list(vec![sexpr::sym(">"), sexpr::num(10), sexpr::num(5)]),
            sexpr::list(vec![sexpr::sym("<"), sexpr::num(3), sexpr::num(7)]),
        ]),
        sexpr::list(vec![
            sexpr::sym("+"),
            sexpr::list(vec![sexpr::sym("*"), sexpr::num(2), sexpr::num(3)]),
            sexpr::list(vec![sexpr::sym("/"), sexpr::num(10), sexpr::num(2)]),
        ]),
        sexpr::num(0),
    ]);

    let output = instance
        .call_with_value("evaluate", &input)
        .expect("failed to call evaluate");

    assert_eq!(output, sexpr::num(11));
}