alef-backend-zig 0.15.26

Zig backend for alef
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
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
//! Zig trait-bridge code generation.
//!
//! Emits one Zig extern struct (vtable) and one registration wrapper function
//! per configured `[[trait_bridges]]` entry.  The Zig consumer fills in the
//! struct with `callconv(.C)` function pointers and calls `register_*`.
//!
//! # C symbol convention
//!
//! The generated `register_{trait_snake}` shim calls
//! `c.{prefix}_register_{trait_snake}` — the symbol exposed by the
//! `kreuzberg-ffi` C layer (pattern: `{crate_prefix}_register_{trait_snake}`).
//! If the actual symbol differs, override the generated call site.
//!
//! # `TraitBridgeGenerator` implementation
//!
//! [`ZigTraitBridgeGenerator`] implements the shared [`TraitBridgeGenerator`]
//! trait so that the shared codegen driver can invoke the Zig-specific
//! `gen_unregistration_fn` and `gen_clear_fn` overrides.  The other required
//! methods are stubs — Zig code is produced through the standalone
//! [`emit_trait_bridge`] free function, not the shared driver.

use alef_codegen::generators::trait_bridge::{TraitBridgeGenerator, TraitBridgeSpec};
use alef_core::config::TraitBridgeConfig;
use alef_core::ir::{MethodDef, TypeDef, TypeRef};
use heck::ToSnakeCase;

/// Zig type string to use for a vtable slot parameter or return type.
///
/// All string/complex types collapse to `[*c]const u8` (C string pointer) since
/// the vtable slots use the raw C ABI — not the Zig-friendly wrapper layer.
fn vtable_param_type(ty: &TypeRef) -> &'static str {
    match ty {
        TypeRef::Primitive(p) => {
            use alef_core::ir::PrimitiveType::*;
            match p {
                Bool => "i32",
                U8 => "u8",
                U16 => "u16",
                U32 => "u32",
                U64 => "u64",
                I8 => "i8",
                I16 => "i16",
                I32 => "i32",
                I64 => "i64",
                F32 => "f32",
                F64 => "f64",
                Usize => "usize",
                Isize => "isize",
            }
        }
        TypeRef::Unit => "void",
        TypeRef::Duration => "i64",
        // All string/path/complex types become C string pointers at the C ABI boundary.
        _ => "[*c]const u8",
    }
}

/// Zig return type for a vtable slot.
///
/// Fallible methods always return `i32` (0 = success, non-zero = error).
/// Unit infallible methods return `void`.  Other infallible returns use the
/// primitive mapping.
fn vtable_return_type(method: &MethodDef) -> String {
    if method.error_type.is_some() {
        "i32".to_string()
    } else {
        vtable_param_type(&method.return_type).to_string()
    }
}

/// Build a snake_case trait name from a PascalCase trait name.
///
/// Uses `heck::ToSnakeCase`, matching the pattern used by Go/C# backends.
fn trait_snake(trait_name: &str) -> String {
    trait_name.to_snake_case()
}

/// Emit a Zig param name for the C-ABI slot, expanding `Bytes` to ptr+len.
///
/// Returns a list of `(c_param_name, c_param_type)` pairs.
fn vtable_c_params(method: &MethodDef) -> Vec<(String, String)> {
    let mut params = vec![("ud".to_string(), "?*anyopaque".to_string())];
    for p in &method.params {
        if matches!(p.ty, TypeRef::Bytes) {
            params.push((format!("{}_ptr", p.name), "[*c]const u8".to_string()));
            params.push((format!("{}_len", p.name), "usize".to_string()));
        } else {
            params.push((p.name.clone(), vtable_param_type(&p.ty).to_string()));
        }
    }
    if method.error_type.is_some() {
        if !matches!(method.return_type, TypeRef::Unit) {
            params.push(("out_result".to_string(), "?*?[*c]u8".to_string()));
        }
        params.push(("out_error".to_string(), "?*?[*c]u8".to_string()));
    } else if !matches!(method.return_type, TypeRef::Unit) {
        params.push(("out_result".to_string(), "?*?[*c]u8".to_string()));
    }
    params
}

