polyplugc 0.1.1

CLI code generator for polyplug - generates type-safe bindings for multiple languages
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
#![allow(clippy::expect_used)]

use polyplug_codegen::{GenerateConfig, Lang, Side};
use polyplugc::generate;
use std::path::Path;
use std::path::PathBuf;

fn create_test_api_with_host_contracts(tmp_dir: &Path) -> PathBuf {
    std::fs::create_dir_all(tmp_dir).expect("create tmp_dir");
    let api_toml_path: PathBuf = tmp_dir.join("test_host_contract_api.toml");
    let content: &str = r#"# Test API with host contracts
[[plugin_contract]]
name = "example.worker"
version = "1.0.0"

[[plugin_contract.functions]]
name = "do_work"
params = [{ name = "input", type = "StringView" }]
return = "StringView"

[[host_contract]]
name = "host.logger"
version = "1.0.0"

[[host_contract.functions]]
name = "log"
params = [{ name = "message", type = "StringView" }]
returns = "void"
"#;
    std::fs::write(&api_toml_path, content).expect("failed to write test api.toml");
    api_toml_path
}

#[test]
fn test_rust_host_contract_generates_host_contracts_file() {
    let tmp_dir: PathBuf =
        PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("test_rust_host_contract");
    let api_toml: PathBuf = create_test_api_with_host_contracts(&tmp_dir);

    let config = GenerateConfig {
        api_toml: api_toml.clone(),
        lang: Lang::Rust,
        side: Side::Host,
        out_dir: tmp_dir.clone(),
    };

    let output = generate(config).expect("polyplugc::generate failed");

    for file in &output.files {
        let file_path = tmp_dir.join(&file.path);
        if let Some(parent) = file_path.parent() {
            std::fs::create_dir_all(parent).expect("failed to create parent dir");
        }
        std::fs::write(&file_path, &file.content).expect("failed to write generated file");
    }

    let host_contracts_path: PathBuf = tmp_dir.join("host").join("host_contracts.rs");
    assert!(
        host_contracts_path.exists(),
        "host/host_contracts.rs must exist"
    );

    let content: String =
        std::fs::read_to_string(&host_contracts_path).expect("read host_contracts.rs");

    assert!(
        content.contains("trait HostLogger"),
        "must contain trait HostLogger"
    );
    assert!(content.contains("fn log"), "must contain fn log");
    assert!(
        content.contains("HOSTLOGGER_CONTRACT_ID"),
        "must contain contract ID"
    );

    println!("test_rust_host_contract_generates_host_contracts_file: passed ✓");
}

#[test]
fn test_rust_host_contract_guest_generates_caller() {
    let tmp_dir: PathBuf =
        PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("test_rust_host_contract_guest");
    let api_toml: PathBuf = create_test_api_with_host_contracts(&tmp_dir);

    let config = GenerateConfig {
        api_toml: api_toml.clone(),
        lang: Lang::Rust,
        side: Side::Guest,
        out_dir: tmp_dir.clone(),
    };

    let output = generate(config).expect("polyplugc::generate failed");

    for file in &output.files {
        let file_path = tmp_dir.join(&file.path);
        if let Some(parent) = file_path.parent() {
            std::fs::create_dir_all(parent).expect("failed to create parent dir");
        }
        std::fs::write(&file_path, &file.content).expect("failed to write generated file");
    }

    let caller_path: PathBuf = tmp_dir.join("guest").join("host_contract_callers.rs");
    assert!(
        caller_path.exists(),
        "guest/host_contract_callers.rs must exist"
    );

    let content: String =
        std::fs::read_to_string(&caller_path).expect("read host_contract_callers.rs");

    assert!(
        content.contains("struct HostLoggerCaller"),
        "must contain HostLoggerCaller"
    );
    assert!(content.contains("from_host"), "must contain from_host");
    assert!(content.contains("is_valid"), "must contain is_valid");

    println!("test_rust_host_contract_guest_generates_caller: passed ✓");
}

