alef 0.23.15

Opinionated polyglot binding generator for Rust libraries
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
//! Service-API codegen for the Java backend.
//!
//! Generates Java source files for service lifecycle and handler registration using Panama FFM:
//! - Service class wrapping opaque owner handles (via downcalls to C FFI symbols)
//! - Handler functional interface that accepts request JSON and returns response JSON
//! - Registration methods that build upcall stubs from handlers and invoke the C FFI
//! - Entrypoint methods (run/finalize) driving the service lifecycle
//!
//! Panama FFM Pattern:
//! - `Linker.nativeLinker()` + `SymbolLookup.libraryLookup(...)` to locate C symbols
//! - `downcallHandle()` + `FunctionDescriptor` for C function invocations
//! - `upcallStub()` + `MethodHandle` to wrap Java callbacks for C to call back into Java
//! - `Arena` for managing lifetime of callback stubs + context pointers
//! - String marshalling via `MemorySegment` + `getString()` / `CLinker.C_CHAR.byteSize()`

use crate::backends::java::template_env;
use crate::core::backend::GeneratedFile;
use crate::core::config::ResolvedCrateConfig;
use crate::core::ir::{ApiSurface, EntrypointKind, ServiceDef, TypeRef};
use heck::{ToLowerCamelCase, ToSnakeCase, ToUpperCamelCase};
use minijinja::context;
use std::path::PathBuf;

// ────────────────────────────────────────────────────────── helpers ──

/// Check if a TypeRef is an opaque (surface-wrapped Named type).
fn is_opaque_metadata(ty: &TypeRef, api: &ApiSurface) -> bool {
    matches!(ty, TypeRef::Named(n) if api.types.iter().any(|t| t.name == *n))
}

/// Map TypeRef to Java parameter type.
/// For Named types that are in the API surface, return the wrapper class name (opaque handle).
/// For String/Char/primitives, return the Java type.
fn java_type_for_metadata(ty: &TypeRef, api: &ApiSurface) -> String {
    match ty {
        TypeRef::String | TypeRef::Char => "String".to_owned(),
        TypeRef::Primitive(p) => {
            use crate::core::ir::PrimitiveType;
            match p {
                PrimitiveType::Bool => "boolean".to_owned(),
                PrimitiveType::U8 | PrimitiveType::I8 => "byte".to_owned(),
                PrimitiveType::U16 | PrimitiveType::I16 => "short".to_owned(),
                PrimitiveType::U32 | PrimitiveType::I32 => "int".to_owned(),
                PrimitiveType::U64 | PrimitiveType::I64 => "long".to_owned(),
                PrimitiveType::F32 => "float".to_owned(),
                PrimitiveType::F64 => "double".to_owned(),
                PrimitiveType::Usize | PrimitiveType::Isize => "long".to_owned(),
            }
        }
        TypeRef::Bytes => "byte[]".to_owned(),
        TypeRef::Unit => "void".to_owned(),
        TypeRef::Named(n) if api.types.iter().any(|t| t.name == *n) => {
            // Opaque wrapper class for surface-wrapped types (e.g., RouteBuilder, AppConfig)
            n.clone()
        }
        _ => "Object".to_owned(),
    }
}

// ──────────────────────────────────────────────── Java Service Class ──