/// Emit a `make_{trait_snake}_vtable(comptime T: type, instance: *T) I{Trait}` helper.
///
/// The helper builds `callconv(.C)` thunks for every vtable slot so the consumer
/// only needs to write plain Zig methods on their type.
///
/// # Limitations
///
/// - Methods returning non-unit values through `out_result` use `unreachable` for
///   the conversion path when the type cannot be expressed as a direct C primitive
///   (complex types are documented as requiring manual implementation).
/// - Lifecycle slots (`name_fn`, `version_fn`, `initialize_fn`, `shutdown_fn`) are
///   emitted with `unreachable` bodies as stubs — the consumer overrides the
///   relevant field in the returned vtable if needed.
pub fn emit_make_vtable(trait_name: &str, has_super_trait: bool, trait_def: &TypeDef, out: &mut String) {
    let snake = trait_snake(trait_name);

    out.push_str(&crate::template_env::render(
        "vtable_header_doc.jinja",
        minijinja::context! {
            trait_name => trait_name,
            snake => &snake,
        },
    ));
    out.push_str(&crate::template_env::render(
        "vtable_impl_method.jinja",
        minijinja::context! {
            snake => &snake,
            trait_name => trait_name,
        },
    ));
    out.push_str(&crate::template_env::render(
        "vtable_make_fn_header.jinja",
        minijinja::context! {
            trait_name => trait_name,
        },
    ));

    // Lifecycle stubs when super_trait is present
    if has_super_trait {
        out.push_str(&crate::template_env::render(
            "vtable_field_name_fn.jinja",
            minijinja::context! {},
        ));
        out.push_str(&crate::template_env::render(
            "vtable_field_version_fn.jinja",
            minijinja::context! {},
        ));
        out.push_str(&crate::template_env::render(
            "vtable_field_initialize_fn.jinja",
            minijinja::context! {},
        ));
        out.push_str(&crate::template_env::render(
            "vtable_field_shutdown_fn.jinja",
            minijinja::context! {},
        ));
    }

    // Per-method thunks
    for method in &trait_def.methods {
        let method_snake = method.name.to_snake_case();
        let c_params = vtable_c_params(method);
        let ret = vtable_return_type(method);

        // Build the thunk parameter list string
        let params_str = c_params
            .iter()
            .map(|(name, ty)| format!("{name}: {ty}"))
            .collect::<Vec<_>>()
            .join(", ");

        out.push_str(&crate::template_env::render(
            "vtable_instance_field.jinja",
            minijinja::context! {
                method_snake => &method_snake,
                params_str => &params_str,
                ret => &ret,
            },
        ));

        // Cast user_data to *T
        out.push_str("                const self: *T = @ptrCast(@alignCast(ud));\n");

        // Reconstruct Bytes slices and build forwarding arg list
        let mut call_args: Vec<String> = Vec::new();
        for p in &method.params {
            if matches!(p.ty, TypeRef::Bytes) {
                out.push_str(&crate::template_env::render(
                    "thunk_bytes_slice.jinja",
                    minijinja::context! {
                        slice_name => format!("{}_slice", p.name),
                        ptr_name => format!("{}_ptr", p.name),
                        len_name => format!("{}_len", p.name),
                    },
                ));
                call_args.push(format!("{}_slice", p.name));
            } else {
                call_args.push(p.name.clone());
            }
        }

        let args_str = call_args.join(", ");

        // Pick a capture name for the success branch that won't collide with method
        // params. Methods can have a param literally called `result`; using that as
        // the unwrap binding shadows the outer scope (zig 0.16+ flags this).
        let ok_binding = if method.params.iter().any(|p| p.name == "value") {
            "ok_value"
        } else {
            "value"
        };

        if method.error_type.is_some() {
            // Fallible method: call returns error union, write out_result/out_error
            let has_result_out = !matches!(method.return_type, TypeRef::Unit);
            out.push_str(&crate::template_env::render(
                "thunk_fn_signature.jinja",
                minijinja::context! {
                    method_snake => &method_snake,
                    args_str => &args_str,
                    ok_binding => &ok_binding,
                },
            ));
            // Write result via out_result pointer — for complex types this is unreachable.
            // `unreachable` diverges, so any code after it (including `return 0;`) would
            // be flagged "unreachable code" by zig 0.16+; only emit the trailing return
            // when the success path actually flows through.
            let mut success_path_diverges = false;
            if has_result_out {
                match &method.return_type {
                    TypeRef::Primitive(_) | TypeRef::Unit => {
                        out.push_str(&crate::template_env::render(
                            "thunk_result_assign.jinja",
                            minijinja::context! {
                                ok_binding => &ok_binding,
                            },
                        ));
                    }
                    _ => {
                        // String/Bytes/complex: cannot safely convert without allocator context
                        out.push_str(&crate::template_env::render(
                            "thunk_if_fallible.jinja",
                            minijinja::context! {
                                ok_binding => &ok_binding,
                            },
                        ));
                        success_path_diverges = true;
                    }
                }
            } else {
                // Unit return on success — discard the captured Void to silence unused-variable.
                out.push_str(&crate::template_env::render(
                    "thunk_if_ok_result.jinja",
                    minijinja::context! {
                        ok_binding => &ok_binding,
                    },
                ));
            }
            if !success_path_diverges {
                out.push_str("                    return 0;\n");
            }
            out.push_str("                } else |err| {\n");
            out.push_str("                    _ = err;\n");
            out.push_str("                    if (out_error) |ptr| ptr.* = null; // caller checks error code\n");
            out.push_str("                    return 1;\n");
            out.push_str("                }\n");
        } else {
            // Infallible non-Unit methods get an `out_result` param "for uniformity"
            // (see vtable_c_params), but the body returns the value directly via the
            // function return type — so the param is unused. Discard it so zig 0.16+
            // doesn't flag "unused function parameter".
            if !matches!(method.return_type, TypeRef::Unit) {
                out.push_str("                _ = out_result;\n");
            }
            match &method.return_type {
                TypeRef::Unit => {
                    out.push_str(&crate::template_env::render(
                        "thunk_if_error.jinja",
                        minijinja::context! {
                            method_snake => &method_snake,
                            args_str => &args_str,
                        },
                    ));
                }
                TypeRef::Primitive(_) => {
                    out.push_str(&crate::template_env::render(
                        "thunk_infallible_return.jinja",
                        minijinja::context! {
                            method_snake => &method_snake,
                            args_str => &args_str,
                        },
                    ));
                }
                _ => {
                    // Non-unit infallible non-primitive: pass through (e.g., [*c]const u8)
                    out.push_str(&crate::template_env::render(
                        "thunk_infallible_return.jinja",
                        minijinja::context! {
                            method_snake => &method_snake,
                            args_str => &args_str,
                        },
                    ));
                }
            }
        }

        out.push_str("            }\n");
        out.push_str("        }.thunk,\n");
        out.push('\n');
    }

    // free_user_data stub — does nothing by default; caller overrides if needed
    out.push_str(&crate::template_env::render(
        "vtable_free_user_data.jinja",
        minijinja::context! {},
    ));

    out.push_str("    };\n");
    out.push_str("}\n");
}