#[test]
fn test_cpp_host_contract_generates_host_contracts_file() {
    let tmp_dir: PathBuf =
        PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("test_cpp_host_contract");
    let api_toml: PathBuf = create_test_api_with_host_contracts(&tmp_dir);

    let config = GenerateConfig {
        api_toml: api_toml.clone(),
        lang: Lang::Cpp,
        side: Side::Host,
        out_dir: tmp_dir.clone(),
    };

    let output = generate(config).expect("polyplugc::generate failed");

    for file in &output.files {
        let file_path = tmp_dir.join(&file.path);
        if let Some(parent) = file_path.parent() {
            std::fs::create_dir_all(parent).expect("failed to create parent dir");
        }
        std::fs::write(&file_path, &file.content).expect("failed to write generated file");
    }

    let host_contracts_path: PathBuf = tmp_dir.join("host").join("host_contracts.hpp");
    assert!(
        host_contracts_path.exists(),
        "host/host_contracts.hpp must exist"
    );

    let content: String =
        std::fs::read_to_string(&host_contracts_path).expect("read host_contracts.hpp");

    assert!(
        content.contains("class HostLogger"),
        "must contain class HostLogger"
    );
    assert!(content.contains("virtual"), "must contain virtual method");
    assert!(
        content.contains("HOSTLOGGER_CONTRACT_ID"),
        "must contain contract ID"
    );

    println!("test_cpp_host_contract_generates_host_contracts_file: passed ✓");
}

#[test]
fn test_cpp_host_contract_guest_generates_caller() {
    let tmp_dir: PathBuf =
        PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("test_cpp_host_contract_guest");
    let api_toml: PathBuf = create_test_api_with_host_contracts(&tmp_dir);

    let config = GenerateConfig {
        api_toml: api_toml.clone(),
        lang: Lang::Cpp,
        side: Side::Guest,
        out_dir: tmp_dir.clone(),
    };

    let output = generate(config).expect("polyplugc::generate failed");

    for file in &output.files {
        let file_path = tmp_dir.join(&file.path);
        if let Some(parent) = file_path.parent() {
            std::fs::create_dir_all(parent).expect("failed to create parent dir");
        }
        std::fs::write(&file_path, &file.content).expect("failed to write generated file");
    }

    let caller_path: PathBuf = tmp_dir.join("guest").join("host_contracts.hpp");
    assert!(caller_path.exists(), "guest/host_contracts.hpp must exist");

    let content: String =
        std::fs::read_to_string(&caller_path).expect("read guest/host_contracts.hpp");

    assert!(
        content.contains("HostLoggerContract"),
        "must contain HostLoggerContract"
    );
    assert!(content.contains("from_host"), "must contain from_host");
    assert!(content.contains("is_valid"), "must contain is_valid");

    println!("test_cpp_host_contract_guest_generates_caller: passed ✓");
}

#[test]
fn test_csharp_host_contract_generates_contracts_file() {
    let tmp_dir: PathBuf =
        PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("test_csharp_host_contract");
    let api_toml: PathBuf = create_test_api_with_host_contracts(&tmp_dir);

    let config = GenerateConfig {
        api_toml: api_toml.clone(),
        lang: Lang::CSharp,
        side: Side::Host,
        out_dir: tmp_dir.clone(),
    };

    let output = generate(config).expect("polyplugc::generate failed");

    for file in &output.files {
        let file_path = tmp_dir.join(&file.path);
        if let Some(parent) = file_path.parent() {
            std::fs::create_dir_all(parent).expect("failed to create parent dir");
        }
        std::fs::write(&file_path, &file.content).expect("failed to write generated file");
    }

    let contracts_path: PathBuf = tmp_dir.join("host").join("Contracts.cs");
    assert!(contracts_path.exists(), "host/Contracts.cs must exist");

    let content: String = std::fs::read_to_string(&contracts_path).expect("read Contracts.cs");

    assert!(
        content.contains("interface IHostLogger"),
        "must contain IHostLogger"
    );
    assert!(content.contains("void Log"), "must contain Log method");
    assert!(
        content.contains("HOSTLOGGER_CONTRACT_ID"),
        "must contain contract ID"
    );

    println!("test_csharp_host_contract_generates_contracts_file: passed ✓");
}