/// Generate the idiomatic Java service class wrapper using Panama FFM.
///
/// The class exposes:
/// - Constructor that invokes the C FFI `{prefix}_{service}_new()` via downcall
/// - Registration methods that build upcall stubs from handlers and register them
/// - Run/Finalize entrypoint methods that invoke C FFI entrypoint downcalls
/// - AutoCloseable interface with close() to invoke the C FFI `_free()` downcall
/// - All Panama FFM binding details (Linker, downcallHandle, FunctionDescriptor, etc.)
fn gen_service_class(api: &ApiSurface, service: &ServiceDef, package: &str, config: &ResolvedCrateConfig) -> String {
    let mut out = String::new();

    // File header
    out.push_str("// Auto-generated by alef — DO NOT EDIT\n\n");
    out.push_str(&format!("package {};\n\n", package));

    // Required imports for Panama FFM
    out.push_str("import java.lang.foreign.*;\n");
    out.push_str("import java.lang.invoke.MethodHandle;\n");
    out.push_str("import java.lang.invoke.MethodHandles;\n");
    out.push_str("import java.lang.invoke.MethodType;\n\n");

    // Service class
    let class_name = &service.name;
    let service_snake = service.name.to_snake_case();
    let ffi_prefix = config.ffi_prefix().to_lowercase();

    out.push_str("/**\n");
    out.push_str(&format!(" * Service wrapper for {} using Panama FFM.\n", service.name));
    out.push_str(" *\n");
    out.push_str(" * Binds to C FFI symbols:\n");
    out.push_str(&format!(
        " * - {}_{}_new() -> opaque handle\n",
        ffi_prefix, service_snake
    ));
    out.push_str(&format!(" * - {}_{}_free(opaque)\n", ffi_prefix, service_snake));
    for reg in &service.registrations {
        out.push_str(&format!(
            " * - {}_{}_register_{} (handler registration)\n",
            ffi_prefix,
            service_snake,
            reg.method.to_snake_case()
        ));
    }
    for ep in &service.entrypoints {
        out.push_str(&format!(
            " * - {}_{}_ep_{} (entrypoint)\n",
            ffi_prefix,
            service_snake,
            ep.method.to_snake_case()
        ));
    }
    out.push_str(" */\n");
    out.push_str(&format!("public class {} implements AutoCloseable {{\n\n", class_name));

    // Private fields: owner handle + arena for callback lifetime management
    out.push_str("    private MemorySegment ownerHandle;\n");
    out.push_str("    private final Arena arena = Arena.ofConfined();\n\n");

    // Static field to hold the NativeLinker (Panama FFM pattern)
    out.push_str("    private static final Linker LINKER = Linker.nativeLinker();\n");
    out.push_str("    private static final SymbolLookup LOOKUP = SymbolLookup.loaderLookup();\n\n");

    // Static initializer: ensure native library is loaded before symbol lookup
    out.push_str("    static {\n");
    out.push_str("        // Force NativeLib static initialization to load the native library\n");
    out.push_str("        // This ensures all FFI symbols are available before we try to look them up.\n");
    out.push_str("        // NativeLib is a package-private class, but accessing its class forces\n");
    out.push_str("        // its static initializer to run and load the native library.\n");
    out.push_str("        try {\n");
    out.push_str(&format!("            Class.forName(\"{}.NativeLib\");\n", package));
    out.push_str("        } catch (ClassNotFoundException ignored) {\n");
    out.push_str("            // NativeLib not available; native library may be pre-loaded\n");
    out.push_str("        }\n");
    out.push_str("    }\n\n");

    // Helper method: invoke handler with C pointer marshalling
    // Signature must match Panama FFM upcall stub requirements: (ADDRESS, ADDRESS) -> ADDRESS
    {
        out.push_str("    // Adapter for handler upcalls: marshals C pointers <-> Java strings\n");
        out.push_str("    private static MemorySegment invokeHandlerWithMarshal(\n");
        out.push_str("            MemorySegment contextPtr,\n");
        out.push_str("            MemorySegment requestPtr,\n");
        out.push_str("            Callable handler,\n");
        out.push_str("            Arena arena) throws Throwable {\n");
        out.push_str("        String requestStr = requestPtr.getString(0);\n");
        out.push_str("        String responseStr = handler.handle(requestStr);\n");
        out.push_str("        return arena.allocateFrom(responseStr);\n");
        out.push_str("    }\n\n");
    }

    // Constructor: invoke {prefix}_{service}_new() downcall
    {
        out.push_str("    /**\n");
        out.push_str(&format!("     * Create a new {}.\n", service.name));
        out.push_str(&format!(
            "     * Invokes C FFI: {}_{}_new()\n",
            ffi_prefix, service_snake
        ));
        out.push_str("     */\n");
        out.push_str(&format!("    public {}() {{\n", class_name));

        out.push_str("        try {\n");
        out.push_str(&format!(
            "            MemorySegment addr = LOOKUP.find(\"{}_{}_new\")\n",
            ffi_prefix, service_snake
        ));
        out.push_str(&format!(
            "                .or(() -> LOOKUP.find(\"_{}_{}_new\"))\n",
            ffi_prefix, service_snake
        ));
        out.push_str("                .orElseThrow();\n");
        out.push_str("            FunctionDescriptor desc = FunctionDescriptor.of(ValueLayout.ADDRESS);\n");
        out.push_str("            MethodHandle handle = LINKER.downcallHandle(addr, desc);\n");
        out.push_str("            this.ownerHandle = (MemorySegment) handle.invoke();\n");
        out.push_str("            if (this.ownerHandle == null) {\n");
        out.push_str("                throw new RuntimeException(\"Failed to allocate service instance\");\n");
        out.push_str("            }\n");
        out.push_str("        } catch (Throwable e) {\n");
        out.push_str("            throw new RuntimeException(\"Failed to invoke constructor\", e);\n");
        out.push_str("        }\n");
        out.push_str("    }\n\n");
    }

    // Registration methods: build upcall stub from handler, invoke register downcall
    for reg in &service.registrations {
        let reg_method = &reg.method;
        let reg_method_camel = reg_method.to_upper_camel_case();
        let reg_method_snake = reg_method.to_snake_case();

        out.push_str("    /**\n");
        out.push_str(&format!("     * Register a handler for {}.\n", reg_method));
        out.push_str(&format!(
            "     * Invokes C FFI: {}_{}_register_{}\n",
            ffi_prefix, service_snake, reg_method_snake
        ));
        out.push_str("     *\n");
        out.push_str("     * @param handler functional interface receiving JSON request, returning JSON response\n");

        for meta_param in &reg.metadata_params {
            out.push_str(&format!(
                "     * @param {} {}\n",
                meta_param.name.to_lower_camel_case(),
                java_type_for_metadata(&meta_param.ty, api)
            ));
        }
        out.push_str("     * @return 0 on success, non-zero error code on failure\n");
        out.push_str("     */\n");

        out.push_str(&format!(
            "    public int register{}{}(Callable handler",
            class_name, reg_method_camel
        ));

        // Add metadata parameters
        for meta_param in &reg.metadata_params {
            let java_type = java_type_for_metadata(&meta_param.ty, api);
            let param_name = meta_param.name.to_lower_camel_case();
            out.push_str(&format!(", {} {}", java_type, param_name));
        }

        out.push_str(") {\n");
        out.push_str("        try {\n");

        // Build upcall stub from the handler functional interface
        // The C FFI callback signature is: fn(*mut c_void, *const c_char) -> *mut c_char
        // Marshalling: C *const char -> Java String -> handler.handle() -> String -> C *mut char
        out.push_str("            // Wrap Java handler in an upcall stub for C to invoke\n");
        out.push_str("            MethodHandles.Lookup lookup = MethodHandles.lookup();\n");
        out.push_str("            MethodHandle mh = lookup.findVirtual(Callable.class, \"handle\",\n");
        out.push_str("                MethodType.methodType(String.class, String.class));\n");
        out.push_str("            MethodHandle boundMh = mh.bindTo(handler);\n\n");

        out.push_str("            // Build C FFI signature: (context: ADDRESS, request: ADDRESS) -> ADDRESS\n");
        out.push_str("            FunctionDescriptor upcallDesc = FunctionDescriptor.of(\n");
        out.push_str("                ValueLayout.ADDRESS,  // return: *mut c_char\n");
        out.push_str("                ValueLayout.ADDRESS,  // param 0: *mut c_void (context)\n");
        out.push_str("                ValueLayout.ADDRESS   // param 1: *const c_char (request JSON)\n");
        out.push_str("            );\n\n");

        out.push_str(
            "            // Create adapter: (context_ptr: ADDRESS, request_ptr: ADDRESS) -> response_ptr: ADDRESS\n",
        );
        out.push_str("            // Marshals C pointers <-> Java strings via Arena\n");
        out.push_str("            MethodHandle baseMh = lookup.findStatic(");
        out.push_str(&format!("{}.class, ", class_name));
        out.push_str("\"invokeHandlerWithMarshal\",\n");
        out.push_str("                MethodType.methodType(MemorySegment.class, MemorySegment.class, MemorySegment.class, Callable.class, Arena.class)\n");
        out.push_str("            );\n");
        out.push_str(
            "            MethodHandle adapter = MethodHandles.insertArguments(baseMh, 2, handler, arena);\n\n",
        );

        out.push_str("            MemorySegment upcallStub = LINKER.upcallStub(adapter, upcallDesc, arena);\n\n");

        out.push_str("            // Get register downcall handle\n");
        out.push_str(&format!(
            "            MemorySegment regAddr = LOOKUP.find(\"{}_{}_register_{}\")\n",
            ffi_prefix, service_snake, reg_method_snake
        ));
        out.push_str(&format!(
            "                .or(() -> LOOKUP.find(\"_{}_{}_register_{}\"))\n",
            ffi_prefix, service_snake, reg_method_snake
        ));
        out.push_str("                .orElseThrow();\n");

        // Build function descriptor for register call
        out.push_str("            FunctionDescriptor regDesc = FunctionDescriptor.of(\n");
        out.push_str("                ValueLayout.JAVA_INT,  // return: int\n");
        out.push_str("                ValueLayout.ADDRESS,   // owner: *mut opaque\n");
        out.push_str("                ValueLayout.ADDRESS    // callback: upcall stub\n");

        // Add metadata params to descriptor
        for meta_param in &reg.metadata_params {
            match &meta_param.ty {
                TypeRef::String => {
                    out.push_str(",\n                ValueLayout.ADDRESS    // ");
                }
                TypeRef::Primitive(p) => {
                    use crate::core::ir::PrimitiveType;
                    let layout = match p {
                        PrimitiveType::Bool => "ValueLayout.JAVA_INT",
                        PrimitiveType::U8 | PrimitiveType::I8 => "ValueLayout.JAVA_BYTE",
                        PrimitiveType::U16 | PrimitiveType::I16 => "ValueLayout.JAVA_SHORT",
                        PrimitiveType::U32 | PrimitiveType::I32 => "ValueLayout.JAVA_INT",
                        PrimitiveType::U64 | PrimitiveType::I64 => "ValueLayout.JAVA_LONG",
                        PrimitiveType::F32 => "ValueLayout.JAVA_FLOAT",
                        PrimitiveType::F64 => "ValueLayout.JAVA_DOUBLE",
                        PrimitiveType::Usize | PrimitiveType::Isize => "ValueLayout.ADDRESS",
                    };
                    out.push_str(&format!(",\n                {}    // ", layout));
                }
                _ => {
                    // Named types (opaque handles) and other complex types use ADDRESS
                    out.push_str(",\n                ValueLayout.ADDRESS    // ");
                }
            }
            out.push_str(&meta_param.name.to_lower_camel_case());
            out.push_str(" param\n");
        }

        out.push_str("            );\n");
        out.push_str("            MethodHandle regHandle = LINKER.downcallHandle(regAddr, regDesc);\n\n");

        // Invoke the register function directly with invokeExact
        out.push_str("            return (int) regHandle.invokeExact(\n");
        out.push_str("                ownerHandle,     // owner\n");
        out.push_str("                upcallStub       // callback\n");

        for meta_param in &reg.metadata_params {
            let param_name = meta_param.name.to_lower_camel_case();
            if is_opaque_metadata(&meta_param.ty, api) {
                // Opaque types pass the MemorySegment handle
                out.push_str(&format!(
                    ",\n                {}.handle()    // opaque handle",
                    param_name
                ));
            } else if matches!(meta_param.ty, TypeRef::Primitive(crate::core::ir::PrimitiveType::Bool)) {
                out.push_str(&format!(",\n                ({} ? 1 : 0)    // metadata", param_name));
            } else {
                // String/primitive/other types pass directly
                out.push_str(&format!(",\n                {}    // metadata", param_name));
            }
        }

        out.push_str("\n            );\n");
        out.push_str("        } catch (Throwable e) {\n");
        out.push_str("            throw new RuntimeException(\"Failed to register handler\", e);\n");
        out.push_str("        }\n");
        out.push_str("    }\n\n");
    }

    // Registration variant methods
    for reg in &service.registrations {
        let reg_method_snake = reg.method.to_snake_case();
        for variant in &reg.variants {
            let variant_method_name = variant.name.to_lower_camel_case();
            let ffi_symbol = format!(
                "{}_{}_register_{}_{}",
                ffi_prefix,
                service_snake,
                reg_method_snake,
                variant.name.to_snake_case()
            );
            let doc = variant.doc.clone();

            let ctx = context! {
                method_name => variant_method_name.clone(),
                variant_name_display => variant.name.to_lower_camel_case(),
                ffi_symbol => ffi_symbol.clone(),
                doc => doc,
            };

            let rendered = template_env::render("registration_variant.java.jinja", ctx);
            out.push_str(&rendered);
            out.push_str("\n\n");
        }
    }

    // Entrypoint methods
    for ep in &service.entrypoints {
        let ep_method = &ep.method;
        let ep_method_snake = ep_method.to_snake_case();

        out.push_str("    /**\n");
        out.push_str(&format!("     * {}.\n", ep_method));
        out.push_str(&format!(
            "     * Invokes C FFI: {}_{}_ep_{}\n",
            ffi_prefix, service_snake, ep_method_snake
        ));
        out.push_str("     */\n");

        let return_type = match ep.kind {
            EntrypointKind::Run => "void",
            EntrypointKind::Finalize => "long",
        };

        out.push_str(&format!("    public {} {}(", return_type, ep_method));

        // Add entrypoint parameters
        for (i, param) in ep.params.iter().enumerate() {
            if i > 0 {
                out.push_str(", ");
            }
            let java_type = java_type_for_metadata(&param.ty, api);
            let param_name = param.name.to_lower_camel_case();
            out.push_str(&format!("{} {}", java_type, param_name));
        }

        out.push_str(") {\n");
        out.push_str("        try {\n");

        out.push_str(&format!(
            "            MemorySegment epAddr = LOOKUP.find(\"{}_{}_ep_{}\")\n",
            ffi_prefix, service_snake, ep_method_snake
        ));
        out.push_str(&format!(
            "                .or(() -> LOOKUP.find(\"_{}_{}_ep_{}\"))\n",
            ffi_prefix, service_snake, ep_method_snake
        ));
        out.push_str("                .orElseThrow();\n");

        // Build FunctionDescriptor for entrypoint
        out.push_str("            FunctionDescriptor epDesc = FunctionDescriptor.of(\n");
        match ep.kind {
            EntrypointKind::Run => {
                out.push_str("                ValueLayout.JAVA_INT,    // return int (status)\n");
            }
            EntrypointKind::Finalize => {
                out.push_str("                ValueLayout.ADDRESS,     // return *mut opaque or int status\n");
            }
        }
        out.push_str("                ValueLayout.ADDRESS       // owner: *mut opaque\n");

        // Add entrypoint params to descriptor
        for param in &ep.params {
            match &param.ty {
                TypeRef::String => {
                    out.push_str(",\n                ValueLayout.ADDRESS    // ");
                }
                TypeRef::Primitive(p) => {
                    use crate::core::ir::PrimitiveType;
                    let layout = match p {
                        PrimitiveType::Bool => "ValueLayout.JAVA_INT",
                        PrimitiveType::U8 | PrimitiveType::I8 => "ValueLayout.JAVA_BYTE",
                        PrimitiveType::U16 | PrimitiveType::I16 => "ValueLayout.JAVA_SHORT",
                        PrimitiveType::U32 | PrimitiveType::I32 => "ValueLayout.JAVA_INT",
                        PrimitiveType::U64 | PrimitiveType::I64 => "ValueLayout.JAVA_LONG",
                        PrimitiveType::F32 => "ValueLayout.JAVA_FLOAT",
                        PrimitiveType::F64 => "ValueLayout.JAVA_DOUBLE",
                        PrimitiveType::Usize | PrimitiveType::Isize => "ValueLayout.ADDRESS",
                    };
                    out.push_str(&format!(",\n                {}    // ", layout));
                }
                _ => {
                    // Named types (opaque handles) use ADDRESS
                    out.push_str(",\n                ValueLayout.ADDRESS    // ");
                }
            }
            out.push_str(&param.name.to_lower_camel_case());
            out.push_str(" param\n");
        }

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

        out.push_str("            MethodHandle epHandle = LINKER.downcallHandle(epAddr, epDesc);\n");

        match ep.kind {
            EntrypointKind::Run => {
                out.push_str("            epHandle.invoke(ownerHandle");
            }
            EntrypointKind::Finalize => {
                out.push_str("            return (long) epHandle.invoke(ownerHandle");
            }
        }

        // Pass entrypoint arguments
        for param in &ep.params {
            let param_name = param.name.to_lower_camel_case();
            if is_opaque_metadata(&param.ty, api) {
                // Opaque types pass the MemorySegment handle
                out.push_str(&format!(", {}.handle()", param_name));
            } else if matches!(param.ty, TypeRef::Primitive(crate::core::ir::PrimitiveType::Bool)) {
                out.push_str(&format!(", ({} ? 1 : 0)", param_name));
            } else {
                // String/primitive/other types pass directly
                out.push_str(&format!(", {}", param_name));
            }
        }

        out.push_str(");\n");
        out.push_str("        } catch (Throwable e) {\n");
        out.push_str("            throw new RuntimeException(\"Failed to invoke entrypoint\", e);\n");
        out.push_str("        }\n");
        out.push_str("    }\n\n");
    }

    // AutoCloseable implementation
    out.push_str("    @Override\n");
    out.push_str("    public void close() {\n");
    out.push_str("        try {\n");
    out.push_str(&format!(
        "            MemorySegment freeAddr = LOOKUP.find(\"{}_{}_free\")\n",
        ffi_prefix, service_snake
    ));
    out.push_str(&format!(
        "                .or(() -> LOOKUP.find(\"_{}_{}_free\"))\n",
        ffi_prefix, service_snake
    ));
    out.push_str("                .orElseThrow();\n");
    out.push_str("            FunctionDescriptor freeDesc = FunctionDescriptor.ofVoid(ValueLayout.ADDRESS);\n");
    out.push_str("            MethodHandle freeHandle = LINKER.downcallHandle(freeAddr, freeDesc);\n");
    out.push_str("            if (ownerHandle != null) {\n");
    out.push_str("                freeHandle.invoke(ownerHandle);\n");
    out.push_str("                ownerHandle = null;\n");
    out.push_str("            }\n");
    out.push_str("            arena.close();\n");
    out.push_str("        } catch (Throwable e) {\n");
    out.push_str("            throw new RuntimeException(\"Failed to close service\", e);\n");
    out.push_str("        }\n");
    out.push_str("    }\n");

    out.push_str("}\n");

    out
}