/// Emit the vtable extern struct and registration shim for a single trait bridge.
///
/// `prefix` is the C FFI prefix (e.g., `"kreuzberg"`).
/// `bridge_cfg` is the trait bridge configuration entry.
/// `trait_def` is the IR type definition for the trait (must have `is_trait = true`).
/// `out` is the output buffer to append to.
pub fn emit_trait_bridge(prefix: &str, bridge_cfg: &TraitBridgeConfig, trait_def: &TypeDef, out: &mut String) {
    let trait_name = &trait_def.name;
    let snake = trait_snake(trait_name);
    let has_super_trait = bridge_cfg.super_trait.is_some();

    // -------------------------------------------------------------------------
    // Vtable struct: I{Trait}
    // -------------------------------------------------------------------------
    out.push_str(&crate::template_env::render(
        "trait_vtable_header.jinja",
        minijinja::context! {
            trait_name => trait_name,
            snake => &snake,
        },
    ));
    out.push_str(&crate::template_env::render(
        "trait_struct_header.jinja",
        minijinja::context! {
            trait_name => trait_name,
        },
    ));

    // Plugin lifecycle slots — always present when a super_trait is configured.
    if has_super_trait {
        out.push_str("    /// Return the plugin name into `out_name` (heap-allocated, caller frees).\n");
        out.push_str(
            "    name_fn: ?*const fn (user_data: ?*anyopaque, out_name: ?*?[*c]u8) callconv(.C) void = null,\n",
        );
        out.push('\n');

        out.push_str("    /// Return the plugin version into `out_version` (heap-allocated, caller frees).\n");
        out.push_str(
            "    version_fn: ?*const fn (user_data: ?*anyopaque, out_version: ?*?[*c]u8) callconv(.C) void = null,\n",
        );
        out.push('\n');

        out.push_str("    /// Initialise the plugin; return 0 on success, non-zero on error.\n");
        out.push_str(
            "    initialize_fn: ?*const fn (user_data: ?*anyopaque, out_error: ?*?[*c]u8) callconv(.C) i32 = null,\n",
        );
        out.push('\n');

        out.push_str("    /// Shut down the plugin; return 0 on success, non-zero on error.\n");
        out.push_str(
            "    shutdown_fn: ?*const fn (user_data: ?*anyopaque, out_error: ?*?[*c]u8) callconv(.C) i32 = null,\n",
        );
        out.push('\n');
    }

    // Trait method slots
    for method in &trait_def.methods {
        if !method.doc.is_empty() {
            for line in method.doc.lines() {
                out.push_str(&crate::template_env::render(
                    "trait_method_doc.jinja",
                    minijinja::context! {
                        line => line,
                    },
                ));
            }
        }

        let ret = vtable_return_type(method);
        let method_snake = method.name.to_snake_case();

        // Build the parameter list: user_data first, then method params.
        let mut params = vec!["user_data: ?*anyopaque".to_string()];
        for p in &method.params {
            let ty = vtable_param_type(&p.ty);
            // Bytes expand to two args (ptr + len)
            if matches!(p.ty, TypeRef::Bytes) {
                params.push(format!("{}_ptr: [*c]const u8", p.name));
                params.push(format!("{}_len: usize", p.name));
            } else {
                params.push(format!("{}: {ty}", p.name));
            }
        }

        // Fallible methods get out-result and out-error pointers.
        if method.error_type.is_some() {
            if !matches!(method.return_type, TypeRef::Unit) {
                params.push("out_result: ?*?[*c]u8".to_string());
            }
            params.push("out_error: ?*?[*c]u8".to_string());
        } else if !matches!(method.return_type, TypeRef::Unit) {
            // Infallible non-void: return via out_result too for uniformity
            params.push("out_result: ?*?[*c]u8".to_string());
        }

        let params_str = params.join(", ");
        out.push_str(&crate::template_env::render(
            "trait_method_signature.jinja",
            minijinja::context! {
                method_snake => &method_snake,
                params_str => &params_str,
                ret => &ret,
            },
        ));
    }

    // free_user_data — always last; called by Rust Drop to release the Zig-side handle.
    out.push_str("    /// Called by the Rust runtime when the bridge is dropped.\n");
    out.push_str("    /// Use this to release any Zig-side state held via `user_data`.\n");
    out.push_str("    free_user_data: ?*const fn (user_data: ?*anyopaque) callconv(.C) void = null,\n");

    out.push_str("};\n");
    out.push('\n');

    // -------------------------------------------------------------------------
    // Registration shim: register_{trait_snake}
    // -------------------------------------------------------------------------
    let c_register = format!("c.{prefix}_register_{snake}");
    let c_unregister = format!("c.{prefix}_unregister_{snake}");

    out.push_str(&crate::template_env::render(
        "register_fn_doc1.jinja",
        minijinja::context! {
            trait_name => trait_name,
            snake => &snake,
        },
    ));
    out.push_str(&crate::template_env::render(
        "register_fn_signature.jinja",
        minijinja::context! {
            snake => &snake,
            trait_name => trait_name,
        },
    ));
    out.push_str(&crate::template_env::render(
        "register_fn_body.jinja",
        minijinja::context! {
            c_register => &c_register,
        },
    ));
    out.push_str("}\n");
    out.push('\n');

    // -------------------------------------------------------------------------
    // Unregistration shim: unregister_{trait_snake}
    // -------------------------------------------------------------------------
    out.push_str(&crate::template_env::render(
        "unregister_fn_doc.jinja",
        minijinja::context! {
            trait_name => trait_name,
        },
    ));
    out.push_str(&crate::template_env::render(
        "unregister_fn_signature.jinja",
        minijinja::context! {
            snake => &snake,
        },
    ));
    out.push_str(&crate::template_env::render(
        "unregister_fn_body.jinja",
        minijinja::context! {
            c_unregister => &c_unregister,
        },
    ));
    out.push_str("}\n");
    out.push('\n');

    // -------------------------------------------------------------------------
    // Comptime vtable builder: make_{trait_snake}_vtable
    // -------------------------------------------------------------------------
    emit_make_vtable(trait_name, has_super_trait, trait_def, out);
}