#[test]
fn test_csharp_host_contract_guest_generates_caller() {
    let tmp_dir: PathBuf =
        PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("test_csharp_host_contract_guest");
    let api_toml: PathBuf = create_test_api_with_host_contracts(&tmp_dir);

    let config = GenerateConfig {
        api_toml: api_toml.clone(),
        lang: Lang::CSharp,
        side: Side::Guest,
        out_dir: tmp_dir.clone(),
    };

    let output = generate(config).expect("polyplugc::generate failed");

    for file in &output.files {
        let file_path = tmp_dir.join(&file.path);
        if let Some(parent) = file_path.parent() {
            std::fs::create_dir_all(parent).expect("failed to create parent dir");
        }
        std::fs::write(&file_path, &file.content).expect("failed to write generated file");
    }

    let caller_path: PathBuf = tmp_dir.join("guest").join("HostContracts.cs");
    assert!(caller_path.exists(), "guest/HostContracts.cs must exist");

    let content: String =
        std::fs::read_to_string(&caller_path).expect("read guest/HostContracts.cs");

    assert!(content.contains("HostLogger"), "must contain HostLogger");
    assert!(content.contains("FromHost"), "must contain FromHost");
    assert!(content.contains("IsValid"), "must contain IsValid");

    println!("test_csharp_host_contract_guest_generates_caller: passed ✓");
}

/// Generate the full C# host side once and return (Callers.cs, InterfaceFactories.cs).
fn generate_csharp_host_side(tmp_dir: &Path) -> (String, String) {
    let api_toml: PathBuf = create_test_api_with_host_contracts(tmp_dir);
    let config = GenerateConfig {
        api_toml,
        lang: Lang::CSharp,
        side: Side::Host,
        out_dir: tmp_dir.to_path_buf(),
    };
    let output = generate(config).expect("polyplugc::generate failed");
    for file in &output.files {
        let file_path = tmp_dir.join(&file.path);
        if let Some(parent) = file_path.parent() {
            std::fs::create_dir_all(parent).expect("failed to create parent dir");
        }
        std::fs::write(&file_path, &file.content).expect("failed to write generated file");
    }
    let callers: String =
        std::fs::read_to_string(tmp_dir.join("host").join("Callers.cs")).expect("read Callers.cs");
    let factories: String =
        std::fs::read_to_string(tmp_dir.join("host").join("InterfaceFactories.cs"))
            .expect("read InterfaceFactories.cs");
    (callers, factories)
}