/// Generate the @FunctionalInterface Callable interface.
///
/// A simple interface that handlers must implement to be passed to registration methods.
fn gen_callable_interface(package: &str) -> String {
    let mut out = String::new();

    out.push_str("// Auto-generated by alef — DO NOT EDIT\n\n");
    out.push_str(&format!("package {};\n\n", package));

    out.push_str("/**\n");
    out.push_str(" * Functional interface for service handlers.\n");
    out.push_str(" *\n");
    out.push_str(" * Implementations receive a JSON request string and return a JSON response string.\n");
    out.push_str(" */\n");
    out.push_str("@FunctionalInterface\n");
    out.push_str("public interface Callable {\n");
    out.push_str("    /**\n");
    out.push_str("     * Handle a request.\n");
    out.push_str("     *\n");
    out.push_str("     * @param request JSON request string\n");
    out.push_str("     * @return JSON response string\n");
    out.push_str("     */\n");
    out.push_str("    String handle(String request);\n");
    out.push_str("}\n");

    out
}

// ──────────────────────────────────────────────── public entry point ──

/// Generate all service-API files for the Java backend.
///
/// Returns Java source files using Panama FFM:
/// - One service class per [`ServiceDef`] (Panama downcalls + upcalls)
/// - One Callable interface (shared)
pub fn generate(api: &ApiSurface, config: &ResolvedCrateConfig) -> anyhow::Result<Vec<GeneratedFile>> {
    if api.services.is_empty() {
        return Ok(vec![]);
    }

    let package = config.java_package();
    let package_path = package.replace('.', "/");

    let output_dir = config
        .output_for("java")
        .map(|p| p.to_string_lossy().into_owned())
        .unwrap_or_else(|| "packages/java/src/main/java/".to_string());

    let base_path = if output_dir.ends_with(&package_path) || output_dir.ends_with(&format!("{}/", package_path)) {
        PathBuf::from(&output_dir)
    } else {
        PathBuf::from(&output_dir).join(&package_path)
    };

    let mut files = Vec::new();

    // Generate one service class per service (Panama FFM downcalls + upcalls)
    for service in &api.services {
        let service_class = gen_service_class(api, service, &package, config);
        files.push(GeneratedFile {
            path: base_path.join(format!("{}.java", service.name)),
            content: service_class,
            generated_header: false, // Header already included
        });
    }

    // Generate Callable interface (once, shared across all services)
    files.push(GeneratedFile {
        path: base_path.join("Callable.java"),
        content: gen_callable_interface(&package),
        generated_header: false,
    });

    Ok(files)
}