// ---------------------------------------------------------------------------
// TraitBridgeGenerator implementation for the Zig backend
// ---------------------------------------------------------------------------

/// Zig-specific [`TraitBridgeGenerator`] implementation.
///
/// Carries the FFI symbol prefix (e.g., `"kreuzberg"`) used when deriving the
/// C symbol for `unregister_*` and `clear_*` wrappers.
///
/// The required trait methods that produce *Rust* source (`gen_sync_method_body`,
/// `gen_async_method_body`, `gen_constructor`, `gen_registration_fn`) return
/// empty strings because Zig bridge code is produced by the standalone
/// [`emit_trait_bridge`] free function, not the shared driver.
pub struct ZigTraitBridgeGenerator {
    /// FFI symbol prefix (e.g., `"kreuzberg"`).
    pub prefix: String,
}

impl ZigTraitBridgeGenerator {
    /// Construct a new generator for the given FFI symbol prefix.
    pub fn new(prefix: impl Into<String>) -> Self {
        Self { prefix: prefix.into() }
    }
}

impl TraitBridgeGenerator for ZigTraitBridgeGenerator {
    // ------------------------------------------------------------------
    // Stub methods — Zig bridge code is emitted by `emit_trait_bridge`.
    // ------------------------------------------------------------------

    fn foreign_object_type(&self) -> &str {
        ""
    }

    fn bridge_imports(&self) -> Vec<String> {
        Vec::new()
    }

    fn gen_sync_method_body(&self, _method: &MethodDef, _spec: &TraitBridgeSpec) -> String {
        String::new()
    }

    fn gen_async_method_body(&self, _method: &MethodDef, _spec: &TraitBridgeSpec) -> String {
        String::new()
    }

    fn gen_constructor(&self, _spec: &TraitBridgeSpec) -> String {
        String::new()
    }

    fn gen_registration_fn(&self, _spec: &TraitBridgeSpec) -> String {
        String::new()
    }