/// The host-caller path (host/Callers.cs) must use the real Runtime + ABI APIs:
/// a one-argument `Create(Runtime rt)` factory, `ResolveGuestContract` (not the
/// phantom `ResolveContract`), an `unsafe` class for its pointer fields, and it
/// must NOT reject a null instance handle (valid for stateless contracts).
#[test]
fn test_csharp_host_callers_use_real_runtime_api() {
    let tmp_dir: PathBuf =
        PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("test_csharp_host_callers_api");
    let (callers, _factories): (String, String) = generate_csharp_host_side(&tmp_dir);

    assert!(
        callers.contains("public static ExampleWorkerContractCaller? Create(Runtime rt) {"),
        "Callers.cs must emit a one-arg Create(Runtime rt) factory: {callers}"
    );
    assert!(
        callers.contains("rt.ResolveGuestContract(handle)"),
        "Callers.cs must call the real Runtime.ResolveGuestContract: {callers}"
    );
    assert!(
        !callers.contains("ResolveContract(handle)"),
        "Callers.cs must NOT call the phantom ResolveContract: {callers}"
    );
    assert!(
        callers.contains("public sealed unsafe class ExampleWorkerContractCaller"),
        "the caller class must be `unsafe` to hold pointer fields: {callers}"
    );
    assert!(
        callers.contains("(HostApi*)rt.HostHandle"),
        "Create must derive the HostApi pointer from Runtime.HostHandle: {callers}"
    );
    assert!(
        !callers.contains("if (inst.Data == nint.Zero) { return null; }"),
        "a null instance handle is valid for stateless contracts and must not abort Create: {callers}"
    );
    // create_guest_instance / destroy_guest_instance are IntPtr fields on HostApi
    // and must be cast to function pointers before invocation. The instance
    // lifecycle is host-mediated so the runtime tracks every live instance.
    assert!(
        callers.contains("(delegate* unmanaged[Cdecl]<HostApi*, GuestContractInterface*, void*, GuestContractInstance*, void>)host->CreateGuestInstance"),
        "Create must cast the IntPtr CreateGuestInstance field to a function pointer (out-param: writes through GuestContractInstance*): {callers}"
    );

    println!("test_csharp_host_callers_use_real_runtime_api: passed ✓");
}

/// The interface-factory path (host/InterfaceFactories.cs) must build the real
/// ABI structs and never reference the phantom VTable type names.
#[test]
fn test_csharp_interface_factories_use_real_abi_types() {
    let tmp_dir: PathBuf =
        PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("test_csharp_factory_abi");
    let (_callers, factories): (String, String) = generate_csharp_host_side(&tmp_dir);

    assert!(
        factories
            .contains("public static unsafe HostContractInterface CreateHostLoggerInterface<T>"),
        "factory must return the canonical HostContractInterface: {factories}"
    );
    assert!(
        factories.contains("new NativeDispatch {"),
        "factory must build a NativeDispatch: {factories}"
    );
    assert!(
        factories.contains("new VmDispatch {"),
        "VM factory must build a VmDispatch: {factories}"
    );
    for phantom in [
        "HostContractVTable",
        "HostContractVTableHeader",
        "NativeHostContractDispatch",
        "VmHostContractDispatchFn",
        "HostContractDispatch",
    ] {
        assert!(
            !factories.contains(phantom),
            "InterfaceFactories.cs must not reference phantom type `{phantom}`: {factories}"
        );
    }

    println!("test_csharp_interface_factories_use_real_abi_types: passed ✓");
}

/// Generate the C# guest side once and return the guest host-contract caller
/// file (guest/HostContracts.cs).
fn generate_csharp_guest_host_contracts(tmp_dir: &Path) -> String {
    let api_toml: PathBuf = create_test_api_with_host_contracts(tmp_dir);
    let config = GenerateConfig {
        api_toml,
        lang: Lang::CSharp,
        side: Side::Guest,
        out_dir: tmp_dir.to_path_buf(),
    };
    let output = generate(config).expect("polyplugc::generate failed");
    for file in &output.files {
        let file_path = tmp_dir.join(&file.path);
        if let Some(parent) = file_path.parent() {
            std::fs::create_dir_all(parent).expect("failed to create parent dir");
        }
        std::fs::write(&file_path, &file.content).expect("failed to write generated file");
    }
    std::fs::read_to_string(tmp_dir.join("guest").join("HostContracts.cs"))
        .expect("read guest/HostContracts.cs")
}

