Skip to main content

alef_backend_java/
gen_bindings.rs

1use crate::type_map::{java_boxed_type, java_ffi_type, java_type};
2use ahash::AHashSet;
3use alef_codegen::naming::{to_class_name, to_java_name};
4use alef_core::backend::{Backend, BuildConfig, Capabilities, GeneratedFile};
5use alef_core::config::{AlefConfig, Language, resolve_output_dir};
6use alef_core::ir::{ApiSurface, EnumDef, FunctionDef, PrimitiveType, TypeDef, TypeRef};
7use heck::{ToLowerCamelCase, ToPascalCase, ToSnakeCase};
8use std::fmt::Write;
9use std::path::PathBuf;
10
11/// Names that conflict with methods on `java.lang.Object` and are therefore
12/// illegal as record component names or method names in generated Java code.
13const JAVA_OBJECT_METHOD_NAMES: &[&str] = &[
14    "wait",
15    "notify",
16    "notifyAll",
17    "getClass",
18    "hashCode",
19    "equals",
20    "toString",
21    "clone",
22    "finalize",
23];
24
25/// Sanitise a field/parameter name that would conflict with `java.lang.Object`
26/// methods.  Conflicting names get a `_` suffix (e.g. `wait` -> `wait_`), which
27/// is then converted to camelCase by `to_java_name`.
28fn safe_java_field_name(name: &str) -> String {
29    let java_name = to_java_name(name);
30    if JAVA_OBJECT_METHOD_NAMES.contains(&java_name.as_str()) {
31        format!("{}Value", java_name)
32    } else {
33        java_name
34    }
35}
36
37pub struct JavaBackend;
38
39impl JavaBackend {
40    /// Convert crate name to main class name (PascalCase + "Rs" suffix).
41    ///
42    /// The "Rs" suffix ensures the raw FFI wrapper class has a distinct name from
43    /// the public facade class (which strips the "Rs" suffix). Without this, the
44    /// facade would delegate to itself, causing infinite recursion.
45    fn resolve_main_class(api: &ApiSurface) -> String {
46        let base = to_class_name(&api.crate_name.replace('-', "_"));
47        if base.ends_with("Rs") {
48            base
49        } else {
50            format!("{}Rs", base)
51        }
52    }
53}
54
55impl Backend for JavaBackend {
56    fn name(&self) -> &str {
57        "java"
58    }
59
60    fn language(&self) -> Language {
61        Language::Java
62    }
63
64    fn capabilities(&self) -> Capabilities {
65        Capabilities {
66            supports_async: true,
67            supports_classes: true,
68            supports_enums: true,
69            supports_option: true,
70            supports_result: true,
71            ..Capabilities::default()
72        }
73    }
74
75    fn generate_bindings(&self, api: &ApiSurface, config: &AlefConfig) -> anyhow::Result<Vec<GeneratedFile>> {
76        let package = config.java_package();
77        let prefix = config.ffi_prefix();
78        let main_class = Self::resolve_main_class(api);
79        let package_path = package.replace('.', "/");
80
81        let output_dir = resolve_output_dir(
82            config.output.java.as_ref(),
83            &config.crate_config.name,
84            "packages/java/src/main/java/",
85        );
86
87        let base_path = PathBuf::from(&output_dir).join(&package_path);
88
89        let mut files = Vec::new();
90
91        // 0. package-info.java - required by Checkstyle
92        let description = config
93            .scaffold
94            .as_ref()
95            .and_then(|s| s.description.as_deref())
96            .unwrap_or("High-performance HTML to Markdown converter.");
97        files.push(GeneratedFile {
98            path: base_path.join("package-info.java"),
99            content: format!(
100                "/**\n * {description}\n */\npackage {package};\n",
101                description = description,
102                package = package,
103            ),
104            generated_header: true,
105        });
106
107        // 1. NativeLib.java - FFI method handles
108        files.push(GeneratedFile {
109            path: base_path.join("NativeLib.java"),
110            content: gen_native_lib(api, config, &package, &prefix),
111            generated_header: true,
112        });
113
114        // 2. Main wrapper class
115        files.push(GeneratedFile {
116            path: base_path.join(format!("{}.java", main_class)),
117            content: gen_main_class(api, config, &package, &main_class, &prefix),
118            generated_header: true,
119        });
120
121        // 3. Exception class
122        files.push(GeneratedFile {
123            path: base_path.join(format!("{}Exception.java", main_class)),
124            content: gen_exception_class(&package, &main_class),
125            generated_header: true,
126        });
127
128        // Collect complex enums (enums with data variants and no serde tag) — use Object for these fields.
129        // Tagged unions (serde_tag is set) are now generated as proper sealed interfaces
130        // and can be deserialized as their concrete types, so they are NOT complex_enums.
131        let complex_enums: AHashSet<String> = api
132            .enums
133            .iter()
134            .filter(|e| e.serde_tag.is_none() && e.variants.iter().any(|v| !v.fields.is_empty()))
135            .map(|e| e.name.clone())
136            .collect();
137
138        // Resolve language-level serde rename strategy (always wins over IR type-level).
139        let lang_rename_all = config.serde_rename_all_for_language(Language::Java);
140
141        // 4. Record types
142        for typ in &api.types {
143            if !typ.is_opaque && !typ.fields.is_empty() {
144                files.push(GeneratedFile {
145                    path: base_path.join(format!("{}.java", typ.name)),
146                    content: gen_record_type(&package, typ, &complex_enums, &lang_rename_all),
147                    generated_header: true,
148                });
149                // Generate builder class for types with defaults
150                if typ.has_default {
151                    files.push(GeneratedFile {
152                        path: base_path.join(format!("{}Builder.java", typ.name)),
153                        content: gen_builder_class(&package, typ),
154                        generated_header: true,
155                    });
156                }
157            }
158        }
159
160        // Collect builder class names generated from record types with defaults,
161        // so we can skip opaque types that would collide with them.
162        let builder_class_names: AHashSet<String> = api
163            .types
164            .iter()
165            .filter(|t| !t.is_opaque && !t.fields.is_empty() && t.has_default)
166            .map(|t| format!("{}Builder", t.name))
167            .collect();
168
169        // 4b. Opaque handle types (skip if a pure-Java builder already covers this name)
170        for typ in &api.types {
171            if typ.is_opaque && !builder_class_names.contains(&typ.name) {
172                files.push(GeneratedFile {
173                    path: base_path.join(format!("{}.java", typ.name)),
174                    content: gen_opaque_handle_class(&package, typ, &prefix),
175                    generated_header: true,
176                });
177            }
178        }
179
180        // 5. Enums
181        for enum_def in &api.enums {
182            files.push(GeneratedFile {
183                path: base_path.join(format!("{}.java", enum_def.name)),
184                content: gen_enum_class(&package, enum_def),
185                generated_header: true,
186            });
187        }
188
189        // 6. Error exception classes
190        for error in &api.errors {
191            for (class_name, content) in alef_codegen::error_gen::gen_java_error_types(error, &package) {
192                files.push(GeneratedFile {
193                    path: base_path.join(format!("{}.java", class_name)),
194                    content,
195                    generated_header: true,
196                });
197            }
198        }
199
200        // Build adapter body map (consumed by generators via body substitution)
201        let _adapter_bodies = alef_adapters::build_adapter_bodies(config, Language::Java)?;
202
203        Ok(files)
204    }
205
206    fn generate_public_api(&self, api: &ApiSurface, config: &AlefConfig) -> anyhow::Result<Vec<GeneratedFile>> {
207        let package = config.java_package();
208        let prefix = config.ffi_prefix();
209        let main_class = Self::resolve_main_class(api);
210        let package_path = package.replace('.', "/");
211
212        let output_dir = resolve_output_dir(
213            config.output.java.as_ref(),
214            &config.crate_config.name,
215            "packages/java/src/main/java/",
216        );
217
218        let base_path = PathBuf::from(&output_dir).join(&package_path);
219
220        // Generate a high-level public API class that wraps the raw FFI class.
221        // Class name = main_class without "Rs" suffix (e.g., HtmlToMarkdownRs -> HtmlToMarkdown)
222        let public_class = main_class.trim_end_matches("Rs").to_string();
223        let facade_content = gen_facade_class(api, &package, &public_class, &main_class, &prefix);
224
225        Ok(vec![GeneratedFile {
226            path: base_path.join(format!("{}.java", public_class)),
227            content: facade_content,
228            generated_header: true,
229        }])
230    }
231
232    fn build_config(&self) -> Option<BuildConfig> {
233        Some(BuildConfig {
234            tool: "mvn",
235            crate_suffix: "",
236            depends_on_ffi: true,
237            post_build: vec![],
238        })
239    }
240}
241
242// ---------------------------------------------------------------------------
243// NativeLib.java - FFI method handles
244// ---------------------------------------------------------------------------
245
246fn gen_native_lib(api: &ApiSurface, config: &AlefConfig, package: &str, prefix: &str) -> String {
247    // Generate the class body first, then scan it to determine which imports are needed.
248    let mut body = String::with_capacity(2048);
249    // Derive the native library name from the FFI output path (directory name with hyphens replaced
250    // by underscores), falling back to `{ffi_prefix}_ffi`.
251    let lib_name = config.ffi_lib_name();
252
253    writeln!(body, "final class NativeLib {{").ok();
254    writeln!(body, "    private static final Linker LINKER = Linker.nativeLinker();").ok();
255    writeln!(body, "    private static final SymbolLookup LIB;").ok();
256    writeln!(body).ok();
257    writeln!(body, "    static {{").ok();
258    writeln!(body, "        System.loadLibrary(\"{}\");", lib_name).ok();
259    writeln!(body, "        LIB = SymbolLookup.loaderLookup();").ok();
260    writeln!(body, "    }}").ok();
261    writeln!(body).ok();
262
263    // Generate method handles for free functions.
264    // All functions get handles regardless of is_async — the FFI layer always exposes
265    // synchronous C functions, and the Java async wrapper delegates to the sync method.
266    for func in &api.functions {
267        let ffi_name = format!("{}_{}", prefix, func.name.to_lowercase());
268        let return_layout = gen_ffi_layout(&func.return_type);
269        let param_layouts: Vec<String> = func.params.iter().map(|p| gen_ffi_layout(&p.ty)).collect();
270
271        let layout_str = gen_function_descriptor(&return_layout, &param_layouts);
272
273        let handle_name = format!("{}_{}", prefix.to_uppercase(), func.name.to_uppercase());
274
275        writeln!(
276            body,
277            "    static final MethodHandle {} = LINKER.downcallHandle(",
278            handle_name
279        )
280        .ok();
281        writeln!(body, "        LIB.find(\"{}\").orElseThrow(),", ffi_name).ok();
282        writeln!(body, "        {}", layout_str).ok();
283        writeln!(body, "    );").ok();
284    }
285
286    // free_string handle for releasing FFI-allocated strings
287    {
288        let free_name = format!("{}_free_string", prefix);
289        let handle_name = format!("{}_FREE_STRING", prefix.to_uppercase());
290        writeln!(body).ok();
291        writeln!(
292            body,
293            "    static final MethodHandle {} = LINKER.downcallHandle(",
294            handle_name
295        )
296        .ok();
297        writeln!(body, "        LIB.find(\"{}\").orElseThrow(),", free_name).ok();
298        writeln!(body, "        FunctionDescriptor.ofVoid(ValueLayout.ADDRESS)").ok();
299        writeln!(body, "    );").ok();
300    }
301
302    // Error handling — use the FFI's last_error_code and last_error_context symbols
303    {
304        writeln!(
305            body,
306            "    static final MethodHandle {}_LAST_ERROR_CODE = LINKER.downcallHandle(",
307            prefix.to_uppercase()
308        )
309        .ok();
310        writeln!(body, "        LIB.find(\"{}_last_error_code\").orElseThrow(),", prefix).ok();
311        writeln!(body, "        FunctionDescriptor.of(ValueLayout.JAVA_INT)").ok();
312        writeln!(body, "    );").ok();
313
314        writeln!(
315            body,
316            "    static final MethodHandle {}_LAST_ERROR_CONTEXT = LINKER.downcallHandle(",
317            prefix.to_uppercase()
318        )
319        .ok();
320        writeln!(
321            body,
322            "        LIB.find(\"{}_last_error_context\").orElseThrow(),",
323            prefix
324        )
325        .ok();
326        writeln!(body, "        FunctionDescriptor.of(ValueLayout.ADDRESS)").ok();
327        writeln!(body, "    );").ok();
328    }
329
330    // Track emitted free handles to avoid duplicates (a type may appear both as
331    // a function return type AND as an opaque type).
332    let mut emitted_free_handles: AHashSet<String> = AHashSet::new();
333
334    // Build the set of opaque type names so we can pick the right accessor below.
335    let opaque_type_names: AHashSet<String> = api
336        .types
337        .iter()
338        .filter(|t| t.is_opaque)
339        .map(|t| t.name.clone())
340        .collect();
341
342    // Accessor handles for Named return types (struct pointer → field accessor + free)
343    for func in &api.functions {
344        if let TypeRef::Named(name) = &func.return_type {
345            let type_snake = name.to_snake_case();
346            let type_upper = type_snake.to_uppercase();
347            let is_opaque = opaque_type_names.contains(name.as_str());
348
349            if is_opaque {
350                // Opaque handles: the caller wraps the pointer directly, no JSON needed.
351                // No content accessor is emitted for opaque types.
352            } else {
353                // Non-opaque record types: use _to_json to serialize the full struct to JSON,
354                // which the Java side then deserializes with ObjectMapper.
355                // NOTE: _content returns only the markdown string field, not the full JSON.
356                let to_json_handle = format!("{}_{}_TO_JSON", prefix.to_uppercase(), type_upper);
357                let to_json_ffi = format!("{}_{}_to_json", prefix, type_snake);
358                writeln!(body).ok();
359                writeln!(
360                    body,
361                    "    static final MethodHandle {} = LINKER.downcallHandle(",
362                    to_json_handle
363                )
364                .ok();
365                writeln!(body, "        LIB.find(\"{}\").orElseThrow(),", to_json_ffi).ok();
366                writeln!(
367                    body,
368                    "        FunctionDescriptor.of(ValueLayout.ADDRESS, ValueLayout.ADDRESS)"
369                )
370                .ok();
371                writeln!(body, "    );").ok();
372            }
373
374            // _free: (struct_ptr) -> void
375            let free_handle = format!("{}_{}_FREE", prefix.to_uppercase(), type_upper);
376            let free_ffi = format!("{}_{}_free", prefix, type_snake);
377            if emitted_free_handles.insert(free_handle.clone()) {
378                writeln!(body).ok();
379                writeln!(
380                    body,
381                    "    static final MethodHandle {} = LINKER.downcallHandle(",
382                    free_handle
383                )
384                .ok();
385                writeln!(body, "        LIB.find(\"{}\").orElseThrow(),", free_ffi).ok();
386                writeln!(body, "        FunctionDescriptor.ofVoid(ValueLayout.ADDRESS)").ok();
387                writeln!(body, "    );").ok();
388            }
389        }
390    }
391
392    // FROM_JSON + FREE handles for non-opaque Named types used as parameters.
393    // These allow serializing a Java record to JSON and passing it to the FFI.
394    let mut emitted_from_json_handles: AHashSet<String> = AHashSet::new();
395    for func in &api.functions {
396        for param in &func.params {
397            // Handle both Named and Optional<Named> params
398            let inner_name = match &param.ty {
399                TypeRef::Named(n) => Some(n.clone()),
400                TypeRef::Optional(inner) => {
401                    if let TypeRef::Named(n) = inner.as_ref() {
402                        Some(n.clone())
403                    } else {
404                        None
405                    }
406                }
407                _ => None,
408            };
409            if let Some(name) = inner_name {
410                if !opaque_type_names.contains(name.as_str()) {
411                    let type_snake = name.to_snake_case();
412                    let type_upper = type_snake.to_uppercase();
413
414                    // _from_json: (char*) -> struct_ptr
415                    let from_json_handle = format!("{}_{}_FROM_JSON", prefix.to_uppercase(), type_upper);
416                    let from_json_ffi = format!("{}_{}_from_json", prefix, type_snake);
417                    if emitted_from_json_handles.insert(from_json_handle.clone()) {
418                        writeln!(body).ok();
419                        writeln!(
420                            body,
421                            "    static final MethodHandle {} = LINKER.downcallHandle(",
422                            from_json_handle
423                        )
424                        .ok();
425                        writeln!(body, "        LIB.find(\"{}\").orElseThrow(),", from_json_ffi).ok();
426                        writeln!(
427                            body,
428                            "        FunctionDescriptor.of(ValueLayout.ADDRESS, ValueLayout.ADDRESS)"
429                        )
430                        .ok();
431                        writeln!(body, "    );").ok();
432                    }
433
434                    // _free: (struct_ptr) -> void
435                    let free_handle = format!("{}_{}_FREE", prefix.to_uppercase(), type_upper);
436                    let free_ffi = format!("{}_{}_free", prefix, type_snake);
437                    if emitted_free_handles.insert(free_handle.clone()) {
438                        writeln!(body).ok();
439                        writeln!(
440                            body,
441                            "    static final MethodHandle {} = LINKER.downcallHandle(",
442                            free_handle
443                        )
444                        .ok();
445                        writeln!(body, "        LIB.find(\"{}\").orElseThrow(),", free_ffi).ok();
446                        writeln!(body, "        FunctionDescriptor.ofVoid(ValueLayout.ADDRESS)").ok();
447                        writeln!(body, "    );").ok();
448                    }
449                }
450            }
451        }
452    }
453
454    // Collect builder class names from record types with defaults, so we skip
455    // opaque types that are superseded by a pure-Java builder class.
456    let builder_class_names: AHashSet<String> = api
457        .types
458        .iter()
459        .filter(|t| !t.is_opaque && !t.fields.is_empty() && t.has_default)
460        .map(|t| format!("{}Builder", t.name))
461        .collect();
462
463    // Free handles for opaque types (handle pointer → void)
464    for typ in &api.types {
465        if typ.is_opaque && !builder_class_names.contains(&typ.name) {
466            let type_snake = typ.name.to_snake_case();
467            let type_upper = type_snake.to_uppercase();
468            let free_handle = format!("{}_{}_FREE", prefix.to_uppercase(), type_upper);
469            let free_ffi = format!("{}_{}_free", prefix, type_snake);
470            if emitted_free_handles.insert(free_handle.clone()) {
471                writeln!(body).ok();
472                writeln!(
473                    body,
474                    "    static final MethodHandle {} = LINKER.downcallHandle(",
475                    free_handle
476                )
477                .ok();
478                writeln!(body, "        LIB.find(\"{}\").orElseThrow(),", free_ffi).ok();
479                writeln!(body, "        FunctionDescriptor.ofVoid(ValueLayout.ADDRESS)").ok();
480                writeln!(body, "    );").ok();
481            }
482        }
483    }
484
485    writeln!(body, "}}").ok();
486
487    // Now assemble the file with only the imports that are actually used in the body.
488    let mut out = String::with_capacity(body.len() + 512);
489
490    writeln!(out, "// DO NOT EDIT - auto-generated by alef").ok();
491    writeln!(out, "package {};", package).ok();
492    writeln!(out).ok();
493    if body.contains("Arena") {
494        writeln!(out, "import java.lang.foreign.Arena;").ok();
495    }
496    if body.contains("FunctionDescriptor") {
497        writeln!(out, "import java.lang.foreign.FunctionDescriptor;").ok();
498    }
499    if body.contains("Linker") {
500        writeln!(out, "import java.lang.foreign.Linker;").ok();
501    }
502    if body.contains("MemorySegment") {
503        writeln!(out, "import java.lang.foreign.MemorySegment;").ok();
504    }
505    if body.contains("SymbolLookup") {
506        writeln!(out, "import java.lang.foreign.SymbolLookup;").ok();
507    }
508    if body.contains("ValueLayout") {
509        writeln!(out, "import java.lang.foreign.ValueLayout;").ok();
510    }
511    if body.contains("MethodHandle") {
512        writeln!(out, "import java.lang.invoke.MethodHandle;").ok();
513    }
514    writeln!(out).ok();
515
516    out.push_str(&body);
517
518    out
519}
520
521// ---------------------------------------------------------------------------
522// Main wrapper class
523// ---------------------------------------------------------------------------
524
525fn gen_main_class(api: &ApiSurface, _config: &AlefConfig, package: &str, class_name: &str, prefix: &str) -> String {
526    // Build the set of opaque type names so we can distinguish opaque handles from records
527    let opaque_types: AHashSet<String> = api
528        .types
529        .iter()
530        .filter(|t| t.is_opaque)
531        .map(|t| t.name.clone())
532        .collect();
533
534    // Generate the class body first, then scan it to determine which imports are needed.
535    let mut body = String::with_capacity(4096);
536
537    writeln!(body, "public final class {} {{", class_name).ok();
538    writeln!(body, "    private {}() {{ }}", class_name).ok();
539    writeln!(body).ok();
540
541    // Generate static methods for free functions
542    for func in &api.functions {
543        // Always generate sync method
544        gen_sync_function_method(&mut body, func, prefix, class_name, &opaque_types);
545        writeln!(body).ok();
546
547        // Also generate async wrapper if marked as async
548        if func.is_async {
549            gen_async_wrapper_method(&mut body, func);
550            writeln!(body).ok();
551        }
552    }
553
554    // Add helper methods only if they are referenced in the body
555    gen_helper_methods(&mut body, prefix, class_name);
556
557    writeln!(body, "}}").ok();
558
559    // Now assemble the file with only the imports that are actually used in the body.
560    let mut out = String::with_capacity(body.len() + 512);
561
562    writeln!(out, "// DO NOT EDIT - auto-generated by alef").ok();
563    writeln!(out, "package {};", package).ok();
564    writeln!(out).ok();
565    if body.contains("Arena") {
566        writeln!(out, "import java.lang.foreign.Arena;").ok();
567    }
568    if body.contains("FunctionDescriptor") {
569        writeln!(out, "import java.lang.foreign.FunctionDescriptor;").ok();
570    }
571    if body.contains("Linker") {
572        writeln!(out, "import java.lang.foreign.Linker;").ok();
573    }
574    if body.contains("MemorySegment") {
575        writeln!(out, "import java.lang.foreign.MemorySegment;").ok();
576    }
577    if body.contains("SymbolLookup") {
578        writeln!(out, "import java.lang.foreign.SymbolLookup;").ok();
579    }
580    if body.contains("ValueLayout") {
581        writeln!(out, "import java.lang.foreign.ValueLayout;").ok();
582    }
583    if body.contains("List<") {
584        writeln!(out, "import java.util.List;").ok();
585    }
586    if body.contains("Map<") {
587        writeln!(out, "import java.util.Map;").ok();
588    }
589    if body.contains("Optional<") {
590        writeln!(out, "import java.util.Optional;").ok();
591    }
592    if body.contains("HashMap<") || body.contains("new HashMap") {
593        writeln!(out, "import java.util.HashMap;").ok();
594    }
595    if body.contains("CompletableFuture") {
596        writeln!(out, "import java.util.concurrent.CompletableFuture;").ok();
597    }
598    if body.contains("CompletionException") {
599        writeln!(out, "import java.util.concurrent.CompletionException;").ok();
600    }
601    // Only import the short name `ObjectMapper` when it's used as a type reference (not just via
602    // `createObjectMapper()` which uses fully qualified names internally).
603    // Check for " ObjectMapper" (space before) which indicates use as a type, not a method name suffix.
604    if body.contains(" ObjectMapper") {
605        writeln!(out, "import com.fasterxml.jackson.databind.ObjectMapper;").ok();
606    }
607    writeln!(out).ok();
608
609    out.push_str(&body);
610
611    out
612}
613
614fn gen_sync_function_method(
615    out: &mut String,
616    func: &FunctionDef,
617    prefix: &str,
618    class_name: &str,
619    opaque_types: &AHashSet<String>,
620) {
621    let params: Vec<String> = func
622        .params
623        .iter()
624        .map(|p| {
625            let ptype = java_type(&p.ty);
626            format!("{} {}", ptype, to_java_name(&p.name))
627        })
628        .collect();
629
630    let return_type = java_type(&func.return_type);
631
632    writeln!(
633        out,
634        "    public static {} {}({}) throws {}Exception {{",
635        return_type,
636        to_java_name(&func.name),
637        params.join(", "),
638        class_name
639    )
640    .ok();
641
642    writeln!(out, "        try (var arena = Arena.ofConfined()) {{").ok();
643
644    // Collect non-opaque Named params that need FFI pointer cleanup after the call.
645    // These are Rust-allocated by _from_json and must be freed with _free.
646    let ffi_ptr_params: Vec<(String, String)> = func
647        .params
648        .iter()
649        .filter_map(|p| {
650            let inner_name = match &p.ty {
651                TypeRef::Named(n) if !opaque_types.contains(n.as_str()) => Some(n.clone()),
652                TypeRef::Optional(inner) => {
653                    if let TypeRef::Named(n) = inner.as_ref() {
654                        if !opaque_types.contains(n.as_str()) {
655                            Some(n.clone())
656                        } else {
657                            None
658                        }
659                    } else {
660                        None
661                    }
662                }
663                _ => None,
664            };
665            inner_name.map(|type_name| {
666                let cname = "c".to_string() + &to_java_name(&p.name);
667                let type_snake = type_name.to_snake_case();
668                let free_handle = format!("NativeLib.{}_{}_FREE", prefix.to_uppercase(), type_snake.to_uppercase());
669                (cname, free_handle)
670            })
671        })
672        .collect();
673
674    // Marshal parameters (use camelCase Java names)
675    for param in &func.params {
676        marshal_param_to_ffi(out, &to_java_name(&param.name), &param.ty, opaque_types, prefix);
677    }
678
679    // Call FFI
680    let ffi_handle = format!("NativeLib.{}_{}", prefix.to_uppercase(), func.name.to_uppercase());
681
682    let call_args: Vec<String> = func
683        .params
684        .iter()
685        .map(|p| ffi_param_name(&to_java_name(&p.name), &p.ty, opaque_types))
686        .collect();
687
688    // Emit a helper closure to free FFI-allocated param pointers (e.g. options created by _from_json)
689    let emit_ffi_ptr_cleanup = |out: &mut String| {
690        for (cname, free_handle) in &ffi_ptr_params {
691            writeln!(out, "            if (!{}.equals(MemorySegment.NULL)) {{", cname).ok();
692            writeln!(out, "                {}.invoke({});", free_handle, cname).ok();
693            writeln!(out, "            }}").ok();
694        }
695    };
696
697    if matches!(func.return_type, TypeRef::Unit) {
698        writeln!(out, "            {}.invoke({});", ffi_handle, call_args.join(", ")).ok();
699        emit_ffi_ptr_cleanup(out);
700        writeln!(out, "        }} catch (Throwable e) {{").ok();
701        writeln!(
702            out,
703            "            throw new {}Exception(\"FFI call failed\", e);",
704            class_name
705        )
706        .ok();
707        writeln!(out, "        }}").ok();
708    } else if is_ffi_string_return(&func.return_type) {
709        let free_handle = format!("NativeLib.{}_FREE_STRING", prefix.to_uppercase());
710        writeln!(
711            out,
712            "            var resultPtr = (MemorySegment) {}.invoke({});",
713            ffi_handle,
714            call_args.join(", ")
715        )
716        .ok();
717        emit_ffi_ptr_cleanup(out);
718        writeln!(out, "            if (resultPtr.equals(MemorySegment.NULL)) {{").ok();
719        writeln!(out, "                checkLastError();").ok();
720        writeln!(out, "                return null;").ok();
721        writeln!(out, "            }}").ok();
722        writeln!(
723            out,
724            "            String result = resultPtr.reinterpret(Long.MAX_VALUE).getString(0);"
725        )
726        .ok();
727        writeln!(out, "            {}.invoke(resultPtr);", free_handle).ok();
728        writeln!(out, "            return result;").ok();
729        writeln!(out, "        }} catch (Throwable e) {{").ok();
730        writeln!(
731            out,
732            "            throw new {}Exception(\"FFI call failed\", e);",
733            class_name
734        )
735        .ok();
736        writeln!(out, "        }}").ok();
737    } else if matches!(func.return_type, TypeRef::Named(_)) {
738        // Named return types: FFI returns a struct pointer.
739        let return_type_name = match &func.return_type {
740            TypeRef::Named(name) => name,
741            _ => unreachable!(),
742        };
743        let is_opaque = opaque_types.contains(return_type_name.as_str());
744
745        writeln!(
746            out,
747            "            var resultPtr = (MemorySegment) {}.invoke({});",
748            ffi_handle,
749            call_args.join(", ")
750        )
751        .ok();
752        emit_ffi_ptr_cleanup(out);
753        writeln!(out, "            if (resultPtr.equals(MemorySegment.NULL)) {{").ok();
754        writeln!(out, "                checkLastError();").ok();
755        writeln!(out, "                return null;").ok();
756        writeln!(out, "            }}").ok();
757
758        if is_opaque {
759            // Opaque handles: wrap the raw pointer directly, caller owns and will close()
760            writeln!(out, "            return new {}(resultPtr);", return_type_name).ok();
761        } else {
762            // Record types: use _to_json to serialize the full struct to JSON, then deserialize.
763            // NOTE: _content only returns the markdown string field, not a full JSON object.
764            let type_snake = return_type_name.to_snake_case();
765            let free_handle = format!("NativeLib.{}_{}_FREE", prefix.to_uppercase(), type_snake.to_uppercase());
766            let to_json_handle = format!(
767                "NativeLib.{}_{}_TO_JSON",
768                prefix.to_uppercase(),
769                type_snake.to_uppercase()
770            );
771            writeln!(
772                out,
773                "            var jsonPtr = (MemorySegment) {}.invoke(resultPtr);",
774                to_json_handle
775            )
776            .ok();
777            writeln!(out, "            {}.invoke(resultPtr);", free_handle).ok();
778            writeln!(out, "            if (jsonPtr.equals(MemorySegment.NULL)) {{").ok();
779            writeln!(out, "                checkLastError();").ok();
780            writeln!(out, "                return null;").ok();
781            writeln!(out, "            }}").ok();
782            writeln!(
783                out,
784                "            String json = jsonPtr.reinterpret(Long.MAX_VALUE).getString(0);"
785            )
786            .ok();
787            writeln!(
788                out,
789                "            NativeLib.{}_FREE_STRING.invoke(jsonPtr);",
790                prefix.to_uppercase()
791            )
792            .ok();
793            writeln!(
794                out,
795                "            return createObjectMapper().readValue(json, {}.class);",
796                return_type_name
797            )
798            .ok();
799        }
800
801        writeln!(out, "        }} catch (Throwable e) {{").ok();
802        writeln!(
803            out,
804            "            throw new {}Exception(\"FFI call failed\", e);",
805            class_name
806        )
807        .ok();
808        writeln!(out, "        }}").ok();
809    } else if matches!(func.return_type, TypeRef::Vec(_)) {
810        // Vec return types: FFI returns a JSON string pointer; deserialize into List<T>.
811        let free_handle = format!("NativeLib.{}_FREE_STRING", prefix.to_uppercase());
812        writeln!(
813            out,
814            "            var resultPtr = (MemorySegment) {}.invoke({});",
815            ffi_handle,
816            call_args.join(", ")
817        )
818        .ok();
819        emit_ffi_ptr_cleanup(out);
820        writeln!(out, "            if (resultPtr.equals(MemorySegment.NULL)) {{").ok();
821        writeln!(out, "                return java.util.List.of();").ok();
822        writeln!(out, "            }}").ok();
823        writeln!(
824            out,
825            "            String json = resultPtr.reinterpret(Long.MAX_VALUE).getString(0);"
826        )
827        .ok();
828        writeln!(out, "            {}.invoke(resultPtr);", free_handle).ok();
829        // Determine the element type for deserialization
830        let element_type = match &func.return_type {
831            TypeRef::Vec(inner) => java_type(inner),
832            _ => unreachable!(),
833        };
834        writeln!(
835            out,
836            "            return createObjectMapper().readValue(json, new com.fasterxml.jackson.core.type.TypeReference<java.util.List<{}>>() {{ }});",
837            element_type
838        )
839        .ok();
840        writeln!(out, "        }} catch (Throwable e) {{").ok();
841        writeln!(
842            out,
843            "            throw new {}Exception(\"FFI call failed\", e);",
844            class_name
845        )
846        .ok();
847        writeln!(out, "        }}").ok();
848    } else {
849        writeln!(
850            out,
851            "            var primitiveResult = ({}) {}.invoke({});",
852            java_ffi_return_cast(&func.return_type),
853            ffi_handle,
854            call_args.join(", ")
855        )
856        .ok();
857        emit_ffi_ptr_cleanup(out);
858        writeln!(out, "            return primitiveResult;").ok();
859        writeln!(out, "        }} catch (Throwable e) {{").ok();
860        writeln!(
861            out,
862            "            throw new {}Exception(\"FFI call failed\", e);",
863            class_name
864        )
865        .ok();
866        writeln!(out, "        }}").ok();
867    }
868
869    writeln!(out, "    }}").ok();
870}
871
872fn gen_async_wrapper_method(out: &mut String, func: &FunctionDef) {
873    let params: Vec<String> = func
874        .params
875        .iter()
876        .map(|p| {
877            let ptype = java_type(&p.ty);
878            format!("{} {}", ptype, to_java_name(&p.name))
879        })
880        .collect();
881
882    let return_type = match &func.return_type {
883        TypeRef::Unit => "Void".to_string(),
884        other => java_boxed_type(other).to_string(),
885    };
886
887    let sync_method_name = to_java_name(&func.name);
888    let async_method_name = format!("{}Async", sync_method_name);
889    let param_names: Vec<String> = func.params.iter().map(|p| to_java_name(&p.name)).collect();
890
891    writeln!(
892        out,
893        "    public static CompletableFuture<{}> {}({}) {{",
894        return_type,
895        async_method_name,
896        params.join(", ")
897    )
898    .ok();
899    writeln!(out, "        return CompletableFuture.supplyAsync(() -> {{").ok();
900    writeln!(out, "            try {{").ok();
901    writeln!(
902        out,
903        "                return {}({});",
904        sync_method_name,
905        param_names.join(", ")
906    )
907    .ok();
908    writeln!(out, "            }} catch (Throwable e) {{").ok();
909    writeln!(out, "                throw new CompletionException(e);").ok();
910    writeln!(out, "            }}").ok();
911    writeln!(out, "        }});").ok();
912    writeln!(out, "    }}").ok();
913}
914
915// ---------------------------------------------------------------------------
916// Exception class
917// ---------------------------------------------------------------------------
918
919fn gen_exception_class(package: &str, class_name: &str) -> String {
920    let mut out = String::with_capacity(512);
921
922    writeln!(out, "// DO NOT EDIT - auto-generated by alef").ok();
923    writeln!(out, "package {};", package).ok();
924    writeln!(out).ok();
925
926    writeln!(out, "public class {}Exception extends Exception {{", class_name).ok();
927    writeln!(out, "    private final int code;").ok();
928    writeln!(out).ok();
929    writeln!(out, "    public {}Exception(int code, String message) {{", class_name).ok();
930    writeln!(out, "        super(message);").ok();
931    writeln!(out, "        this.code = code;").ok();
932    writeln!(out, "    }}").ok();
933    writeln!(out).ok();
934    writeln!(
935        out,
936        "    public {}Exception(String message, Throwable cause) {{",
937        class_name
938    )
939    .ok();
940    writeln!(out, "        super(message, cause);").ok();
941    writeln!(out, "        this.code = -1;").ok();
942    writeln!(out, "    }}").ok();
943    writeln!(out).ok();
944    writeln!(out, "    public int getCode() {{").ok();
945    writeln!(out, "        return code;").ok();
946    writeln!(out, "    }}").ok();
947    writeln!(out, "}}").ok();
948
949    out
950}
951
952// ---------------------------------------------------------------------------
953// High-level facade class (public API)
954// ---------------------------------------------------------------------------
955
956fn gen_facade_class(api: &ApiSurface, package: &str, public_class: &str, raw_class: &str, _prefix: &str) -> String {
957    let mut body = String::with_capacity(4096);
958
959    writeln!(body, "public final class {} {{", public_class).ok();
960    writeln!(body, "    private {}() {{ }}", public_class).ok();
961    writeln!(body).ok();
962
963    // Generate static methods for free functions
964    for func in &api.functions {
965        // Sync method
966        let params: Vec<String> = func
967            .params
968            .iter()
969            .map(|p| {
970                let ptype = java_type(&p.ty);
971                format!("{} {}", ptype, to_java_name(&p.name))
972            })
973            .collect();
974
975        let return_type = java_type(&func.return_type);
976
977        if !func.doc.is_empty() {
978            writeln!(body, "    /**").ok();
979            for line in func.doc.lines() {
980                writeln!(body, "     * {}", line).ok();
981            }
982            writeln!(body, "     */").ok();
983        }
984
985        writeln!(
986            body,
987            "    public static {} {}({}) throws {}Exception {{",
988            return_type,
989            to_java_name(&func.name),
990            params.join(", "),
991            raw_class
992        )
993        .ok();
994
995        // Null checks for required parameters
996        for param in &func.params {
997            if !param.optional {
998                let pname = to_java_name(&param.name);
999                writeln!(
1000                    body,
1001                    "        java.util.Objects.requireNonNull({}, \"{} must not be null\");",
1002                    pname, pname
1003                )
1004                .ok();
1005            }
1006        }
1007
1008        // Delegate to the raw FFI class
1009        let call_args: Vec<String> = func.params.iter().map(|p| to_java_name(&p.name)).collect();
1010
1011        if matches!(func.return_type, TypeRef::Unit) {
1012            writeln!(
1013                body,
1014                "        {}.{}({});",
1015                raw_class,
1016                to_java_name(&func.name),
1017                call_args.join(", ")
1018            )
1019            .ok();
1020        } else {
1021            writeln!(
1022                body,
1023                "        return {}.{}({});",
1024                raw_class,
1025                to_java_name(&func.name),
1026                call_args.join(", ")
1027            )
1028            .ok();
1029        }
1030
1031        writeln!(body, "    }}").ok();
1032        writeln!(body).ok();
1033
1034        // Generate overload without optional params (convenience method)
1035        let has_optional = func.params.iter().any(|p| p.optional);
1036        if has_optional {
1037            let required_params: Vec<String> = func
1038                .params
1039                .iter()
1040                .filter(|p| !p.optional)
1041                .map(|p| {
1042                    let ptype = java_type(&p.ty);
1043                    format!("{} {}", ptype, to_java_name(&p.name))
1044                })
1045                .collect();
1046
1047            writeln!(
1048                body,
1049                "    public static {} {}({}) throws {}Exception {{",
1050                return_type,
1051                to_java_name(&func.name),
1052                required_params.join(", "),
1053                raw_class
1054            )
1055            .ok();
1056
1057            // Build call with null for optional params
1058            let full_args: Vec<String> = func
1059                .params
1060                .iter()
1061                .map(|p| {
1062                    if p.optional {
1063                        "null".to_string()
1064                    } else {
1065                        to_java_name(&p.name)
1066                    }
1067                })
1068                .collect();
1069
1070            if matches!(func.return_type, TypeRef::Unit) {
1071                writeln!(body, "        {}({});", to_java_name(&func.name), full_args.join(", ")).ok();
1072            } else {
1073                writeln!(
1074                    body,
1075                    "        return {}({});",
1076                    to_java_name(&func.name),
1077                    full_args.join(", ")
1078                )
1079                .ok();
1080            }
1081
1082            writeln!(body, "    }}").ok();
1083            writeln!(body).ok();
1084        }
1085    }
1086
1087    writeln!(body, "}}").ok();
1088
1089    // Now assemble the file with imports
1090    let mut out = String::with_capacity(body.len() + 512);
1091
1092    writeln!(out, "// DO NOT EDIT - auto-generated by alef").ok();
1093    writeln!(out, "package {};", package).ok();
1094
1095    // Check what imports are needed based on content
1096    let has_list = body.contains("List<");
1097    let has_map = body.contains("Map<");
1098    let has_optional = body.contains("Optional<");
1099    let has_imports = has_list || has_map || has_optional;
1100
1101    if has_imports {
1102        writeln!(out).ok();
1103        if has_list {
1104            writeln!(out, "import java.util.List;").ok();
1105        }
1106        if has_map {
1107            writeln!(out, "import java.util.Map;").ok();
1108        }
1109        if has_optional {
1110            writeln!(out, "import java.util.Optional;").ok();
1111        }
1112    }
1113
1114    writeln!(out).ok();
1115    out.push_str(&body);
1116
1117    out
1118}
1119
1120// ---------------------------------------------------------------------------
1121// Opaque handle classes
1122// ---------------------------------------------------------------------------
1123
1124fn gen_opaque_handle_class(package: &str, typ: &TypeDef, prefix: &str) -> String {
1125    let mut out = String::with_capacity(1024);
1126    let class_name = &typ.name;
1127    let type_snake = class_name.to_snake_case();
1128
1129    writeln!(out, "// DO NOT EDIT - auto-generated by alef").ok();
1130    writeln!(out, "package {};", package).ok();
1131    writeln!(out).ok();
1132    writeln!(out, "import java.lang.foreign.MemorySegment;").ok();
1133    writeln!(out).ok();
1134
1135    if !typ.doc.is_empty() {
1136        writeln!(out, "/**").ok();
1137        for line in typ.doc.lines() {
1138            writeln!(out, " * {}", line).ok();
1139        }
1140        writeln!(out, " */").ok();
1141    }
1142
1143    writeln!(out, "public class {} implements AutoCloseable {{", class_name).ok();
1144    writeln!(out, "    private final MemorySegment handle;").ok();
1145    writeln!(out).ok();
1146    writeln!(out, "    {}(MemorySegment handle) {{", class_name).ok();
1147    writeln!(out, "        this.handle = handle;").ok();
1148    writeln!(out, "    }}").ok();
1149    writeln!(out).ok();
1150    writeln!(out, "    MemorySegment handle() {{").ok();
1151    writeln!(out, "        return this.handle;").ok();
1152    writeln!(out, "    }}").ok();
1153    writeln!(out).ok();
1154    writeln!(out, "    @Override").ok();
1155    writeln!(out, "    public void close() {{").ok();
1156    writeln!(
1157        out,
1158        "        if (handle != null && !handle.equals(MemorySegment.NULL)) {{"
1159    )
1160    .ok();
1161    writeln!(out, "            try {{").ok();
1162    writeln!(
1163        out,
1164        "                NativeLib.{}_{}_FREE.invoke(handle);",
1165        prefix.to_uppercase(),
1166        type_snake.to_uppercase()
1167    )
1168    .ok();
1169    writeln!(out, "            }} catch (Throwable e) {{").ok();
1170    writeln!(
1171        out,
1172        "                throw new RuntimeException(\"Failed to free {}: \" + e.getMessage(), e);",
1173        class_name
1174    )
1175    .ok();
1176    writeln!(out, "            }}").ok();
1177    writeln!(out, "        }}").ok();
1178    writeln!(out, "    }}").ok();
1179    writeln!(out, "}}").ok();
1180
1181    out
1182}
1183
1184// ---------------------------------------------------------------------------
1185// Record types (Java records)
1186// ---------------------------------------------------------------------------
1187
1188/// Maximum line length before splitting record fields across multiple lines.
1189/// Checkstyle enforces 120 chars; we split at 100 to leave headroom for indentation.
1190const RECORD_LINE_WRAP_THRESHOLD: usize = 100;
1191
1192fn gen_record_type(package: &str, typ: &TypeDef, complex_enums: &AHashSet<String>, lang_rename_all: &str) -> String {
1193    // Generate the record body first, then scan for needed imports.
1194    // For each field, if the language uses camelCase but the JSON key is snake_case
1195    // (the Rust default), annotate with @JsonProperty so Jackson maps correctly.
1196    let field_list: Vec<String> = typ
1197        .fields
1198        .iter()
1199        .map(|f| {
1200            // Complex enums (tagged unions with data) can't be simple Java enums.
1201            // Use Object for flexible Jackson deserialization.
1202            let is_complex = matches!(&f.ty, TypeRef::Named(n) if complex_enums.contains(n.as_str()));
1203            let ftype = if is_complex {
1204                "Object".to_string()
1205            } else if f.optional {
1206                format!("Optional<{}>", java_boxed_type(&f.ty))
1207            } else {
1208                java_type(&f.ty).to_string()
1209            };
1210            let jname = safe_java_field_name(&f.name);
1211            // When the language convention is camelCase but the JSON wire format uses
1212            // snake_case (the Rust/serde default), add an explicit @JsonProperty annotation
1213            // so Jackson serialises/deserialises using the correct snake_case key.
1214            if lang_rename_all == "camelCase" && f.name.contains('_') {
1215                format!("@JsonProperty(\"{}\") {} {}", f.name, ftype, jname)
1216            } else {
1217                format!("{} {}", ftype, jname)
1218            }
1219        })
1220        .collect();
1221
1222    // Build the single-line form to check length and scan for imports.
1223    let single_line = format!("public record {}({}) {{ }}", typ.name, field_list.join(", "));
1224
1225    // Build the actual record declaration, splitting across lines if too long.
1226    let mut record_block = String::new();
1227    if single_line.len() > RECORD_LINE_WRAP_THRESHOLD && field_list.len() > 1 {
1228        writeln!(record_block, "public record {}(", typ.name).ok();
1229        for (i, field) in field_list.iter().enumerate() {
1230            let comma = if i < field_list.len() - 1 { "," } else { "" };
1231            writeln!(record_block, "    {}{}", field, comma).ok();
1232        }
1233        writeln!(record_block, ") {{").ok();
1234    } else {
1235        writeln!(record_block, "public record {}({}) {{", typ.name, field_list.join(", ")).ok();
1236    }
1237
1238    // Add builder() factory method if type has defaults
1239    if typ.has_default {
1240        writeln!(record_block, "    public static {}Builder builder() {{", typ.name).ok();
1241        writeln!(record_block, "        return new {}Builder();", typ.name).ok();
1242        writeln!(record_block, "    }}").ok();
1243    }
1244
1245    writeln!(record_block, "}}").ok();
1246
1247    // Scan the single-line form to determine which imports are needed
1248    let needs_json_property = field_list.iter().any(|f| f.contains("@JsonProperty("));
1249    let mut out = String::with_capacity(record_block.len() + 512);
1250    writeln!(out, "// DO NOT EDIT - auto-generated by alef").ok();
1251    writeln!(out, "package {};", package).ok();
1252    writeln!(out).ok();
1253    if single_line.contains("List<") {
1254        writeln!(out, "import java.util.List;").ok();
1255    }
1256    if single_line.contains("Map<") {
1257        writeln!(out, "import java.util.Map;").ok();
1258    }
1259    if single_line.contains("Optional<") {
1260        writeln!(out, "import java.util.Optional;").ok();
1261    }
1262    if needs_json_property {
1263        writeln!(out, "import com.fasterxml.jackson.annotation.JsonProperty;").ok();
1264    }
1265    writeln!(out).ok();
1266    write!(out, "{}", record_block).ok();
1267
1268    out
1269}
1270
1271// ---------------------------------------------------------------------------
1272// Enum classes
1273// ---------------------------------------------------------------------------
1274
1275/// Apply a serde `rename_all` strategy to a variant name for Java codegen.
1276fn java_apply_rename_all(name: &str, rename_all: Option<&str>) -> String {
1277    match rename_all {
1278        Some("snake_case") => name.to_snake_case(),
1279        Some("camelCase") => name.to_lower_camel_case(),
1280        Some("PascalCase") => name.to_pascal_case(),
1281        Some("SCREAMING_SNAKE_CASE") => name.to_snake_case().to_uppercase(),
1282        Some("lowercase") => name.to_lowercase(),
1283        Some("UPPERCASE") => name.to_uppercase(),
1284        _ => name.to_lowercase(),
1285    }
1286}
1287
1288fn gen_enum_class(package: &str, enum_def: &EnumDef) -> String {
1289    let has_data_variants = enum_def.variants.iter().any(|v| !v.fields.is_empty());
1290
1291    // Tagged union: enum has a serde tag AND data variants → generate sealed interface hierarchy
1292    if enum_def.serde_tag.is_some() && has_data_variants {
1293        return gen_java_tagged_union(package, enum_def);
1294    }
1295
1296    let mut out = String::with_capacity(1024);
1297
1298    writeln!(out, "// DO NOT EDIT - auto-generated by alef").ok();
1299    writeln!(out, "package {};", package).ok();
1300    writeln!(out).ok();
1301    writeln!(out, "import com.fasterxml.jackson.annotation.JsonCreator;").ok();
1302    writeln!(out, "import com.fasterxml.jackson.annotation.JsonValue;").ok();
1303    writeln!(out).ok();
1304
1305    writeln!(out, "public enum {} {{", enum_def.name).ok();
1306
1307    for (i, variant) in enum_def.variants.iter().enumerate() {
1308        let comma = if i < enum_def.variants.len() - 1 { "," } else { ";" };
1309        // Use serde_rename if available, otherwise apply rename_all strategy
1310        let json_name = variant
1311            .serde_rename
1312            .clone()
1313            .unwrap_or_else(|| java_apply_rename_all(&variant.name, enum_def.serde_rename_all.as_deref()));
1314        writeln!(out, "    {}(\"{}\"){}", variant.name, json_name, comma).ok();
1315    }
1316
1317    writeln!(out).ok();
1318    writeln!(out, "    private final String value;").ok();
1319    writeln!(out).ok();
1320    writeln!(out, "    {}(String value) {{", enum_def.name).ok();
1321    writeln!(out, "        this.value = value;").ok();
1322    writeln!(out, "    }}").ok();
1323    writeln!(out).ok();
1324    writeln!(out, "    @JsonValue").ok();
1325    writeln!(out, "    public String getValue() {{").ok();
1326    writeln!(out, "        return value;").ok();
1327    writeln!(out, "    }}").ok();
1328    writeln!(out).ok();
1329    writeln!(out, "    @JsonCreator").ok();
1330    writeln!(out, "    public static {} fromValue(String value) {{", enum_def.name).ok();
1331    writeln!(out, "        for ({} e : values()) {{", enum_def.name).ok();
1332    writeln!(out, "            if (e.value.equalsIgnoreCase(value)) {{").ok();
1333    writeln!(out, "                return e;").ok();
1334    writeln!(out, "            }}").ok();
1335    writeln!(out, "        }}").ok();
1336    writeln!(
1337        out,
1338        "        throw new IllegalArgumentException(\"Unknown value: \" + value);"
1339    )
1340    .ok();
1341    writeln!(out, "    }}").ok();
1342
1343    writeln!(out, "}}").ok();
1344
1345    out
1346}
1347
1348/// Generate a Java sealed interface hierarchy for internally tagged enums.
1349///
1350/// Maps `#[serde(tag = "type_field", rename_all = "snake_case")]` Rust enums to
1351/// `@JsonTypeInfo` / `@JsonSubTypes` Java sealed interfaces with record implementations.
1352fn gen_java_tagged_union(package: &str, enum_def: &EnumDef) -> String {
1353    let tag_field = enum_def.serde_tag.as_deref().unwrap_or("type");
1354
1355    // Collect variant names to detect Java type name conflicts.
1356    // If a variant is named "List", "Map", or "Optional", using those type names
1357    // inside the sealed interface would refer to the nested record, not java.util.*.
1358    // We use fully qualified names in that case.
1359    let variant_names: std::collections::HashSet<&str> = enum_def.variants.iter().map(|v| v.name.as_str()).collect();
1360    let optional_type = if variant_names.contains("Optional") {
1361        "java.util.Optional"
1362    } else {
1363        "Optional"
1364    };
1365
1366    let mut out = String::with_capacity(2048);
1367    writeln!(out, "// DO NOT EDIT - auto-generated by alef").ok();
1368    writeln!(out, "package {};", package).ok();
1369    writeln!(out).ok();
1370    writeln!(out, "import com.fasterxml.jackson.annotation.JsonProperty;").ok();
1371    writeln!(out, "import com.fasterxml.jackson.annotation.JsonSubTypes;").ok();
1372    writeln!(out, "import com.fasterxml.jackson.annotation.JsonTypeInfo;").ok();
1373
1374    // Check if any field types need list/map/optional imports (only when not conflicting)
1375    let needs_list = !variant_names.contains("List")
1376        && enum_def
1377            .variants
1378            .iter()
1379            .any(|v| v.fields.iter().any(|f| matches!(&f.ty, TypeRef::Vec(_))));
1380    let needs_map = !variant_names.contains("Map")
1381        && enum_def
1382            .variants
1383            .iter()
1384            .any(|v| v.fields.iter().any(|f| matches!(&f.ty, TypeRef::Map(_, _))));
1385    let needs_optional =
1386        !variant_names.contains("Optional") && enum_def.variants.iter().any(|v| v.fields.iter().any(|f| f.optional));
1387    if needs_list {
1388        writeln!(out, "import java.util.List;").ok();
1389    }
1390    if needs_map {
1391        writeln!(out, "import java.util.Map;").ok();
1392    }
1393    if needs_optional {
1394        writeln!(out, "import java.util.Optional;").ok();
1395    }
1396    writeln!(out).ok();
1397
1398    // @JsonTypeInfo and @JsonSubTypes annotations
1399    writeln!(
1400        out,
1401        "@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = \"{tag_field}\", visible = false)"
1402    )
1403    .ok();
1404    writeln!(out, "@JsonSubTypes({{").ok();
1405    for (i, variant) in enum_def.variants.iter().enumerate() {
1406        let discriminator = variant
1407            .serde_rename
1408            .clone()
1409            .unwrap_or_else(|| java_apply_rename_all(&variant.name, enum_def.serde_rename_all.as_deref()));
1410        let comma = if i < enum_def.variants.len() - 1 { "," } else { "" };
1411        writeln!(
1412            out,
1413            "    @JsonSubTypes.Type(value = {}.{}.class, name = \"{}\"){}",
1414            enum_def.name, variant.name, discriminator, comma
1415        )
1416        .ok();
1417    }
1418    writeln!(out, "}})").ok();
1419    writeln!(out, "public sealed interface {} {{", enum_def.name).ok();
1420
1421    // Nested records for each variant
1422    for variant in &enum_def.variants {
1423        writeln!(out).ok();
1424        if variant.fields.is_empty() {
1425            // Unit variant
1426            writeln!(out, "    record {}() implements {} {{", variant.name, enum_def.name).ok();
1427            writeln!(out, "    }}").ok();
1428        } else {
1429            // Build field list using fully qualified names where variant names shadow imports
1430            let field_parts: Vec<String> = variant
1431                .fields
1432                .iter()
1433                .map(|f| {
1434                    let json_name = f.name.trim_start_matches('_');
1435                    let ftype = if f.optional {
1436                        let inner = java_boxed_type(&f.ty);
1437                        let inner_str = inner.as_ref();
1438                        // Replace "List"/"Map" with fully qualified if conflicting
1439                        let inner_qualified = if inner_str.starts_with("List<") && variant_names.contains("List") {
1440                            inner_str.replacen("List<", "java.util.List<", 1)
1441                        } else if inner_str.starts_with("Map<") && variant_names.contains("Map") {
1442                            inner_str.replacen("Map<", "java.util.Map<", 1)
1443                        } else {
1444                            inner_str.to_string()
1445                        };
1446                        format!("{optional_type}<{inner_qualified}>")
1447                    } else {
1448                        let t = java_type(&f.ty);
1449                        let t_str = t.as_ref();
1450                        if t_str.starts_with("List<") && variant_names.contains("List") {
1451                            t_str.replacen("List<", "java.util.List<", 1)
1452                        } else if t_str.starts_with("Map<") && variant_names.contains("Map") {
1453                            t_str.replacen("Map<", "java.util.Map<", 1)
1454                        } else {
1455                            t_str.to_string()
1456                        }
1457                    };
1458                    let jname = safe_java_field_name(json_name);
1459                    format!("@JsonProperty(\"{json_name}\") {ftype} {jname}")
1460                })
1461                .collect();
1462
1463            let single = format!(
1464                "    record {}({}) implements {} {{ }}",
1465                variant.name,
1466                field_parts.join(", "),
1467                enum_def.name
1468            );
1469
1470            if single.len() > RECORD_LINE_WRAP_THRESHOLD && field_parts.len() > 1 {
1471                writeln!(out, "    record {}(", variant.name).ok();
1472                for (i, fp) in field_parts.iter().enumerate() {
1473                    let comma = if i < field_parts.len() - 1 { "," } else { "" };
1474                    writeln!(out, "        {}{}", fp, comma).ok();
1475                }
1476                writeln!(out, "    ) implements {} {{", enum_def.name).ok();
1477                writeln!(out, "    }}").ok();
1478            } else {
1479                writeln!(
1480                    out,
1481                    "    record {}({}) implements {} {{ }}",
1482                    variant.name,
1483                    field_parts.join(", "),
1484                    enum_def.name
1485                )
1486                .ok();
1487            }
1488        }
1489    }
1490
1491    writeln!(out).ok();
1492    writeln!(out, "}}").ok();
1493    out
1494}
1495
1496// ---------------------------------------------------------------------------
1497// Helper functions for FFI marshalling
1498// ---------------------------------------------------------------------------
1499
1500fn gen_ffi_layout(ty: &TypeRef) -> String {
1501    match ty {
1502        TypeRef::Primitive(prim) => java_ffi_type(prim).to_string(),
1503        TypeRef::String | TypeRef::Char | TypeRef::Path | TypeRef::Json => "ValueLayout.ADDRESS".to_string(),
1504        TypeRef::Bytes => "ValueLayout.ADDRESS".to_string(),
1505        TypeRef::Optional(inner) => gen_ffi_layout(inner),
1506        TypeRef::Vec(_) => "ValueLayout.ADDRESS".to_string(),
1507        TypeRef::Map(_, _) => "ValueLayout.ADDRESS".to_string(),
1508        TypeRef::Named(_) => "ValueLayout.ADDRESS".to_string(),
1509        TypeRef::Unit => "".to_string(),
1510        TypeRef::Duration => "ValueLayout.JAVA_LONG".to_string(),
1511    }
1512}
1513
1514fn marshal_param_to_ffi(out: &mut String, name: &str, ty: &TypeRef, opaque_types: &AHashSet<String>, prefix: &str) {
1515    match ty {
1516        TypeRef::String | TypeRef::Char | TypeRef::Path | TypeRef::Json => {
1517            let cname = "c".to_string() + name;
1518            writeln!(out, "            var {} = arena.allocateFrom({});", cname, name).ok();
1519        }
1520        TypeRef::Named(type_name) => {
1521            let cname = "c".to_string() + name;
1522            if opaque_types.contains(type_name.as_str()) {
1523                // Opaque handles: pass the inner MemorySegment via .handle()
1524                writeln!(out, "            var {} = {}.handle();", cname, name).ok();
1525            } else {
1526                // Non-opaque named types: serialize to JSON, call _from_json to get FFI pointer.
1527                // The pointer must be freed after the FFI call with _free.
1528                let type_snake = type_name.to_snake_case();
1529                let from_json_handle = format!(
1530                    "NativeLib.{}_{}_FROM_JSON",
1531                    prefix.to_uppercase(),
1532                    type_snake.to_uppercase()
1533                );
1534                let _free_handle = format!("NativeLib.{}_{}_FREE", prefix.to_uppercase(), type_snake.to_uppercase());
1535                writeln!(
1536                    out,
1537                    "            var {}Json = {} != null ? createObjectMapper().writeValueAsString({}) : null;",
1538                    cname, name, name
1539                )
1540                .ok();
1541                writeln!(
1542                    out,
1543                    "            var {}JsonSeg = {}Json != null ? arena.allocateFrom({}Json) : MemorySegment.NULL;",
1544                    cname, cname, cname
1545                )
1546                .ok();
1547                writeln!(out, "            var {} = {}Json != null", cname, cname).ok();
1548                writeln!(
1549                    out,
1550                    "                ? (MemorySegment) {}.invoke({}JsonSeg)",
1551                    from_json_handle, cname
1552                )
1553                .ok();
1554                writeln!(out, "                : MemorySegment.NULL;").ok();
1555            }
1556        }
1557        TypeRef::Optional(inner) => {
1558            // For optional types, marshal the inner type if not null
1559            match inner.as_ref() {
1560                TypeRef::String | TypeRef::Char | TypeRef::Path | TypeRef::Json => {
1561                    let cname = "c".to_string() + name;
1562                    writeln!(
1563                        out,
1564                        "            var {} = {} != null ? arena.allocateFrom({}) : MemorySegment.NULL;",
1565                        cname, name, name
1566                    )
1567                    .ok();
1568                }
1569                TypeRef::Named(type_name) => {
1570                    let cname = "c".to_string() + name;
1571                    if opaque_types.contains(type_name.as_str()) {
1572                        writeln!(
1573                            out,
1574                            "            var {} = {} != null ? {}.handle() : MemorySegment.NULL;",
1575                            cname, name, name
1576                        )
1577                        .ok();
1578                    } else {
1579                        // Non-opaque named type in Optional: serialize to JSON and call _from_json
1580                        let type_snake = type_name.to_snake_case();
1581                        let from_json_handle = format!(
1582                            "NativeLib.{}_{}_FROM_JSON",
1583                            prefix.to_uppercase(),
1584                            type_snake.to_uppercase()
1585                        );
1586                        writeln!(
1587                            out,
1588                            "            var {}Json = {} != null ? createObjectMapper().writeValueAsString({}) : null;",
1589                            cname, name, name
1590                        )
1591                        .ok();
1592                        writeln!(out, "            var {}JsonSeg = {}Json != null ? arena.allocateFrom({}Json) : MemorySegment.NULL;", cname, cname, cname).ok();
1593                        writeln!(out, "            var {} = {}Json != null", cname, cname).ok();
1594                        writeln!(
1595                            out,
1596                            "                ? (MemorySegment) {}.invoke({}JsonSeg)",
1597                            from_json_handle, cname
1598                        )
1599                        .ok();
1600                        writeln!(out, "                : MemorySegment.NULL;").ok();
1601                    }
1602                }
1603                _ => {
1604                    // Other optional types (primitives) pass through
1605                }
1606            }
1607        }
1608        TypeRef::Vec(_) | TypeRef::Map(_, _) => {
1609            // Vec/Map types: serialize to JSON string, then pass as a C string via arena.
1610            let cname = "c".to_string() + name;
1611            writeln!(
1612                out,
1613                "            var {}Json = createObjectMapper().writeValueAsString({});",
1614                cname, name
1615            )
1616            .ok();
1617            writeln!(out, "            var {} = arena.allocateFrom({}Json);", cname, cname).ok();
1618        }
1619        _ => {
1620            // Primitives and others pass through directly
1621        }
1622    }
1623}
1624
1625fn ffi_param_name(name: &str, ty: &TypeRef, _opaque_types: &AHashSet<String>) -> String {
1626    match ty {
1627        TypeRef::String | TypeRef::Char | TypeRef::Path | TypeRef::Json => "c".to_string() + name,
1628        TypeRef::Named(_) => "c".to_string() + name,
1629        TypeRef::Vec(_) | TypeRef::Map(_, _) => "c".to_string() + name,
1630        TypeRef::Optional(inner) => match inner.as_ref() {
1631            TypeRef::String | TypeRef::Char | TypeRef::Path | TypeRef::Json | TypeRef::Named(_) => {
1632                "c".to_string() + name
1633            }
1634            _ => name.to_string(),
1635        },
1636        _ => name.to_string(),
1637    }
1638}
1639
1640/// Build a `FunctionDescriptor` string for a given return layout and parameter layouts.
1641/// Handles void returns (ofVoid) and non-void returns (of) correctly.
1642fn gen_function_descriptor(return_layout: &str, param_layouts: &[String]) -> String {
1643    if return_layout.is_empty() {
1644        // Void return
1645        if param_layouts.is_empty() {
1646            "FunctionDescriptor.ofVoid()".to_string()
1647        } else {
1648            format!("FunctionDescriptor.ofVoid({})", param_layouts.join(", "))
1649        }
1650    } else {
1651        // Non-void return
1652        if param_layouts.is_empty() {
1653            format!("FunctionDescriptor.of({})", return_layout)
1654        } else {
1655            format!("FunctionDescriptor.of({}, {})", return_layout, param_layouts.join(", "))
1656        }
1657    }
1658}
1659
1660/// Returns true if the given return type maps to an FFI ADDRESS that represents a string
1661/// (i.e. the FFI returns `*mut c_char` which must be unmarshaled and freed).
1662fn is_ffi_string_return(ty: &TypeRef) -> bool {
1663    match ty {
1664        TypeRef::String | TypeRef::Char | TypeRef::Path | TypeRef::Json => true,
1665        TypeRef::Optional(inner) => is_ffi_string_return(inner),
1666        _ => false,
1667    }
1668}
1669
1670/// Returns the appropriate Java cast type for non-string FFI return values.
1671fn java_ffi_return_cast(ty: &TypeRef) -> &'static str {
1672    match ty {
1673        TypeRef::Primitive(prim) => match prim {
1674            PrimitiveType::Bool => "boolean",
1675            PrimitiveType::U8 | PrimitiveType::I8 => "byte",
1676            PrimitiveType::U16 | PrimitiveType::I16 => "short",
1677            PrimitiveType::U32 | PrimitiveType::I32 => "int",
1678            PrimitiveType::U64 | PrimitiveType::I64 | PrimitiveType::Usize | PrimitiveType::Isize => "long",
1679            PrimitiveType::F32 => "float",
1680            PrimitiveType::F64 => "double",
1681        },
1682        TypeRef::Bytes | TypeRef::Vec(_) | TypeRef::Map(_, _) | TypeRef::Named(_) => "MemorySegment",
1683        _ => "MemorySegment",
1684    }
1685}
1686
1687fn gen_helper_methods(out: &mut String, prefix: &str, class_name: &str) {
1688    // Only emit helper methods that are actually called in the generated body.
1689    let needs_check_last_error = out.contains("checkLastError()");
1690    let needs_read_cstring = out.contains("readCString(");
1691    let needs_read_bytes = out.contains("readBytes(");
1692    let needs_create_object_mapper = out.contains("createObjectMapper()");
1693
1694    if !needs_check_last_error && !needs_read_cstring && !needs_read_bytes && !needs_create_object_mapper {
1695        return;
1696    }
1697
1698    writeln!(out, "    // Helper methods for FFI marshalling").ok();
1699    writeln!(out).ok();
1700
1701    if needs_check_last_error {
1702        // Reads the last FFI error code and, if non-zero, reads the error message and throws.
1703        // Called immediately after a null-pointer return from an FFI call.
1704        writeln!(out, "    private static void checkLastError() throws Throwable {{").ok();
1705        writeln!(
1706            out,
1707            "        int errCode = (int) NativeLib.{}_LAST_ERROR_CODE.invoke();",
1708            prefix.to_uppercase()
1709        )
1710        .ok();
1711        writeln!(out, "        if (errCode != 0) {{").ok();
1712        writeln!(
1713            out,
1714            "            var ctxPtr = (MemorySegment) NativeLib.{}_LAST_ERROR_CONTEXT.invoke();",
1715            prefix.to_uppercase()
1716        )
1717        .ok();
1718        writeln!(
1719            out,
1720            "            String msg = ctxPtr.reinterpret(Long.MAX_VALUE).getString(0);"
1721        )
1722        .ok();
1723        writeln!(out, "            throw new {}Exception(errCode, msg);", class_name).ok();
1724        writeln!(out, "        }}").ok();
1725        writeln!(out, "    }}").ok();
1726        writeln!(out).ok();
1727    }
1728
1729    if needs_create_object_mapper {
1730        // Emit a configured ObjectMapper factory:
1731        //   - findAndRegisterModules() to pick up jackson-datatype-jdk8 (Optional support)
1732        //   - ACCEPT_CASE_INSENSITIVE_ENUMS so enum names like "json_ld" match JsonLd, etc.
1733        // Field name mapping relies on explicit @JsonProperty annotations on record components
1734        // (generated by alef for snake_case FFI fields on camelCase Java records).
1735        writeln!(
1736            out,
1737            "    private static com.fasterxml.jackson.databind.ObjectMapper createObjectMapper() {{"
1738        )
1739        .ok();
1740        writeln!(out, "        return new com.fasterxml.jackson.databind.ObjectMapper()").ok();
1741        writeln!(
1742            out,
1743            "            .registerModule(new com.fasterxml.jackson.datatype.jdk8.Jdk8Module())"
1744        )
1745        .ok();
1746        writeln!(out, "            .findAndRegisterModules()").ok();
1747        writeln!(
1748            out,
1749            "            .setSerializationInclusion(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL)"
1750        )
1751        .ok();
1752        writeln!(
1753            out,
1754            "            .configure(com.fasterxml.jackson.databind.MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS, true);"
1755        )
1756        .ok();
1757        writeln!(out, "    }}").ok();
1758        writeln!(out).ok();
1759    }
1760
1761    if needs_read_cstring {
1762        writeln!(out, "    private static String readCString(MemorySegment ptr) {{").ok();
1763        writeln!(out, "        if (ptr == null || ptr.address() == 0) {{").ok();
1764        writeln!(out, "            return null;").ok();
1765        writeln!(out, "        }}").ok();
1766        writeln!(out, "        return ptr.getUtf8String(0);").ok();
1767        writeln!(out, "    }}").ok();
1768        writeln!(out).ok();
1769    }
1770
1771    if needs_read_bytes {
1772        writeln!(
1773            out,
1774            "    private static byte[] readBytes(MemorySegment ptr, long len) {{"
1775        )
1776        .ok();
1777        writeln!(out, "        if (ptr == null || ptr.address() == 0) {{").ok();
1778        writeln!(out, "            return new byte[0];").ok();
1779        writeln!(out, "        }}").ok();
1780        writeln!(out, "        byte[] bytes = new byte[(int) len];").ok();
1781        writeln!(
1782            out,
1783            "        MemorySegment.copy(ptr, ValueLayout.JAVA_BYTE.byteSize() * 0, bytes, 0, (int) len);"
1784        )
1785        .ok();
1786        writeln!(out, "        return bytes;").ok();
1787        writeln!(out, "    }}").ok();
1788    }
1789}
1790
1791// ---------------------------------------------------------------------------
1792// Builder class for types with defaults
1793// ---------------------------------------------------------------------------
1794
1795/// Format a default value for an Optional field, wrapping it in Optional.of()
1796/// with proper Java literal syntax.
1797fn format_optional_value(ty: &TypeRef, default: &str) -> String {
1798    // Check if the default is already wrapped (e.g., "Optional.of(...)" or "Optional.empty()")
1799    if default.contains("Optional.") {
1800        return default.to_string();
1801    }
1802
1803    // Unwrap Optional types to get the inner type
1804    let inner_ty = match ty {
1805        TypeRef::Optional(inner) => inner.as_ref(),
1806        other => other,
1807    };
1808
1809    // Determine the proper literal suffix based on type
1810    let formatted_value = match inner_ty {
1811        TypeRef::Primitive(p) => match p {
1812            PrimitiveType::I64 | PrimitiveType::U64 | PrimitiveType::Isize | PrimitiveType::Usize => {
1813                // Add 'L' suffix for long values if not already present
1814                if default.ends_with('L') || default.ends_with('l') {
1815                    default.to_string()
1816                } else if default.parse::<i64>().is_ok() {
1817                    format!("{}L", default)
1818                } else {
1819                    default.to_string()
1820                }
1821            }
1822            PrimitiveType::F32 => {
1823                // Add 'f' suffix for float values if not already present
1824                if default.ends_with('f') || default.ends_with('F') {
1825                    default.to_string()
1826                } else if default.parse::<f32>().is_ok() {
1827                    format!("{}f", default)
1828                } else {
1829                    default.to_string()
1830                }
1831            }
1832            PrimitiveType::F64 => {
1833                // Double defaults can have optional 'd' suffix, but 0.0 is fine
1834                default.to_string()
1835            }
1836            _ => default.to_string(),
1837        },
1838        _ => default.to_string(),
1839    };
1840
1841    format!("Optional.of({})", formatted_value)
1842}
1843
1844fn gen_builder_class(package: &str, typ: &TypeDef) -> String {
1845    let mut body = String::with_capacity(2048);
1846
1847    writeln!(body, "public class {}Builder {{", typ.name).ok();
1848    writeln!(body).ok();
1849
1850    // Generate field declarations with defaults
1851    for field in &typ.fields {
1852        let field_name = safe_java_field_name(&field.name);
1853
1854        // Skip unnamed tuple fields (name is "_0", "_1", "0", "1", etc.) — Java requires named fields
1855        if field.name.starts_with('_') && field.name[1..].chars().all(|c| c.is_ascii_digit())
1856            || field.name.chars().next().is_none_or(|c| c.is_ascii_digit())
1857        {
1858            continue;
1859        }
1860
1861        // Duration maps to primitive `long` in the public record, but in builder
1862        // classes we use boxed `Long` so that `null` can represent "not set".
1863        let field_type = if field.optional {
1864            format!("Optional<{}>", java_boxed_type(&field.ty))
1865        } else if matches!(field.ty, TypeRef::Duration) {
1866            java_boxed_type(&field.ty).to_string()
1867        } else {
1868            java_type(&field.ty).to_string()
1869        };
1870
1871        let default_value = if field.optional {
1872            // For Optional fields, always use Optional.empty() or Optional.of(value)
1873            if let Some(default) = &field.default {
1874                // If there's an explicit default, wrap it in Optional.of()
1875                format_optional_value(&field.ty, default)
1876            } else {
1877                // If no default, use Optional.empty()
1878                "Optional.empty()".to_string()
1879            }
1880        } else {
1881            // For non-Optional fields, use regular defaults
1882            if let Some(default) = &field.default {
1883                default.clone()
1884            } else {
1885                match &field.ty {
1886                    TypeRef::String | TypeRef::Char | TypeRef::Path => "\"\"".to_string(),
1887                    TypeRef::Json => "null".to_string(),
1888                    TypeRef::Bytes => "new byte[0]".to_string(),
1889                    TypeRef::Primitive(p) => match p {
1890                        PrimitiveType::Bool => "false".to_string(),
1891                        PrimitiveType::F32 | PrimitiveType::F64 => "0.0".to_string(),
1892                        _ => "0".to_string(),
1893                    },
1894                    TypeRef::Vec(_) => "List.of()".to_string(),
1895                    TypeRef::Map(_, _) => "Map.of()".to_string(),
1896                    TypeRef::Optional(_) => "Optional.empty()".to_string(),
1897                    TypeRef::Duration => "null".to_string(),
1898                    _ => "null".to_string(),
1899                }
1900            }
1901        };
1902
1903        writeln!(body, "    private {} {} = {};", field_type, field_name, default_value).ok();
1904    }
1905
1906    writeln!(body).ok();
1907
1908    // Generate withXxx() methods
1909    for field in &typ.fields {
1910        // Skip unnamed tuple fields (name is "_0", "_1", "0", "1", etc.) — Java requires named fields
1911        if field.name.starts_with('_') && field.name[1..].chars().all(|c| c.is_ascii_digit())
1912            || field.name.chars().next().is_none_or(|c| c.is_ascii_digit())
1913        {
1914            continue;
1915        }
1916
1917        let field_name = safe_java_field_name(&field.name);
1918        let field_name_pascal = to_class_name(&field.name);
1919        let field_type = if field.optional {
1920            format!("Optional<{}>", java_boxed_type(&field.ty))
1921        } else if matches!(field.ty, TypeRef::Duration) {
1922            java_boxed_type(&field.ty).to_string()
1923        } else {
1924            java_type(&field.ty).to_string()
1925        };
1926
1927        writeln!(
1928            body,
1929            "    public {}Builder with{}({} value) {{",
1930            typ.name, field_name_pascal, field_type
1931        )
1932        .ok();
1933        writeln!(body, "        this.{} = value;", field_name).ok();
1934        writeln!(body, "        return this;").ok();
1935        writeln!(body, "    }}").ok();
1936        writeln!(body).ok();
1937    }
1938
1939    // Generate build() method
1940    writeln!(body, "    public {} build() {{", typ.name).ok();
1941    writeln!(body, "        return new {}(", typ.name).ok();
1942    let non_tuple_fields: Vec<_> = typ
1943        .fields
1944        .iter()
1945        .filter(|f| {
1946            // Include named fields (skip unnamed tuple fields)
1947            !(f.name.starts_with('_') && f.name[1..].chars().all(|c| c.is_ascii_digit())
1948                || f.name.chars().next().is_none_or(|c| c.is_ascii_digit()))
1949        })
1950        .collect();
1951    for (i, field) in non_tuple_fields.iter().enumerate() {
1952        let field_name = safe_java_field_name(&field.name);
1953        let comma = if i < non_tuple_fields.len() - 1 { "," } else { "" };
1954        writeln!(body, "            {}{}", field_name, comma).ok();
1955    }
1956    writeln!(body, "        );").ok();
1957    writeln!(body, "    }}").ok();
1958
1959    writeln!(body, "}}").ok();
1960
1961    // Now assemble with conditional imports based on what's actually used in the body
1962    let mut out = String::with_capacity(body.len() + 512);
1963
1964    writeln!(out, "// DO NOT EDIT - auto-generated by alef").ok();
1965    writeln!(out, "package {};", package).ok();
1966    writeln!(out).ok();
1967
1968    if body.contains("List<") {
1969        writeln!(out, "import java.util.List;").ok();
1970    }
1971    if body.contains("Map<") {
1972        writeln!(out, "import java.util.Map;").ok();
1973    }
1974    if body.contains("Optional<") {
1975        writeln!(out, "import java.util.Optional;").ok();
1976    }
1977
1978    writeln!(out).ok();
1979    out.push_str(&body);
1980
1981    out
1982}