    // ------------------------------------------------------------------
    // Zig-specific overrides
    // ------------------------------------------------------------------

    /// Emit a Zig wrapper that calls `c.{prefix}_{unregister_fn}(name, out_error)`.
    ///
    /// Returns an empty string when `spec.bridge_config.unregister_fn` is `None`.
    fn gen_unregistration_fn(&self, spec: &TraitBridgeSpec) -> String {
        let Some(unregister_fn) = spec.bridge_config.unregister_fn.as_deref() else {
            return String::new();
        };
        let c_unregister = format!("c.{}_{}", self.prefix, unregister_fn);

        let mut out = String::new();
        out.push_str(&crate::template_env::render(
            "unregister_fn_doc.jinja",
            minijinja::context! {
                trait_name => spec.trait_def.name.as_str(),
            },
        ));
        // Emit the signature directly: the configured `unregister_fn` is the
        // complete Zig function name, not just the trait-snake suffix.
        out.push_str(&format!(
            "pub fn {unregister_fn}(name: [*c]const u8, out_error: ?*?[*c]u8) i32 {{\n"
        ));
        out.push_str(&crate::template_env::render(
            "unregister_fn_body.jinja",
            minijinja::context! {
                c_unregister => &c_unregister,
            },
        ));
        out.push_str("}\n");
        out
    }