/// The guest-caller path (guest/HostContracts.cs) must resolve host contracts
/// through the real HostApi ABI: `GetHostContract` for the instance and
/// `ResolveHostContractInterface` for the interface, then dispatch via the flat
/// `HostContractInterface` (DispatchType + Dispatch.Native / Dispatch.Vm). It
/// must never reference the phantom VTable / header types that the old emitter
/// produced.
#[test]
fn test_csharp_guest_host_contract_callers_use_real_abi_types() {
    let tmp_dir: PathBuf =
        PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("test_csharp_guest_caller_abi");
    let callers: String = generate_csharp_guest_host_contracts(&tmp_dir);

    // Real ABI mechanisms must be present.
    assert!(
        callers.contains("HostContractInterface*"),
        "guest caller must cast the interface to the canonical HostContractInterface*: {callers}"
    );
    assert!(
        callers.contains("GetHostContract"),
        "guest caller must obtain the instance via GetHostContract: {callers}"
    );
    assert!(
        callers.contains("ResolveHostContractInterface"),
        "guest caller must resolve the interface via ResolveHostContractInterface: {callers}"
    );
    assert!(
        callers.contains("contract->DispatchType"),
        "guest caller must branch on the real DispatchType field: {callers}"
    );
    assert!(
        callers.contains("contract->Dispatch.Native.Functions")
            && callers.contains("contract->Dispatch.Native.FunctionCount"),
        "guest caller must read the flat Dispatch.Native fields: {callers}"
    );
    assert!(
        callers.contains("contract->Dispatch.Vm.Call")
            && callers.contains("contract->Dispatch.Vm.LoaderData"),
        "guest caller must read the flat Dispatch.Vm fields: {callers}"
    );
    assert!(
        callers.contains("err.Code != (uint)AbiErrorCode.Ok"),
        "guest caller must check the AbiError code via the AbiErrorCode enum: {callers}"
    );

    // Phantom types from the old emitter must NOT appear.
    for phantom in [
        "HostContractVTable",
        "header->Header",
        "Dispatch.VM.Call",
        "Dispatch.VM.BridgeData",
        "BridgeData",
    ] {
        assert!(
            !callers.contains(phantom),
            "guest/HostContracts.cs must not reference phantom `{phantom}`: {callers}"
        );
    }

    println!("test_csharp_guest_host_contract_callers_use_real_abi_types: passed ✓");
}

#[test]
fn test_python_host_contract_generates_contracts_file() {
    let tmp_dir: PathBuf =
        PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("test_python_host_contract");
    let api_toml: PathBuf = create_test_api_with_host_contracts(&tmp_dir);

    let config = GenerateConfig {
        api_toml: api_toml.clone(),
        lang: Lang::Python,
        side: Side::Host,
        out_dir: tmp_dir.clone(),
    };

    let output = generate(config).expect("polyplugc::generate failed");

    for file in &output.files {
        let file_path = tmp_dir.join(&file.path);
        if let Some(parent) = file_path.parent() {
            std::fs::create_dir_all(parent).expect("failed to create parent dir");
        }
        std::fs::write(&file_path, &file.content).expect("failed to write generated file");
    }

    let contracts_path: PathBuf = tmp_dir.join("host").join("contracts.py");
    assert!(contracts_path.exists(), "host/contracts.py must exist");

    let content: String = std::fs::read_to_string(&contracts_path).expect("read contracts.py");

    assert!(
        content.contains("class HostLogger"),
        "must contain HostLogger"
    );
    assert!(content.contains("ABC"), "must contain ABC");
    assert!(content.contains("def log"), "must contain log method");
    assert!(
        content.contains("HOSTLOGGER_CONTRACT_ID"),
        "must contain contract ID"
    );

    println!("test_python_host_contract_generates_contracts_file: passed ✓");
}