// ───────────────────────────────────────────────────────────────────── tests ──

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::ir::{
        EntrypointDef, EntrypointKind, HandlerContractDef, MethodDef, ParamDef, RegistrationDef, ServiceDef, TypeRef,
    };

    /// Construct a minimal but realistic [`ApiSurface`] that exercises:
    /// - A service with a constructor, one registration, and Run entrypoint
    /// - One [`HandlerContractDef`] with wire request/response DTO names
    fn make_fixture_surface() -> ApiSurface {
        let constructor = MethodDef {
            name: "new".to_owned(),
            params: vec![],
            return_type: TypeRef::Unit,
            is_async: false,
            is_static: true,
            error_type: None,
            doc: "Create a new service owner.".to_owned(),
            receiver: None,
            sanitized: false,
            trait_source: None,
            returns_ref: false,
            returns_cow: false,
            return_newtype_wrapper: None,
            has_default_impl: false,
            binding_excluded: false,
            binding_exclusion_reason: None,
        };

        let registration = RegistrationDef {
            method: "add_handler".to_owned(),
            callback_param: "handler".to_owned(),
            callback_contract: "RequestHandler".to_owned(),
            metadata_params: vec![ParamDef {
                name: "path".to_owned(),
                ty: TypeRef::String,
                optional: false,
                default: None,
                ..ParamDef::default()
            }],
            receiver: Some(crate::core::ir::ReceiverKind::RefMut),
            return_type: TypeRef::Unit,
            error_type: None,
            doc: "Register a request handler.".to_owned(),
            variants: vec![
                crate::core::ir::RegistrationVariant {
                    name: "get".to_owned(),
                    overrides: vec![],
                    wrapper_call: None,
                    signature_params: vec![],
                    doc: Some("Register a GET handler.".to_owned()),
                    style: Default::default(),
                },
                crate::core::ir::RegistrationVariant {
                    name: "post".to_owned(),
                    overrides: vec![],
                    wrapper_call: None,
                    signature_params: vec![],
                    doc: Some("Register a POST handler.".to_owned()),
                    style: Default::default(),
                },
            ],
        };

        let run_ep = EntrypointDef {
            method: "run".to_owned(),
            kind: EntrypointKind::Run,
            is_async: true,
            params: vec![ParamDef {
                name: "addr".to_owned(),
                ty: TypeRef::String,
                optional: false,
                default: None,
                ..ParamDef::default()
            }],
            return_type: TypeRef::Unit,
            error_type: Some("ServiceError".to_owned()),
            doc: "Run the service.".to_owned(),
        };

        let service = ServiceDef {
            name: "TestService".to_owned(),
            rust_path: "my_crate::TestService".to_owned(),
            constructor,
            configurators: vec![],
            registrations: vec![registration],
            entrypoints: vec![run_ep],
            doc: "A test service owner.".to_owned(),
            cfg: None,
        };

        let dispatch_method = MethodDef {
            name: "handle".to_owned(),
            params: vec![ParamDef {
                name: "request".to_owned(),
                ty: TypeRef::Named("RequestData".to_owned()),
                optional: false,
                default: None,
                ..ParamDef::default()
            }],
            return_type: TypeRef::Named("ResponseData".to_owned()),
            is_async: true,
            is_static: false,
            error_type: Some("HandlerError".to_owned()),
            doc: "Dispatch a request.".to_owned(),
            receiver: Some(crate::core::ir::ReceiverKind::Ref),
            sanitized: false,
            trait_source: None,
            returns_ref: false,
            returns_cow: false,
            return_newtype_wrapper: None,
            has_default_impl: false,
            binding_excluded: false,
            binding_exclusion_reason: None,
        };

        let contract = HandlerContractDef {
            trait_name: "RequestHandler".to_owned(),
            rust_path: "my_crate::RequestHandler".to_owned(),
            dispatch: dispatch_method,
            optional_methods: vec![],
            wire_request_type: Some("RequestData".to_owned()),
            wire_response_type: Some("ResponseData".to_owned()),
            dispatch_extra_params: vec![],
            wire_param_name: None,
            dispatch_return_type: None,
            response_adapter: None,
            doc: "Async trait for handling requests.".to_owned(),
        };

        ApiSurface {
            crate_name: "my_crate".to_owned(),
            version: "0.1.0".to_owned(),
            services: vec![service],
            handler_contracts: vec![contract],
            ..ApiSurface::default()
        }
    }

    fn make_test_config() -> ResolvedCrateConfig {
        // `ffi_prefix()` derives from `name` (hyphens → underscores) when `[ffi] prefix`
        // is unset, so `test-crate` yields the prefix `test_crate`.
        ResolvedCrateConfig {
            name: "test-crate".to_owned(),
            ..ResolvedCrateConfig::default()
        }
    }

    #[test]
    fn java_class_uses_panama_ffm() {
        let surface = make_fixture_surface();
        let config = make_test_config();
        let java = gen_service_class(&surface, &surface.services[0], "com.example", &config);

        // Verify Panama FFM imports and patterns
        assert!(java.contains("import java.lang.foreign.*;"), "should import Panama FFM");
        assert!(java.contains("Linker.nativeLinker()"), "should use Linker");
        assert!(java.contains("downcallHandle"), "should use downcalls");
        assert!(java.contains("SymbolLookup"), "should lookup C symbols");
        assert!(java.contains("FunctionDescriptor"), "should build function descriptors");
        assert!(java.contains("MemorySegment"), "should use MemorySegment");
        assert!(java.contains("Arena"), "should use Arena for lifetime management");
    }

    #[test]
    fn java_class_contains_service_class() {
        let surface = make_fixture_surface();
        let config = make_test_config();
        let java = gen_service_class(&surface, &surface.services[0], "com.example", &config);

        assert!(java.contains("public class TestService"));
        assert!(java.contains("implements AutoCloseable"));
        assert!(java.contains("private MemorySegment ownerHandle"));
    }

    #[test]
    fn java_class_constructor_uses_downcall() {
        let surface = make_fixture_surface();
        let config = make_test_config();
        let java = gen_service_class(&surface, &surface.services[0], "com.example", &config);

        assert!(java.contains("public TestService()"));
        assert!(
            java.contains("test_crate_test_service_new"),
            "constructor should bind to C symbol"
        );
        assert!(
            java.contains("LINKER.downcallHandle"),
            "constructor should use downcall"
        );
    }

    #[test]
    fn java_class_contains_upcall_stub_for_handler() {
        let surface = make_fixture_surface();
        let config = make_test_config();
        let java = gen_service_class(&surface, &surface.services[0], "com.example", &config);

        assert!(
            java.contains("LINKER.upcallStub"),
            "registration should build upcall stub for handler"
        );
        assert!(java.contains("MethodHandle"), "should use MethodHandle to wrap handler");
    }

    #[test]
    fn java_class_registration_binds_to_c_symbol() {
        let surface = make_fixture_surface();
        let config = make_test_config();
        let java = gen_service_class(&surface, &surface.services[0], "com.example", &config);

        assert!(
            java.contains("test_crate_test_service_register_add_handler"),
            "registration should bind to exact C FFI symbol"
        );
    }

    #[test]
    fn java_class_entrypoint_uses_downcall() {
        let surface = make_fixture_surface();
        let config = make_test_config();
        let java = gen_service_class(&surface, &surface.services[0], "com.example", &config);

        assert!(java.contains("public void run(String addr)"));
        assert!(
            java.contains("test_crate_test_service_ep_run"),
            "entrypoint should bind to C symbol"
        );
        assert!(java.contains("LINKER.downcallHandle"), "entrypoint should use downcall");
    }

    #[test]
    fn java_class_close_frees_via_downcall() {
        let surface = make_fixture_surface();
        let config = make_test_config();
        let java = gen_service_class(&surface, &surface.services[0], "com.example", &config);

        assert!(java.contains("@Override"));
        assert!(java.contains("public void close()"));
        assert!(
            java.contains("test_crate_test_service_free"),
            "close should bind to C symbol"
        );
        assert!(java.contains("LINKER.downcallHandle"), "close should use downcall");
        assert!(java.contains("arena.close()"), "arena lifetime should be managed");
    }

    #[test]
    fn java_class_no_native_method_declarations() {
        let surface = make_fixture_surface();
        let config = make_test_config();
        let java = gen_service_class(&surface, &surface.services[0], "com.example", &config);

        assert!(
            !java.contains("native "),
            "should not contain JNI native method declarations"
        );
        assert!(
            !java.contains("System.loadLibrary"),
            "should not load library (Panama manages it)"
        );
        assert!(!java.contains("Java_"), "should not contain Java_ JNI symbols");
    }

    #[test]
    fn callable_interface_is_functional() {
        let iface = gen_callable_interface("com.example");

        assert!(iface.contains("@FunctionalInterface"));
        assert!(iface.contains("public interface Callable"));
        assert!(iface.contains("String handle(String request)"));
    }

    #[test]
    fn generate_returns_service_and_callable() {
        let surface = make_fixture_surface();
        let config = make_test_config();

        let files = generate(&surface, &config).expect("generate should not fail");
        assert!(files.len() >= 2, "expected at least service class + Callable interface");

        let has_service_class = files
            .iter()
            .any(|f| f.path.to_string_lossy().contains("TestService.java"));
        let has_callable = files.iter().any(|f| f.path.to_string_lossy().contains("Callable.java"));

        assert!(has_service_class, "expected TestService.java");
        assert!(has_callable, "expected Callable.java");
    }

    #[test]
    fn generate_returns_empty_for_no_services() {
        let surface = ApiSurface::default();
        let config = make_test_config();

        let files = generate(&surface, &config).expect("generate should not fail");
        assert!(files.is_empty(), "expected no files for surface without services");
    }

    #[test]
    fn java_class_passes_all_metadata_params() {
        let mut surface = make_fixture_surface();
        let reg = &mut surface.services[0].registrations[0];

        // Add more metadata parameters
        reg.metadata_params.push(ParamDef {
            name: "method".to_owned(),
            ty: TypeRef::String,
            optional: false,
            default: None,
            ..ParamDef::default()
        });
        reg.metadata_params.push(ParamDef {
            name: "priority".to_owned(),
            ty: TypeRef::Primitive(crate::core::ir::PrimitiveType::I32),
            optional: false,
            default: None,
            ..ParamDef::default()
        });

        let config = make_test_config();
        let java = gen_service_class(&surface, &surface.services[0], "com.example", &config);

        // Check that the method signature includes all params
        assert!(
            java.contains("public int registerTestServiceAddHandler(Callable handler, String path"),
            "registration method must include all metadata parameters"
        );

        // Check that metadata params are part of function descriptor
        assert!(
            java.contains("ValueLayout.ADDRESS") || java.contains("ValueLayout.JAVA_INT"),
            "registration should build FunctionDescriptor with metadata param layouts"
        );
    }

    #[test]
    fn java_class_emits_registration_variants() {
        let surface = make_fixture_surface();
        let config = make_test_config();
        let java = gen_service_class(&surface, &surface.services[0], "com.example", &config);

        // Verify variant methods are emitted
        assert!(
            java.contains("public int get(String path, Callable handler)"),
            "should emit get variant method"
        );
        assert!(
            java.contains("public int post(String path, Callable handler)"),
            "should emit post variant method"
        );

        // Verify variant C symbols are correctly formed
        assert!(
            java.contains("test_crate_test_service_register_add_handler_get"),
            "should bind get variant to correct C symbol"
        );
        assert!(
            java.contains("test_crate_test_service_register_add_handler_post"),
            "should bind post variant to correct C symbol"
        );

        // Verify variant methods use Panama FFM
        assert!(
            java.contains("LINKER.downcallHandle"),
            "variant methods should use Panama downcalls"
        );
        assert!(
            java.contains("LINKER.upcallStub"),
            "variant methods should create upcall stubs"
        );
        assert!(
            java.contains("FunctionDescriptor.of"),
            "variant methods should build function descriptors"
        );
    }
}