    /// Emit a Zig wrapper that calls `c.{prefix}_{clear_fn}(out_error)`.
    ///
    /// Returns an empty string when `spec.bridge_config.clear_fn` is `None`.
    fn gen_clear_fn(&self, spec: &TraitBridgeSpec) -> String {
        let Some(clear_fn) = spec.bridge_config.clear_fn.as_deref() else {
            return String::new();
        };
        let c_clear = format!("c.{}_{}", self.prefix, clear_fn);

        let mut out = String::new();
        out.push_str(&crate::template_env::render(
            "clear_fn_doc.jinja",
            minijinja::context! {
                trait_name => spec.trait_def.name.as_str(),
            },
        ));
        out.push_str(&crate::template_env::render(
            "clear_fn_signature.jinja",
            minijinja::context! {
                clear_fn => clear_fn,
            },
        ));
        out.push_str(&crate::template_env::render(
            "clear_fn_body.jinja",
            minijinja::context! {
                c_clear => &c_clear,
            },
        ));
        out.push_str("}\n");
        out
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alef_core::ir::{FieldDef, MethodDef, ParamDef, PrimitiveType, ReceiverKind, TypeRef};

    fn make_trait_def(name: &str, methods: Vec<MethodDef>) -> TypeDef {
        TypeDef {
            name: name.to_string(),
            rust_path: format!("demo::{name}"),
            original_rust_path: String::new(),
            fields: Vec::<FieldDef>::new(),
            methods,
            is_opaque: true,
            is_clone: false,
            is_copy: false,
            is_trait: true,
            has_default: false,
            has_stripped_cfg_fields: false,
            is_return_type: false,
            serde_rename_all: None,
            has_serde: false,
            super_traits: vec![],
            doc: String::new(),
            cfg: None,
        }
    }

    fn make_method(name: &str, params: Vec<ParamDef>, return_type: TypeRef, error_type: Option<&str>) -> MethodDef {
        MethodDef {
            name: name.to_string(),
            params,
            return_type,
            is_async: false,
            is_static: false,
            error_type: error_type.map(|s| s.to_string()),
            doc: String::new(),
            receiver: Some(ReceiverKind::Ref),
            sanitized: false,
            trait_source: None,
            returns_ref: false,
            returns_cow: false,
            return_newtype_wrapper: None,
            has_default_impl: false,
        }
    }

    fn make_param(name: &str, ty: TypeRef) -> ParamDef {
        ParamDef {
            name: name.to_string(),
            ty,
            optional: false,
            default: None,
            sanitized: false,
            typed_default: None,
            is_ref: false,
            is_mut: false,
            newtype_wrapper: None,
            original_type: None,
        }
    }

    fn make_bridge_cfg(trait_name: &str, super_trait: Option<&str>) -> TraitBridgeConfig {
        TraitBridgeConfig {
            trait_name: trait_name.to_string(),
            super_trait: super_trait.map(|s| s.to_string()),
            registry_getter: None,
            register_fn: None,

            unregister_fn: None,

            clear_fn: None,
            type_alias: None,
            param_name: None,
            register_extra_args: None,
            exclude_languages: vec![],
            bind_via: alef_core::config::BridgeBinding::FunctionParam,
            options_type: None,
            options_field: None,
        }
    }

    #[test]
    fn single_method_trait_emits_vtable_and_register() {
        let trait_def = make_trait_def(
            "Validator",
            vec![make_method(
                "validate",
                vec![make_param("input", TypeRef::String)],
                TypeRef::Primitive(PrimitiveType::Bool),
                None,
            )],
        );
        let bridge_cfg = make_bridge_cfg("Validator", None);

        let mut out = String::new();
        emit_trait_bridge("demo", &bridge_cfg, &trait_def, &mut out);

        // Vtable struct
        assert!(
            out.contains("pub const IValidator = extern struct {"),
            "missing vtable struct: {out}"
        );
        // Method slot present
        assert!(out.contains("validate:"), "missing validate slot: {out}");
        // user_data first arg
        assert!(out.contains("user_data: ?*anyopaque"), "missing user_data: {out}");
        // callconv(.C) present
        assert!(out.contains("callconv(.C)"), "missing callconv: {out}");
        // free_user_data slot
        assert!(out.contains("free_user_data:"), "missing free_user_data: {out}");
        // Registration shim
        assert!(out.contains("pub fn register_validator("), "missing register fn: {out}");
        assert!(out.contains("c.demo_register_validator("), "wrong C symbol: {out}");
        // Unregistration shim
        assert!(
            out.contains("pub fn unregister_validator("),
            "missing unregister fn: {out}"
        );
        assert!(
            out.contains("c.demo_unregister_validator("),
            "wrong unregister C symbol: {out}"
        );
        // No plugin lifecycle when no super_trait
        assert!(
            !out.contains("name_fn:"),
            "should not emit name_fn without super_trait: {out}"
        );
    }

    #[test]
    fn multi_method_trait_with_super_trait_emits_lifecycle_slots() {
        let trait_def = make_trait_def(
            "OcrBackend",
            vec![
                make_method(
                    "process_image",
                    vec![
                        make_param("image_bytes", TypeRef::Bytes),
                        make_param("config", TypeRef::String),
                    ],
                    TypeRef::String,
                    Some("OcrError"),
                ),
                make_method(
                    "supports_language",
                    vec![make_param("lang", TypeRef::String)],
                    TypeRef::Primitive(PrimitiveType::Bool),
                    None,
                ),
            ],
        );
        let bridge_cfg = make_bridge_cfg("OcrBackend", Some("kreuzberg::plugins::Plugin"));

        let mut out = String::new();
        emit_trait_bridge("kreuzberg", &bridge_cfg, &trait_def, &mut out);

        // Struct name
        assert!(
            out.contains("pub const IOcrBackend = extern struct {"),
            "missing vtable: {out}"
        );
        // Plugin lifecycle slots emitted
        assert!(out.contains("name_fn:"), "missing name_fn: {out}");
        assert!(out.contains("version_fn:"), "missing version_fn: {out}");
        assert!(out.contains("initialize_fn:"), "missing initialize_fn: {out}");
        assert!(out.contains("shutdown_fn:"), "missing shutdown_fn: {out}");
        // Trait method slots
        assert!(out.contains("process_image:"), "missing process_image slot: {out}");
        assert!(
            out.contains("supports_language:"),
            "missing supports_language slot: {out}"
        );
        // Bytes param expands to ptr + len
        assert!(out.contains("image_bytes_ptr:"), "missing bytes ptr expansion: {out}");
        assert!(out.contains("image_bytes_len:"), "missing bytes len expansion: {out}");
        // Fallible method gets out_error
        assert!(
            out.contains("out_error:"),
            "missing out_error for fallible method: {out}"
        );
        // C symbols use kreuzberg prefix
        assert!(
            out.contains("c.kreuzberg_register_ocr_backend("),
            "wrong register symbol: {out}"
        );
        assert!(
            out.contains("c.kreuzberg_unregister_ocr_backend("),
            "wrong unregister symbol: {out}"
        );
        // Registration shim signature
        assert!(
            out.contains("pub fn register_ocr_backend("),
            "missing register_ocr_backend fn: {out}"
        );
    }

    // -----------------------------------------------------------------
    // make_*_vtable tests
    // -----------------------------------------------------------------

    #[test]
    fn make_vtable_emits_comptime_function_and_thunk() {
        let trait_def = make_trait_def(
            "Validator",
            vec![make_method(
                "validate",
                vec![make_param("input", TypeRef::String)],
                TypeRef::Primitive(PrimitiveType::Bool),
                None,
            )],
        );
        let bridge_cfg = make_bridge_cfg("Validator", None);

        let mut out = String::new();
        emit_trait_bridge("demo", &bridge_cfg, &trait_def, &mut out);

        // Helper function declaration
        assert!(
            out.contains("pub fn make_validator_vtable(comptime T: type, instance: *T)"),
            "missing make_validator_vtable: {out}"
        );
        // Returns the vtable type
        assert!(out.contains("IValidator{"), "missing vtable literal: {out}");
        // Thunk casts user_data
        assert!(out.contains("@ptrCast(@alignCast(ud))"), "missing @ptrCast cast: {out}");
        // callconv(.C) in thunk
        assert!(out.contains("callconv(.C)"), "missing callconv(.C) in thunk: {out}");
        // validate thunk field
        assert!(out.contains(".validate ="), "missing .validate thunk field: {out}");
        // free_user_data thunk
        assert!(
            out.contains(".free_user_data ="),
            "missing .free_user_data thunk: {out}"
        );
        // No lifecycle stubs without super_trait
        assert!(
            !out.contains(".name_fn ="),
            "must not emit .name_fn without super_trait: {out}"
        );
    }

    #[test]
    fn make_vtable_with_super_trait_emits_lifecycle_stubs() {
        let trait_def = make_trait_def("OcrBackend", vec![]);
        let bridge_cfg = make_bridge_cfg("OcrBackend", Some("kreuzberg::Plugin"));

        let mut out = String::new();
        emit_trait_bridge("kreuzberg", &bridge_cfg, &trait_def, &mut out);

        assert!(
            out.contains("pub fn make_ocr_backend_vtable(comptime T: type, instance: *T)"),
            "missing make_ocr_backend_vtable: {out}"
        );
        assert!(out.contains(".name_fn ="), "missing .name_fn stub: {out}");
        assert!(out.contains(".version_fn ="), "missing .version_fn stub: {out}");
        assert!(out.contains(".initialize_fn ="), "missing .initialize_fn stub: {out}");
        assert!(out.contains(".shutdown_fn ="), "missing .shutdown_fn stub: {out}");
    }

    #[test]
    fn make_vtable_bytes_param_reconstructs_slice_in_thunk() {
        let trait_def = make_trait_def(
            "Processor",
            vec![make_method(
                "process",
                vec![make_param("data", TypeRef::Bytes)],
                TypeRef::Unit,
                None,
            )],
        );
        let bridge_cfg = make_bridge_cfg("Processor", None);

        let mut out = String::new();
        emit_trait_bridge("demo", &bridge_cfg, &trait_def, &mut out);

        // Thunk receives ptr+len params
        assert!(out.contains("data_ptr: [*c]const u8"), "missing data_ptr param: {out}");
        assert!(out.contains("data_len: usize"), "missing data_len param: {out}");
        // Thunk reconstructs slice
        assert!(
            out.contains("data_ptr[0..data_len]"),
            "thunk must reconstruct slice from ptr+len: {out}"
        );
        // Thunk calls self.process with the slice
        assert!(
            out.contains("self.process(data_slice)"),
            "thunk must call self.process: {out}"
        );
    }

    #[test]
    fn make_vtable_fallible_method_returns_i32_error_code() {
        let trait_def = make_trait_def(
            "Parser",
            vec![make_method("parse", vec![], TypeRef::Unit, Some("ParseError"))],
        );
        let bridge_cfg = make_bridge_cfg("Parser", None);

        let mut out = String::new();
        emit_trait_bridge("demo", &bridge_cfg, &trait_def, &mut out);

        // Thunk returns i32 (fallible → i32 return)
        assert!(
            out.contains("callconv(.C) i32"),
            "fallible thunk must return i32: {out}"
        );
        // Returns 0 on success
        assert!(out.contains("return 0;"), "must return 0 on success: {out}");
        // Returns 1 on error
        assert!(out.contains("return 1;"), "must return 1 on error: {out}");
        // Error branch writes to out_error
        assert!(out.contains("out_error"), "must write to out_error: {out}");
    }

    #[test]
    fn make_vtable_primitive_return_passes_through() {
        let trait_def = make_trait_def(
            "Counter",
            vec![make_method(
                "count",
                vec![],
                TypeRef::Primitive(PrimitiveType::I32),
                None,
            )],
        );
        let bridge_cfg = make_bridge_cfg("demo", None);

        let mut out = String::new();
        emit_trait_bridge("demo", &bridge_cfg, &trait_def, &mut out);

        // Infallible primitive method: thunk returns the value directly
        assert!(
            out.contains("return self.count()"),
            "primitive return must be forwarded directly: {out}"
        );
    }

    // -----------------------------------------------------------------
    // ZigTraitBridgeGenerator tests
    // -----------------------------------------------------------------

    fn make_spec<'a>(trait_def: &'a TypeDef, bridge_cfg: &'a TraitBridgeConfig) -> TraitBridgeSpec<'a> {
        use alef_codegen::generators::trait_bridge::TraitBridgeSpec;
        use std::collections::HashMap;
        TraitBridgeSpec {
            trait_def,
            bridge_config: bridge_cfg,
            core_import: "kreuzberg",
            wrapper_prefix: "Zig",
            type_paths: HashMap::new(),
            error_type: "KreuzbergError".to_string(),
            error_constructor: "KreuzbergError::msg({msg})".to_string(),
        }
    }

    #[test]
    fn gen_unregistration_fn_emits_wrapper_when_configured() {
        let trait_def = make_trait_def("OcrBackend", vec![]);
        let mut bridge_cfg = make_bridge_cfg("OcrBackend", None);
        bridge_cfg.unregister_fn = Some("unregister_ocr_backend".to_string());

        let generator = ZigTraitBridgeGenerator::new("kreuzberg");
        let spec = make_spec(&trait_def, &bridge_cfg);
        let out = generator.gen_unregistration_fn(&spec);

        assert!(!out.is_empty(), "expected non-empty output when unregister_fn is set");
        assert!(
            out.contains("pub fn unregister_ocr_backend("),
            "wrong function name: {out}"
        );
        assert!(
            out.contains("c.kreuzberg_unregister_ocr_backend("),
            "wrong C symbol: {out}"
        );
        assert!(
            out.contains("out_error: ?*?[*c]u8") || out.contains("out_error"),
            "missing out_error param: {out}"
        );
        assert!(out.contains("return "), "missing return statement: {out}");
        assert!(out.ends_with("}\n"), "missing closing brace: {out}");
    }

    #[test]
    fn gen_unregistration_fn_returns_empty_when_not_configured() {
        let trait_def = make_trait_def("OcrBackend", vec![]);
        let bridge_cfg = make_bridge_cfg("OcrBackend", None); // unregister_fn is None

        let generator = ZigTraitBridgeGenerator::new("kreuzberg");
        let spec = make_spec(&trait_def, &bridge_cfg);
        let out = generator.gen_unregistration_fn(&spec);

        assert!(
            out.is_empty(),
            "expected empty output when unregister_fn is None, got: {out}"
        );
    }

    #[test]
    fn gen_clear_fn_emits_wrapper_when_configured() {
        let trait_def = make_trait_def("OcrBackend", vec![]);
        let mut bridge_cfg = make_bridge_cfg("OcrBackend", None);
        bridge_cfg.clear_fn = Some("clear_ocr_backends".to_string());

        let generator = ZigTraitBridgeGenerator::new("kreuzberg");
        let spec = make_spec(&trait_def, &bridge_cfg);
        let out = generator.gen_clear_fn(&spec);

        assert!(!out.is_empty(), "expected non-empty output when clear_fn is set");
        assert!(out.contains("pub fn clear_ocr_backends("), "wrong function name: {out}");
        assert!(out.contains("c.kreuzberg_clear_ocr_backends("), "wrong C symbol: {out}");
        assert!(
            out.contains("out_error: ?*?[*c]u8") || out.contains("out_error"),
            "missing out_error param: {out}"
        );
        assert!(out.contains("return "), "missing return statement: {out}");
        assert!(out.ends_with("}\n"), "missing closing brace: {out}");
    }

    #[test]
    fn gen_clear_fn_returns_empty_when_not_configured() {
        let trait_def = make_trait_def("OcrBackend", vec![]);
        let bridge_cfg = make_bridge_cfg("OcrBackend", None); // clear_fn is None

        let generator = ZigTraitBridgeGenerator::new("kreuzberg");
        let spec = make_spec(&trait_def, &bridge_cfg);
        let out = generator.gen_clear_fn(&spec);

        assert!(
            out.is_empty(),
            "expected empty output when clear_fn is None, got: {out}"
        );
    }

    #[test]
    fn gen_unregistration_fn_uses_snake_case_function_name_verbatim() {
        // The configured `unregister_fn` name is used as-is (not re-derived from the trait).
        let trait_def = make_trait_def("DocumentExtractor", vec![]);
        let mut bridge_cfg = make_bridge_cfg("DocumentExtractor", None);
        bridge_cfg.unregister_fn = Some("unregister_extractor".to_string());

        let generator = ZigTraitBridgeGenerator::new("demo");
        let spec = make_spec(&trait_def, &bridge_cfg);
        let out = generator.gen_unregistration_fn(&spec);

        assert!(
            out.contains("pub fn unregister_extractor("),
            "must use configured fn name verbatim: {out}"
        );
        assert!(
            out.contains("c.demo_unregister_extractor("),
            "must use configured fn name in C symbol: {out}"
        );
    }

    #[test]
    fn gen_clear_fn_uses_configured_fn_name_verbatim() {
        let trait_def = make_trait_def("DocumentExtractor", vec![]);
        let mut bridge_cfg = make_bridge_cfg("DocumentExtractor", None);
        bridge_cfg.clear_fn = Some("clear_all_extractors".to_string());

        let generator = ZigTraitBridgeGenerator::new("demo");
        let spec = make_spec(&trait_def, &bridge_cfg);
        let out = generator.gen_clear_fn(&spec);

        assert!(
            out.contains("pub fn clear_all_extractors("),
            "must use configured fn name verbatim: {out}"
        );
        assert!(
            out.contains("c.demo_clear_all_extractors("),
            "must use configured fn name in C symbol: {out}"
        );
    }
}