#[test]
fn test_python_host_contract_guest_generates_caller() {
    let tmp_dir: PathBuf =
        PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("test_python_host_contract_guest");
    let api_toml: PathBuf = create_test_api_with_host_contracts(&tmp_dir);

    let config = GenerateConfig {
        api_toml: api_toml.clone(),
        lang: Lang::Python,
        side: Side::Guest,
        out_dir: tmp_dir.clone(),
    };

    let output = generate(config).expect("polyplugc::generate failed");

    for file in &output.files {
        let file_path = tmp_dir.join(&file.path);
        if let Some(parent) = file_path.parent() {
            std::fs::create_dir_all(parent).expect("failed to create parent dir");
        }
        std::fs::write(&file_path, &file.content).expect("failed to write generated file");
    }

    let caller_path: PathBuf = tmp_dir.join("guest").join("host_contracts.py");
    assert!(caller_path.exists(), "guest/host_contracts.py must exist");

    let content: String =
        std::fs::read_to_string(&caller_path).expect("read guest/host_contracts.py");

    assert!(
        content.contains("HostLoggerContract"),
        "must contain HostLoggerContract"
    );
    assert!(content.contains("from_host"), "must contain from_host");
    assert!(content.contains("is_valid"), "must contain is_valid");

    println!("test_python_host_contract_guest_generates_caller: passed ✓");
}

#[test]
fn test_python_host_caller_branches_on_dispatch_type() {
    // Defect (b): the Python host-side caller (a Python host calling INTO a guest
    // contract) must branch on dispatch_type. VM-dispatched guests (Lua/JS) must be
    // called through the union's vm.call member with the canonical 6-arg signature,
    // not mis-read as dispatch.native.
    let tmp_dir: PathBuf =
        PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("test_python_host_caller_dispatch");
    let api_toml: PathBuf = create_test_api_with_host_contracts(&tmp_dir);

    let config = GenerateConfig {
        api_toml: api_toml.clone(),
        lang: Lang::Python,
        side: Side::Host,
        out_dir: tmp_dir.clone(),
    };

    let output = generate(config).expect("polyplugc::generate failed");

    for file in &output.files {
        let file_path = tmp_dir.join(&file.path);
        if let Some(parent) = file_path.parent() {
            std::fs::create_dir_all(parent).expect("failed to create parent dir");
        }
        std::fs::write(&file_path, &file.content).expect("failed to write generated file");
    }

    let callers_path: PathBuf = tmp_dir.join("host").join("callers.py");
    assert!(callers_path.exists(), "host/callers.py must exist");

    let content: String = std::fs::read_to_string(&callers_path).expect("read host/callers.py");

    // DispatchType must be imported and the caller must branch on it.
    assert!(
        content.contains("DispatchType"),
        "host caller must import/use DispatchType"
    );
    assert!(
        content.contains("if interface.dispatch_type == DispatchType.Native:"),
        "host caller must branch on dispatch_type"
    );
    // VM path: 6-arg call(loader_data, instance, fn_id, args, out, arena). The
    // test contract's `do_work` returns a StringView (arena-backed), so the host
    // caller resets and hands the guest this caller's per-call arena. Scalar-only
    // functions would instead pass None (the host->alloc fallback) — see
    // arena_parity.rs for the scalar-vs-arena split.
    assert!(
        content.contains(
            "interface.dispatch.vm.call(interface.dispatch.vm.loader_data, self._instance,"
        ),
        "VM dispatch must use the canonical 7-arg out-param call shape"
    );
    assert!(
        content.contains(", args_ptr, out_ptr, ctypes.byref(self._arena), ctypes.byref(err))"),
        "arena-backed VM dispatch must hand the guest the per-call arena then the AbiError out-param"
    );

    println!("test_python_host_caller_branches_on_dispatch_type: passed ✓");
}

#[test]
fn test_lua_host_contract_generates_contracts_file() {
    let tmp_dir: PathBuf =
        PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("test_lua_host_contract");
    let api_toml: PathBuf = create_test_api_with_host_contracts(&tmp_dir);

    let config = GenerateConfig {
        api_toml: api_toml.clone(),
        lang: Lang::Lua,
        side: Side::Host,
        out_dir: tmp_dir.clone(),
    };

    let output = generate(config).expect("polyplugc::generate failed");

    for file in &output.files {
        let file_path = tmp_dir.join(&file.path);
        if let Some(parent) = file_path.parent() {
            std::fs::create_dir_all(parent).expect("failed to create parent dir");
        }
        std::fs::write(&file_path, &file.content).expect("failed to write generated file");
    }

    let contracts_path: PathBuf = tmp_dir.join("host").join("contracts.lua");
    assert!(contracts_path.exists(), "host/contracts.lua must exist");

    let content: String = std::fs::read_to_string(&contracts_path).expect("read contracts.lua");

    assert!(content.contains("HostLogger"), "must contain HostLogger");
    assert!(
        content.contains("function HostLogger:log"),
        "must contain log method"
    );
    assert!(
        content.contains("HOSTLOGGER_CONTRACT_ID"),
        "must contain contract ID"
    );

    println!("test_lua_host_contract_generates_contracts_file: passed ✓");
}

#[test]
fn test_lua_host_contract_guest_generates_caller() {
    let tmp_dir: PathBuf =
        PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("test_lua_host_contract_guest");
    let api_toml: PathBuf = create_test_api_with_host_contracts(&tmp_dir);

    let config = GenerateConfig {
        api_toml: api_toml.clone(),
        lang: Lang::Lua,
        side: Side::Guest,
        out_dir: tmp_dir.clone(),
    };

    let output = generate(config).expect("polyplugc::generate failed");

    for file in &output.files {
        let file_path = tmp_dir.join(&file.path);
        if let Some(parent) = file_path.parent() {
            std::fs::create_dir_all(parent).expect("failed to create parent dir");
        }
        std::fs::write(&file_path, &file.content).expect("failed to write generated file");
    }

    let caller_path: PathBuf = tmp_dir.join("guest").join("host_contracts.lua");
    assert!(caller_path.exists(), "guest/host_contracts.lua must exist");

    let content: String =
        std::fs::read_to_string(&caller_path).expect("read guest/host_contracts.lua");

    assert!(
        content.contains("HostLoggerContract"),
        "must contain HostLoggerContract"
    );
    assert!(content.contains("from_host"), "must contain from_host");
    assert!(content.contains("is_valid"), "must contain is_valid");

    // Defect (a): the caller must require the polyplug_abi Lua SDK so every cdef it
    // casts to (HostContractInterface / AbiError / GuestContractInstance) is declared.
    assert!(
        content.contains("require(\"polyplug_abi\")"),
        "guest host-contract caller must require polyplug_abi for its cdefs"
    );
    // It must cast to the canonical flat HostContractInterface, NOT the dead
    // HostContractVTable type that is defined nowhere in the ABI.
    assert!(
        content.contains("ffi.cast(\"HostContractInterface*\""),
        "must cast to the canonical HostContractInterface"
    );
    assert!(
        !content.contains("HostContractVTable"),
        "must NOT reference the nonexistent HostContractVTable type"
    );
    // No `.header.` indirection: the ABI struct is flat (dispatch_type / dispatch
    // live directly on HostContractInterface).
    assert!(
        !content.contains(".header."),
        "must not read through a nonexistent .header field"
    );
    // VM dispatch must use the canonical 7-arg out-param call with loader_data,
    // a nil arena, and the trailing AbiError out-param.
    assert!(
        content.contains("interface.dispatch.vm.call(interface.dispatch.vm.loader_data,")
            && content.contains(", args_ptr, out_ptr, nil, err)"),
        "VM dispatch must use the 7-arg call(loader_data, instance, fn_id, args, out, nil, err)"
    );
    assert!(
        !content.contains("bridge_data"),
        "must use loader_data, not the nonexistent bridge_data field"
    );

    println!("test_lua_host_contract_guest_generates_caller: passed ✓");
}

#[test]
fn test_js_quickjs_host_contract_generates_contracts_file() {
    let tmp_dir: PathBuf =
        PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("test_js_quickjs_host_contract");
    let api_toml: PathBuf = create_test_api_with_host_contracts(&tmp_dir);

    let config = GenerateConfig {
        api_toml: api_toml.clone(),
        lang: Lang::JsQuickJs,
        side: Side::Host,
        out_dir: tmp_dir.clone(),
    };

    let output = generate(config).expect("polyplugc::generate failed");

    for file in &output.files {
        let file_path = tmp_dir.join(&file.path);
        if let Some(parent) = file_path.parent() {
            std::fs::create_dir_all(parent).expect("failed to create parent dir");
        }
        std::fs::write(&file_path, &file.content).expect("failed to write generated file");
    }

    let contracts_path: PathBuf = tmp_dir.join("host").join("contracts.ts");
    assert!(contracts_path.exists(), "host/contracts.ts must exist");

    let content: String = std::fs::read_to_string(&contracts_path).expect("read contracts.ts");

    assert!(
        content.contains("interface HostLogger"),
        "must contain HostLogger interface"
    );
    assert!(content.contains("Log"), "must contain Log method");
    assert!(
        content.contains("HOSTLOGGER_CONTRACT_ID"),
        "must contain contract ID"
    );

    println!("test_js_quickjs_host_contract_generates_contracts_file: passed ✓");
}

#[test]
fn test_js_quickjs_host_contract_guest_generates_caller() {
    let tmp_dir: PathBuf =
        PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("test_js_quickjs_host_contract_guest");
    let api_toml: PathBuf = create_test_api_with_host_contracts(&tmp_dir);

    let config = GenerateConfig {
        api_toml: api_toml.clone(),
        lang: Lang::JsQuickJs,
        side: Side::Guest,
        out_dir: tmp_dir.clone(),
    };

    let output = generate(config).expect("polyplugc::generate failed");

    for file in &output.files {
        let file_path = tmp_dir.join(&file.path);
        if let Some(parent) = file_path.parent() {
            std::fs::create_dir_all(parent).expect("failed to create parent dir");
        }
        std::fs::write(&file_path, &file.content).expect("failed to write generated file");
    }

    let caller_path: PathBuf = tmp_dir.join("guest").join("host_contracts.ts");
    assert!(caller_path.exists(), "guest/host_contracts.ts must exist");

    let content: String =
        std::fs::read_to_string(&caller_path).expect("read guest/host_contracts.ts");

    assert!(
        content.contains("HostLoggerContract"),
        "must contain HostLoggerContract"
    );
    assert!(content.contains("fromHost"), "must contain fromHost");
    assert!(content.contains("isValid"), "must contain isValid");

    // Dispatch must go through the new callHostContract bridge primitive (resolves
    // and dispatches internally — no vtable header reading or split dispatch paths).
    assert!(
        content.contains("polyplug.callHostContract("),
        "must use callHostContract bridge primitive"
    );
    // The old split-dispatch machinery must NOT be present.
    assert!(
        !content.contains("readHostContractHeader"),
        "must not use readHostContractHeader"
    );
    assert!(
        !content.contains("callVmDispatch"),
        "must not use callVmDispatch"
    );
    assert!(
        !content.contains("callDispatchFn"),
        "must not use callDispatchFn"
    );
    // Caller arg/out buffers must use the host-allocator shim (_callerAlloc) and be
    // explicitly freed — the caller has no per-call arena, so it cannot use the
    // threaded arenaAlloc (Rule 12).
    assert!(
        content.contains("const _callerAlloc = (sz: number): number[] =>"),
        "must use the _callerAlloc host-allocator shim for caller buffers"
    );
    assert!(
        content.contains("for (const _f of _frees) { polyplug.free("),
        "must explicitly free caller buffers in a finally block"
    );
    // The bridge is threaded in, not read from a global (Rule 12).
    assert!(
        !content.contains("(globalThis as any).polyplug"),
        "host-contract caller must not read a global bridge"
    );

    println!("test_js_quickjs_host_contract_guest_generates_caller: passed ✓");
}