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);
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, "                return null;").ok();
720        writeln!(out, "            }}").ok();
721        writeln!(
722            out,
723            "            String result = resultPtr.reinterpret(Long.MAX_VALUE).getString(0);"
724        )
725        .ok();
726        writeln!(out, "            {}.invoke(resultPtr);", free_handle).ok();
727        writeln!(out, "            return result;").ok();
728        writeln!(out, "        }} catch (Throwable e) {{").ok();
729        writeln!(
730            out,
731            "            throw new {}Exception(\"FFI call failed\", e);",
732            class_name
733        )
734        .ok();
735        writeln!(out, "        }}").ok();
736    } else if matches!(func.return_type, TypeRef::Named(_)) {
737        // Named return types: FFI returns a struct pointer.
738        let return_type_name = match &func.return_type {
739            TypeRef::Named(name) => name,
740            _ => unreachable!(),
741        };
742        let is_opaque = opaque_types.contains(return_type_name.as_str());
743
744        writeln!(
745            out,
746            "            var resultPtr = (MemorySegment) {}.invoke({});",
747            ffi_handle,
748            call_args.join(", ")
749        )
750        .ok();
751        emit_ffi_ptr_cleanup(out);
752        writeln!(out, "            if (resultPtr.equals(MemorySegment.NULL)) {{").ok();
753        writeln!(out, "                return null;").ok();
754        writeln!(out, "            }}").ok();
755
756        if is_opaque {
757            // Opaque handles: wrap the raw pointer directly, caller owns and will close()
758            writeln!(out, "            return new {}(resultPtr);", return_type_name).ok();
759        } else {
760            // Record types: use _to_json to serialize the full struct to JSON, then deserialize.
761            // NOTE: _content only returns the markdown string field, not a full JSON object.
762            let type_snake = return_type_name.to_snake_case();
763            let free_handle = format!("NativeLib.{}_{}_FREE", prefix.to_uppercase(), type_snake.to_uppercase());
764            let to_json_handle = format!(
765                "NativeLib.{}_{}_TO_JSON",
766                prefix.to_uppercase(),
767                type_snake.to_uppercase()
768            );
769            writeln!(
770                out,
771                "            var jsonPtr = (MemorySegment) {}.invoke(resultPtr);",
772                to_json_handle
773            )
774            .ok();
775            writeln!(out, "            {}.invoke(resultPtr);", free_handle).ok();
776            writeln!(out, "            if (jsonPtr.equals(MemorySegment.NULL)) {{").ok();
777            writeln!(out, "                return null;").ok();
778            writeln!(out, "            }}").ok();
779            writeln!(
780                out,
781                "            String json = jsonPtr.reinterpret(Long.MAX_VALUE).getString(0);"
782            )
783            .ok();
784            writeln!(
785                out,
786                "            NativeLib.{}_FREE_STRING.invoke(jsonPtr);",
787                prefix.to_uppercase()
788            )
789            .ok();
790            writeln!(
791                out,
792                "            return createObjectMapper().readValue(json, {}.class);",
793                return_type_name
794            )
795            .ok();
796        }
797
798        writeln!(out, "        }} catch (Throwable e) {{").ok();
799        writeln!(
800            out,
801            "            throw new {}Exception(\"FFI call failed\", e);",
802            class_name
803        )
804        .ok();
805        writeln!(out, "        }}").ok();
806    } else if matches!(func.return_type, TypeRef::Vec(_)) {
807        // Vec return types: FFI returns a JSON string pointer; deserialize into List<T>.
808        let free_handle = format!("NativeLib.{}_FREE_STRING", prefix.to_uppercase());
809        writeln!(
810            out,
811            "            var resultPtr = (MemorySegment) {}.invoke({});",
812            ffi_handle,
813            call_args.join(", ")
814        )
815        .ok();
816        emit_ffi_ptr_cleanup(out);
817        writeln!(out, "            if (resultPtr.equals(MemorySegment.NULL)) {{").ok();
818        writeln!(out, "                return java.util.List.of();").ok();
819        writeln!(out, "            }}").ok();
820        writeln!(
821            out,
822            "            String json = resultPtr.reinterpret(Long.MAX_VALUE).getString(0);"
823        )
824        .ok();
825        writeln!(out, "            {}.invoke(resultPtr);", free_handle).ok();
826        // Determine the element type for deserialization
827        let element_type = match &func.return_type {
828            TypeRef::Vec(inner) => java_type(inner),
829            _ => unreachable!(),
830        };
831        writeln!(
832            out,
833            "            return createObjectMapper().readValue(json, new com.fasterxml.jackson.core.type.TypeReference<java.util.List<{}>>() {{ }});",
834            element_type
835        )
836        .ok();
837        writeln!(out, "        }} catch (Throwable e) {{").ok();
838        writeln!(
839            out,
840            "            throw new {}Exception(\"FFI call failed\", e);",
841            class_name
842        )
843        .ok();
844        writeln!(out, "        }}").ok();
845    } else {
846        writeln!(
847            out,
848            "            var primitiveResult = ({}) {}.invoke({});",
849            java_ffi_return_cast(&func.return_type),
850            ffi_handle,
851            call_args.join(", ")
852        )
853        .ok();
854        emit_ffi_ptr_cleanup(out);
855        writeln!(out, "            return primitiveResult;").ok();
856        writeln!(out, "        }} catch (Throwable e) {{").ok();
857        writeln!(
858            out,
859            "            throw new {}Exception(\"FFI call failed\", e);",
860            class_name
861        )
862        .ok();
863        writeln!(out, "        }}").ok();
864    }
865
866    writeln!(out, "    }}").ok();
867}
868
869fn gen_async_wrapper_method(out: &mut String, func: &FunctionDef) {
870    let params: Vec<String> = func
871        .params
872        .iter()
873        .map(|p| {
874            let ptype = java_type(&p.ty);
875            format!("{} {}", ptype, to_java_name(&p.name))
876        })
877        .collect();
878
879    let return_type = match &func.return_type {
880        TypeRef::Unit => "Void".to_string(),
881        other => java_boxed_type(other).to_string(),
882    };
883
884    let sync_method_name = to_java_name(&func.name);
885    let async_method_name = format!("{}Async", sync_method_name);
886    let param_names: Vec<String> = func.params.iter().map(|p| to_java_name(&p.name)).collect();
887
888    writeln!(
889        out,
890        "    public static CompletableFuture<{}> {}({}) {{",
891        return_type,
892        async_method_name,
893        params.join(", ")
894    )
895    .ok();
896    writeln!(out, "        return CompletableFuture.supplyAsync(() -> {{").ok();
897    writeln!(out, "            try {{").ok();
898    writeln!(
899        out,
900        "                return {}({});",
901        sync_method_name,
902        param_names.join(", ")
903    )
904    .ok();
905    writeln!(out, "            }} catch (Throwable e) {{").ok();
906    writeln!(out, "                throw new CompletionException(e);").ok();
907    writeln!(out, "            }}").ok();
908    writeln!(out, "        }});").ok();
909    writeln!(out, "    }}").ok();
910}
911
912// ---------------------------------------------------------------------------
913// Exception class
914// ---------------------------------------------------------------------------
915
916fn gen_exception_class(package: &str, class_name: &str) -> String {
917    let mut out = String::with_capacity(512);
918
919    writeln!(out, "// DO NOT EDIT - auto-generated by alef").ok();
920    writeln!(out, "package {};", package).ok();
921    writeln!(out).ok();
922
923    writeln!(out, "public class {}Exception extends Exception {{", class_name).ok();
924    writeln!(out, "    private final int code;").ok();
925    writeln!(out).ok();
926    writeln!(out, "    public {}Exception(int code, String message) {{", class_name).ok();
927    writeln!(out, "        super(message);").ok();
928    writeln!(out, "        this.code = code;").ok();
929    writeln!(out, "    }}").ok();
930    writeln!(out).ok();
931    writeln!(
932        out,
933        "    public {}Exception(String message, Throwable cause) {{",
934        class_name
935    )
936    .ok();
937    writeln!(out, "        super(message, cause);").ok();
938    writeln!(out, "        this.code = -1;").ok();
939    writeln!(out, "    }}").ok();
940    writeln!(out).ok();
941    writeln!(out, "    public int getCode() {{").ok();
942    writeln!(out, "        return code;").ok();
943    writeln!(out, "    }}").ok();
944    writeln!(out, "}}").ok();
945
946    out
947}
948
949// ---------------------------------------------------------------------------
950// High-level facade class (public API)
951// ---------------------------------------------------------------------------
952
953fn gen_facade_class(api: &ApiSurface, package: &str, public_class: &str, raw_class: &str, _prefix: &str) -> String {
954    let mut body = String::with_capacity(4096);
955
956    writeln!(body, "public final class {} {{", public_class).ok();
957    writeln!(body, "    private {}() {{ }}", public_class).ok();
958    writeln!(body).ok();
959
960    // Generate static methods for free functions
961    for func in &api.functions {
962        // Sync method
963        let params: Vec<String> = func
964            .params
965            .iter()
966            .map(|p| {
967                let ptype = java_type(&p.ty);
968                format!("{} {}", ptype, to_java_name(&p.name))
969            })
970            .collect();
971
972        let return_type = java_type(&func.return_type);
973
974        if !func.doc.is_empty() {
975            writeln!(body, "    /**").ok();
976            for line in func.doc.lines() {
977                writeln!(body, "     * {}", line).ok();
978            }
979            writeln!(body, "     */").ok();
980        }
981
982        writeln!(
983            body,
984            "    public static {} {}({}) throws {}Exception {{",
985            return_type,
986            to_java_name(&func.name),
987            params.join(", "),
988            raw_class
989        )
990        .ok();
991
992        // Null checks for required parameters
993        for param in &func.params {
994            if !param.optional {
995                let pname = to_java_name(&param.name);
996                writeln!(
997                    body,
998                    "        java.util.Objects.requireNonNull({}, \"{} must not be null\");",
999                    pname, pname
1000                )
1001                .ok();
1002            }
1003        }
1004
1005        // Delegate to the raw FFI class
1006        let call_args: Vec<String> = func.params.iter().map(|p| to_java_name(&p.name)).collect();
1007
1008        if matches!(func.return_type, TypeRef::Unit) {
1009            writeln!(
1010                body,
1011                "        {}.{}({});",
1012                raw_class,
1013                to_java_name(&func.name),
1014                call_args.join(", ")
1015            )
1016            .ok();
1017        } else {
1018            writeln!(
1019                body,
1020                "        return {}.{}({});",
1021                raw_class,
1022                to_java_name(&func.name),
1023                call_args.join(", ")
1024            )
1025            .ok();
1026        }
1027
1028        writeln!(body, "    }}").ok();
1029        writeln!(body).ok();
1030
1031        // Generate overload without optional params (convenience method)
1032        let has_optional = func.params.iter().any(|p| p.optional);
1033        if has_optional {
1034            let required_params: Vec<String> = func
1035                .params
1036                .iter()
1037                .filter(|p| !p.optional)
1038                .map(|p| {
1039                    let ptype = java_type(&p.ty);
1040                    format!("{} {}", ptype, to_java_name(&p.name))
1041                })
1042                .collect();
1043
1044            writeln!(
1045                body,
1046                "    public static {} {}({}) throws {}Exception {{",
1047                return_type,
1048                to_java_name(&func.name),
1049                required_params.join(", "),
1050                raw_class
1051            )
1052            .ok();
1053
1054            // Build call with null for optional params
1055            let full_args: Vec<String> = func
1056                .params
1057                .iter()
1058                .map(|p| {
1059                    if p.optional {
1060                        "null".to_string()
1061                    } else {
1062                        to_java_name(&p.name)
1063                    }
1064                })
1065                .collect();
1066
1067            if matches!(func.return_type, TypeRef::Unit) {
1068                writeln!(body, "        {}({});", to_java_name(&func.name), full_args.join(", ")).ok();
1069            } else {
1070                writeln!(
1071                    body,
1072                    "        return {}({});",
1073                    to_java_name(&func.name),
1074                    full_args.join(", ")
1075                )
1076                .ok();
1077            }
1078
1079            writeln!(body, "    }}").ok();
1080            writeln!(body).ok();
1081        }
1082    }
1083
1084    writeln!(body, "}}").ok();
1085
1086    // Now assemble the file with imports
1087    let mut out = String::with_capacity(body.len() + 512);
1088
1089    writeln!(out, "// DO NOT EDIT - auto-generated by alef").ok();
1090    writeln!(out, "package {};", package).ok();
1091
1092    // Check what imports are needed based on content
1093    let has_list = body.contains("List<");
1094    let has_map = body.contains("Map<");
1095    let has_optional = body.contains("Optional<");
1096    let has_imports = has_list || has_map || has_optional;
1097
1098    if has_imports {
1099        writeln!(out).ok();
1100        if has_list {
1101            writeln!(out, "import java.util.List;").ok();
1102        }
1103        if has_map {
1104            writeln!(out, "import java.util.Map;").ok();
1105        }
1106        if has_optional {
1107            writeln!(out, "import java.util.Optional;").ok();
1108        }
1109    }
1110
1111    writeln!(out).ok();
1112    out.push_str(&body);
1113
1114    out
1115}
1116
1117// ---------------------------------------------------------------------------
1118// Opaque handle classes
1119// ---------------------------------------------------------------------------
1120
1121fn gen_opaque_handle_class(package: &str, typ: &TypeDef, prefix: &str) -> String {
1122    let mut out = String::with_capacity(1024);
1123    let class_name = &typ.name;
1124    let type_snake = class_name.to_snake_case();
1125
1126    writeln!(out, "// DO NOT EDIT - auto-generated by alef").ok();
1127    writeln!(out, "package {};", package).ok();
1128    writeln!(out).ok();
1129    writeln!(out, "import java.lang.foreign.MemorySegment;").ok();
1130    writeln!(out).ok();
1131
1132    if !typ.doc.is_empty() {
1133        writeln!(out, "/**").ok();
1134        for line in typ.doc.lines() {
1135            writeln!(out, " * {}", line).ok();
1136        }
1137        writeln!(out, " */").ok();
1138    }
1139
1140    writeln!(out, "public class {} implements AutoCloseable {{", class_name).ok();
1141    writeln!(out, "    private final MemorySegment handle;").ok();
1142    writeln!(out).ok();
1143    writeln!(out, "    {}(MemorySegment handle) {{", class_name).ok();
1144    writeln!(out, "        this.handle = handle;").ok();
1145    writeln!(out, "    }}").ok();
1146    writeln!(out).ok();
1147    writeln!(out, "    MemorySegment handle() {{").ok();
1148    writeln!(out, "        return this.handle;").ok();
1149    writeln!(out, "    }}").ok();
1150    writeln!(out).ok();
1151    writeln!(out, "    @Override").ok();
1152    writeln!(out, "    public void close() {{").ok();
1153    writeln!(
1154        out,
1155        "        if (handle != null && !handle.equals(MemorySegment.NULL)) {{"
1156    )
1157    .ok();
1158    writeln!(out, "            try {{").ok();
1159    writeln!(
1160        out,
1161        "                NativeLib.{}_{}_FREE.invoke(handle);",
1162        prefix.to_uppercase(),
1163        type_snake.to_uppercase()
1164    )
1165    .ok();
1166    writeln!(out, "            }} catch (Throwable e) {{").ok();
1167    writeln!(
1168        out,
1169        "                throw new RuntimeException(\"Failed to free {}: \" + e.getMessage(), e);",
1170        class_name
1171    )
1172    .ok();
1173    writeln!(out, "            }}").ok();
1174    writeln!(out, "        }}").ok();
1175    writeln!(out, "    }}").ok();
1176    writeln!(out, "}}").ok();
1177
1178    out
1179}
1180
1181// ---------------------------------------------------------------------------
1182// Record types (Java records)
1183// ---------------------------------------------------------------------------
1184
1185/// Maximum line length before splitting record fields across multiple lines.
1186/// Checkstyle enforces 120 chars; we split at 100 to leave headroom for indentation.
1187const RECORD_LINE_WRAP_THRESHOLD: usize = 100;
1188
1189fn gen_record_type(package: &str, typ: &TypeDef, complex_enums: &AHashSet<String>, lang_rename_all: &str) -> String {
1190    // Generate the record body first, then scan for needed imports.
1191    // For each field, if the language uses camelCase but the JSON key is snake_case
1192    // (the Rust default), annotate with @JsonProperty so Jackson maps correctly.
1193    let field_list: Vec<String> = typ
1194        .fields
1195        .iter()
1196        .map(|f| {
1197            // Complex enums (tagged unions with data) can't be simple Java enums.
1198            // Use Object for flexible Jackson deserialization.
1199            let is_complex = matches!(&f.ty, TypeRef::Named(n) if complex_enums.contains(n.as_str()));
1200            let ftype = if is_complex {
1201                "Object".to_string()
1202            } else if f.optional {
1203                format!("Optional<{}>", java_boxed_type(&f.ty))
1204            } else {
1205                java_type(&f.ty).to_string()
1206            };
1207            let jname = safe_java_field_name(&f.name);
1208            // When the language convention is camelCase but the JSON wire format uses
1209            // snake_case (the Rust/serde default), add an explicit @JsonProperty annotation
1210            // so Jackson serialises/deserialises using the correct snake_case key.
1211            if lang_rename_all == "camelCase" && f.name.contains('_') {
1212                format!("@JsonProperty(\"{}\") {} {}", f.name, ftype, jname)
1213            } else {
1214                format!("{} {}", ftype, jname)
1215            }
1216        })
1217        .collect();
1218
1219    // Build the single-line form to check length and scan for imports.
1220    let single_line = format!("public record {}({}) {{ }}", typ.name, field_list.join(", "));
1221
1222    // Build the actual record declaration, splitting across lines if too long.
1223    let mut record_block = String::new();
1224    if single_line.len() > RECORD_LINE_WRAP_THRESHOLD && field_list.len() > 1 {
1225        writeln!(record_block, "public record {}(", typ.name).ok();
1226        for (i, field) in field_list.iter().enumerate() {
1227            let comma = if i < field_list.len() - 1 { "," } else { "" };
1228            writeln!(record_block, "    {}{}", field, comma).ok();
1229        }
1230        writeln!(record_block, ") {{").ok();
1231    } else {
1232        writeln!(record_block, "public record {}({}) {{", typ.name, field_list.join(", ")).ok();
1233    }
1234
1235    // Add builder() factory method if type has defaults
1236    if typ.has_default {
1237        writeln!(record_block, "    public static {}Builder builder() {{", typ.name).ok();
1238        writeln!(record_block, "        return new {}Builder();", typ.name).ok();
1239        writeln!(record_block, "    }}").ok();
1240    }
1241
1242    writeln!(record_block, "}}").ok();
1243
1244    // Scan the single-line form to determine which imports are needed
1245    let needs_json_property = field_list.iter().any(|f| f.contains("@JsonProperty("));
1246    let mut out = String::with_capacity(record_block.len() + 512);
1247    writeln!(out, "// DO NOT EDIT - auto-generated by alef").ok();
1248    writeln!(out, "package {};", package).ok();
1249    writeln!(out).ok();
1250    if single_line.contains("List<") {
1251        writeln!(out, "import java.util.List;").ok();
1252    }
1253    if single_line.contains("Map<") {
1254        writeln!(out, "import java.util.Map;").ok();
1255    }
1256    if single_line.contains("Optional<") {
1257        writeln!(out, "import java.util.Optional;").ok();
1258    }
1259    if needs_json_property {
1260        writeln!(out, "import com.fasterxml.jackson.annotation.JsonProperty;").ok();
1261    }
1262    writeln!(out).ok();
1263    write!(out, "{}", record_block).ok();
1264
1265    out
1266}
1267
1268// ---------------------------------------------------------------------------
1269// Enum classes
1270// ---------------------------------------------------------------------------
1271
1272/// Apply a serde `rename_all` strategy to a variant name for Java codegen.
1273fn java_apply_rename_all(name: &str, rename_all: Option<&str>) -> String {
1274    match rename_all {
1275        Some("snake_case") => name.to_snake_case(),
1276        Some("camelCase") => name.to_lower_camel_case(),
1277        Some("PascalCase") => name.to_pascal_case(),
1278        Some("SCREAMING_SNAKE_CASE") => name.to_snake_case().to_uppercase(),
1279        Some("lowercase") => name.to_lowercase(),
1280        Some("UPPERCASE") => name.to_uppercase(),
1281        _ => name.to_lowercase(),
1282    }
1283}
1284
1285fn gen_enum_class(package: &str, enum_def: &EnumDef) -> String {
1286    let has_data_variants = enum_def.variants.iter().any(|v| !v.fields.is_empty());
1287
1288    // Tagged union: enum has a serde tag AND data variants → generate sealed interface hierarchy
1289    if enum_def.serde_tag.is_some() && has_data_variants {
1290        return gen_java_tagged_union(package, enum_def);
1291    }
1292
1293    let mut out = String::with_capacity(1024);
1294
1295    writeln!(out, "// DO NOT EDIT - auto-generated by alef").ok();
1296    writeln!(out, "package {};", package).ok();
1297    writeln!(out).ok();
1298    writeln!(out, "import com.fasterxml.jackson.annotation.JsonCreator;").ok();
1299    writeln!(out, "import com.fasterxml.jackson.annotation.JsonValue;").ok();
1300    writeln!(out).ok();
1301
1302    writeln!(out, "public enum {} {{", enum_def.name).ok();
1303
1304    for (i, variant) in enum_def.variants.iter().enumerate() {
1305        let comma = if i < enum_def.variants.len() - 1 { "," } else { ";" };
1306        // Use serde_rename if available, otherwise apply rename_all strategy
1307        let json_name = variant
1308            .serde_rename
1309            .clone()
1310            .unwrap_or_else(|| java_apply_rename_all(&variant.name, enum_def.serde_rename_all.as_deref()));
1311        writeln!(out, "    {}(\"{}\"){}", variant.name, json_name, comma).ok();
1312    }
1313
1314    writeln!(out).ok();
1315    writeln!(out, "    private final String value;").ok();
1316    writeln!(out).ok();
1317    writeln!(out, "    {}(String value) {{", enum_def.name).ok();
1318    writeln!(out, "        this.value = value;").ok();
1319    writeln!(out, "    }}").ok();
1320    writeln!(out).ok();
1321    writeln!(out, "    @JsonValue").ok();
1322    writeln!(out, "    public String getValue() {{").ok();
1323    writeln!(out, "        return value;").ok();
1324    writeln!(out, "    }}").ok();
1325    writeln!(out).ok();
1326    writeln!(out, "    @JsonCreator").ok();
1327    writeln!(out, "    public static {} fromValue(String value) {{", enum_def.name).ok();
1328    writeln!(out, "        for ({} e : values()) {{", enum_def.name).ok();
1329    writeln!(out, "            if (e.value.equalsIgnoreCase(value)) {{").ok();
1330    writeln!(out, "                return e;").ok();
1331    writeln!(out, "            }}").ok();
1332    writeln!(out, "        }}").ok();
1333    writeln!(
1334        out,
1335        "        throw new IllegalArgumentException(\"Unknown value: \" + value);"
1336    )
1337    .ok();
1338    writeln!(out, "    }}").ok();
1339
1340    writeln!(out, "}}").ok();
1341
1342    out
1343}
1344
1345/// Generate a Java sealed interface hierarchy for internally tagged enums.
1346///
1347/// Maps `#[serde(tag = "type_field", rename_all = "snake_case")]` Rust enums to
1348/// `@JsonTypeInfo` / `@JsonSubTypes` Java sealed interfaces with record implementations.
1349fn gen_java_tagged_union(package: &str, enum_def: &EnumDef) -> String {
1350    let tag_field = enum_def.serde_tag.as_deref().unwrap_or("type");
1351
1352    // Collect variant names to detect Java type name conflicts.
1353    // If a variant is named "List", "Map", or "Optional", using those type names
1354    // inside the sealed interface would refer to the nested record, not java.util.*.
1355    // We use fully qualified names in that case.
1356    let variant_names: std::collections::HashSet<&str> = enum_def.variants.iter().map(|v| v.name.as_str()).collect();
1357    let optional_type = if variant_names.contains("Optional") {
1358        "java.util.Optional"
1359    } else {
1360        "Optional"
1361    };
1362
1363    let mut out = String::with_capacity(2048);
1364    writeln!(out, "// DO NOT EDIT - auto-generated by alef").ok();
1365    writeln!(out, "package {};", package).ok();
1366    writeln!(out).ok();
1367    writeln!(out, "import com.fasterxml.jackson.annotation.JsonProperty;").ok();
1368    writeln!(out, "import com.fasterxml.jackson.annotation.JsonSubTypes;").ok();
1369    writeln!(out, "import com.fasterxml.jackson.annotation.JsonTypeInfo;").ok();
1370
1371    // Check if any field types need list/map/optional imports (only when not conflicting)
1372    let needs_list = !variant_names.contains("List")
1373        && enum_def
1374            .variants
1375            .iter()
1376            .any(|v| v.fields.iter().any(|f| matches!(&f.ty, TypeRef::Vec(_))));
1377    let needs_map = !variant_names.contains("Map")
1378        && enum_def
1379            .variants
1380            .iter()
1381            .any(|v| v.fields.iter().any(|f| matches!(&f.ty, TypeRef::Map(_, _))));
1382    let needs_optional =
1383        !variant_names.contains("Optional") && enum_def.variants.iter().any(|v| v.fields.iter().any(|f| f.optional));
1384    if needs_list {
1385        writeln!(out, "import java.util.List;").ok();
1386    }
1387    if needs_map {
1388        writeln!(out, "import java.util.Map;").ok();
1389    }
1390    if needs_optional {
1391        writeln!(out, "import java.util.Optional;").ok();
1392    }
1393    writeln!(out).ok();
1394
1395    // @JsonTypeInfo and @JsonSubTypes annotations
1396    writeln!(
1397        out,
1398        "@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = \"{tag_field}\", visible = false)"
1399    )
1400    .ok();
1401    writeln!(out, "@JsonSubTypes({{").ok();
1402    for (i, variant) in enum_def.variants.iter().enumerate() {
1403        let discriminator = variant
1404            .serde_rename
1405            .clone()
1406            .unwrap_or_else(|| java_apply_rename_all(&variant.name, enum_def.serde_rename_all.as_deref()));
1407        let comma = if i < enum_def.variants.len() - 1 { "," } else { "" };
1408        writeln!(
1409            out,
1410            "    @JsonSubTypes.Type(value = {}.{}.class, name = \"{}\"){}",
1411            enum_def.name, variant.name, discriminator, comma
1412        )
1413        .ok();
1414    }
1415    writeln!(out, "}})").ok();
1416    writeln!(out, "public sealed interface {} {{", enum_def.name).ok();
1417
1418    // Nested records for each variant
1419    for variant in &enum_def.variants {
1420        writeln!(out).ok();
1421        if variant.fields.is_empty() {
1422            // Unit variant
1423            writeln!(out, "    record {}() implements {} {{", variant.name, enum_def.name).ok();
1424            writeln!(out, "    }}").ok();
1425        } else {
1426            // Build field list using fully qualified names where variant names shadow imports
1427            let field_parts: Vec<String> = variant
1428                .fields
1429                .iter()
1430                .map(|f| {
1431                    let json_name = f.name.trim_start_matches('_');
1432                    let ftype = if f.optional {
1433                        let inner = java_boxed_type(&f.ty);
1434                        let inner_str = inner.as_ref();
1435                        // Replace "List"/"Map" with fully qualified if conflicting
1436                        let inner_qualified = if inner_str.starts_with("List<") && variant_names.contains("List") {
1437                            inner_str.replacen("List<", "java.util.List<", 1)
1438                        } else if inner_str.starts_with("Map<") && variant_names.contains("Map") {
1439                            inner_str.replacen("Map<", "java.util.Map<", 1)
1440                        } else {
1441                            inner_str.to_string()
1442                        };
1443                        format!("{optional_type}<{inner_qualified}>")
1444                    } else {
1445                        let t = java_type(&f.ty);
1446                        let t_str = t.as_ref();
1447                        if t_str.starts_with("List<") && variant_names.contains("List") {
1448                            t_str.replacen("List<", "java.util.List<", 1)
1449                        } else if t_str.starts_with("Map<") && variant_names.contains("Map") {
1450                            t_str.replacen("Map<", "java.util.Map<", 1)
1451                        } else {
1452                            t_str.to_string()
1453                        }
1454                    };
1455                    let jname = safe_java_field_name(json_name);
1456                    format!("@JsonProperty(\"{json_name}\") {ftype} {jname}")
1457                })
1458                .collect();
1459
1460            let single = format!(
1461                "    record {}({}) implements {} {{ }}",
1462                variant.name,
1463                field_parts.join(", "),
1464                enum_def.name
1465            );
1466
1467            if single.len() > RECORD_LINE_WRAP_THRESHOLD && field_parts.len() > 1 {
1468                writeln!(out, "    record {}(", variant.name).ok();
1469                for (i, fp) in field_parts.iter().enumerate() {
1470                    let comma = if i < field_parts.len() - 1 { "," } else { "" };
1471                    writeln!(out, "        {}{}", fp, comma).ok();
1472                }
1473                writeln!(out, "    ) implements {} {{", enum_def.name).ok();
1474                writeln!(out, "    }}").ok();
1475            } else {
1476                writeln!(
1477                    out,
1478                    "    record {}({}) implements {} {{ }}",
1479                    variant.name,
1480                    field_parts.join(", "),
1481                    enum_def.name
1482                )
1483                .ok();
1484            }
1485        }
1486    }
1487
1488    writeln!(out).ok();
1489    writeln!(out, "}}").ok();
1490    out
1491}
1492
1493// ---------------------------------------------------------------------------
1494// Helper functions for FFI marshalling
1495// ---------------------------------------------------------------------------
1496
1497fn gen_ffi_layout(ty: &TypeRef) -> String {
1498    match ty {
1499        TypeRef::Primitive(prim) => java_ffi_type(prim).to_string(),
1500        TypeRef::String | TypeRef::Char | TypeRef::Path | TypeRef::Json => "ValueLayout.ADDRESS".to_string(),
1501        TypeRef::Bytes => "ValueLayout.ADDRESS".to_string(),
1502        TypeRef::Optional(inner) => gen_ffi_layout(inner),
1503        TypeRef::Vec(_) => "ValueLayout.ADDRESS".to_string(),
1504        TypeRef::Map(_, _) => "ValueLayout.ADDRESS".to_string(),
1505        TypeRef::Named(_) => "ValueLayout.ADDRESS".to_string(),
1506        TypeRef::Unit => "".to_string(),
1507        TypeRef::Duration => "ValueLayout.JAVA_LONG".to_string(),
1508    }
1509}
1510
1511fn marshal_param_to_ffi(out: &mut String, name: &str, ty: &TypeRef, opaque_types: &AHashSet<String>, prefix: &str) {
1512    match ty {
1513        TypeRef::String | TypeRef::Char | TypeRef::Path | TypeRef::Json => {
1514            let cname = "c".to_string() + name;
1515            writeln!(out, "            var {} = arena.allocateFrom({});", cname, name).ok();
1516        }
1517        TypeRef::Named(type_name) => {
1518            let cname = "c".to_string() + name;
1519            if opaque_types.contains(type_name.as_str()) {
1520                // Opaque handles: pass the inner MemorySegment via .handle()
1521                writeln!(out, "            var {} = {}.handle();", cname, name).ok();
1522            } else {
1523                // Non-opaque named types: serialize to JSON, call _from_json to get FFI pointer.
1524                // The pointer must be freed after the FFI call with _free.
1525                let type_snake = type_name.to_snake_case();
1526                let from_json_handle = format!(
1527                    "NativeLib.{}_{}_FROM_JSON",
1528                    prefix.to_uppercase(),
1529                    type_snake.to_uppercase()
1530                );
1531                let _free_handle = format!("NativeLib.{}_{}_FREE", prefix.to_uppercase(), type_snake.to_uppercase());
1532                writeln!(
1533                    out,
1534                    "            var {}Json = {} != null ? createObjectMapper().writeValueAsString({}) : null;",
1535                    cname, name, name
1536                )
1537                .ok();
1538                writeln!(
1539                    out,
1540                    "            var {}JsonSeg = {}Json != null ? arena.allocateFrom({}Json) : MemorySegment.NULL;",
1541                    cname, cname, cname
1542                )
1543                .ok();
1544                writeln!(out, "            var {} = {}Json != null", cname, cname).ok();
1545                writeln!(
1546                    out,
1547                    "                ? (MemorySegment) {}.invoke({}JsonSeg)",
1548                    from_json_handle, cname
1549                )
1550                .ok();
1551                writeln!(out, "                : MemorySegment.NULL;").ok();
1552            }
1553        }
1554        TypeRef::Optional(inner) => {
1555            // For optional types, marshal the inner type if not null
1556            match inner.as_ref() {
1557                TypeRef::String | TypeRef::Char | TypeRef::Path | TypeRef::Json => {
1558                    let cname = "c".to_string() + name;
1559                    writeln!(
1560                        out,
1561                        "            var {} = {} != null ? arena.allocateFrom({}) : MemorySegment.NULL;",
1562                        cname, name, name
1563                    )
1564                    .ok();
1565                }
1566                TypeRef::Named(type_name) => {
1567                    let cname = "c".to_string() + name;
1568                    if opaque_types.contains(type_name.as_str()) {
1569                        writeln!(
1570                            out,
1571                            "            var {} = {} != null ? {}.handle() : MemorySegment.NULL;",
1572                            cname, name, name
1573                        )
1574                        .ok();
1575                    } else {
1576                        // Non-opaque named type in Optional: serialize to JSON and call _from_json
1577                        let type_snake = type_name.to_snake_case();
1578                        let from_json_handle = format!(
1579                            "NativeLib.{}_{}_FROM_JSON",
1580                            prefix.to_uppercase(),
1581                            type_snake.to_uppercase()
1582                        );
1583                        writeln!(
1584                            out,
1585                            "            var {}Json = {} != null ? createObjectMapper().writeValueAsString({}) : null;",
1586                            cname, name, name
1587                        )
1588                        .ok();
1589                        writeln!(out, "            var {}JsonSeg = {}Json != null ? arena.allocateFrom({}Json) : MemorySegment.NULL;", cname, cname, cname).ok();
1590                        writeln!(out, "            var {} = {}Json != null", cname, cname).ok();
1591                        writeln!(
1592                            out,
1593                            "                ? (MemorySegment) {}.invoke({}JsonSeg)",
1594                            from_json_handle, cname
1595                        )
1596                        .ok();
1597                        writeln!(out, "                : MemorySegment.NULL;").ok();
1598                    }
1599                }
1600                _ => {
1601                    // Other optional types (primitives) pass through
1602                }
1603            }
1604        }
1605        _ => {
1606            // Primitives and others pass through directly
1607        }
1608    }
1609}
1610
1611fn ffi_param_name(name: &str, ty: &TypeRef, _opaque_types: &AHashSet<String>) -> String {
1612    match ty {
1613        TypeRef::String | TypeRef::Char | TypeRef::Path | TypeRef::Json => "c".to_string() + name,
1614        TypeRef::Named(_) => "c".to_string() + name,
1615        TypeRef::Optional(inner) => match inner.as_ref() {
1616            TypeRef::String | TypeRef::Char | TypeRef::Path | TypeRef::Json | TypeRef::Named(_) => {
1617                "c".to_string() + name
1618            }
1619            _ => name.to_string(),
1620        },
1621        _ => name.to_string(),
1622    }
1623}
1624
1625/// Build a `FunctionDescriptor` string for a given return layout and parameter layouts.
1626/// Handles void returns (ofVoid) and non-void returns (of) correctly.
1627fn gen_function_descriptor(return_layout: &str, param_layouts: &[String]) -> String {
1628    if return_layout.is_empty() {
1629        // Void return
1630        if param_layouts.is_empty() {
1631            "FunctionDescriptor.ofVoid()".to_string()
1632        } else {
1633            format!("FunctionDescriptor.ofVoid({})", param_layouts.join(", "))
1634        }
1635    } else {
1636        // Non-void return
1637        if param_layouts.is_empty() {
1638            format!("FunctionDescriptor.of({})", return_layout)
1639        } else {
1640            format!("FunctionDescriptor.of({}, {})", return_layout, param_layouts.join(", "))
1641        }
1642    }
1643}
1644
1645/// Returns true if the given return type maps to an FFI ADDRESS that represents a string
1646/// (i.e. the FFI returns `*mut c_char` which must be unmarshaled and freed).
1647fn is_ffi_string_return(ty: &TypeRef) -> bool {
1648    match ty {
1649        TypeRef::String | TypeRef::Char | TypeRef::Path | TypeRef::Json => true,
1650        TypeRef::Optional(inner) => is_ffi_string_return(inner),
1651        _ => false,
1652    }
1653}
1654
1655/// Returns the appropriate Java cast type for non-string FFI return values.
1656fn java_ffi_return_cast(ty: &TypeRef) -> &'static str {
1657    match ty {
1658        TypeRef::Primitive(prim) => match prim {
1659            PrimitiveType::Bool => "boolean",
1660            PrimitiveType::U8 | PrimitiveType::I8 => "byte",
1661            PrimitiveType::U16 | PrimitiveType::I16 => "short",
1662            PrimitiveType::U32 | PrimitiveType::I32 => "int",
1663            PrimitiveType::U64 | PrimitiveType::I64 | PrimitiveType::Usize | PrimitiveType::Isize => "long",
1664            PrimitiveType::F32 => "float",
1665            PrimitiveType::F64 => "double",
1666        },
1667        TypeRef::Bytes | TypeRef::Vec(_) | TypeRef::Map(_, _) | TypeRef::Named(_) => "MemorySegment",
1668        _ => "MemorySegment",
1669    }
1670}
1671
1672fn gen_helper_methods(out: &mut String) {
1673    // Only emit helper methods that are actually called in the generated body.
1674    let needs_read_cstring = out.contains("readCString(");
1675    let needs_read_bytes = out.contains("readBytes(");
1676    let needs_create_object_mapper = out.contains("createObjectMapper()");
1677
1678    if !needs_read_cstring && !needs_read_bytes && !needs_create_object_mapper {
1679        return;
1680    }
1681
1682    writeln!(out, "    // Helper methods for FFI marshalling").ok();
1683    writeln!(out).ok();
1684
1685    if needs_create_object_mapper {
1686        // Emit a configured ObjectMapper factory:
1687        //   - findAndRegisterModules() to pick up jackson-datatype-jdk8 (Optional support)
1688        //   - ACCEPT_CASE_INSENSITIVE_ENUMS so enum names like "json_ld" match JsonLd, etc.
1689        // Field name mapping relies on explicit @JsonProperty annotations on record components
1690        // (generated by alef for snake_case FFI fields on camelCase Java records).
1691        writeln!(
1692            out,
1693            "    private static com.fasterxml.jackson.databind.ObjectMapper createObjectMapper() {{"
1694        )
1695        .ok();
1696        writeln!(out, "        return new com.fasterxml.jackson.databind.ObjectMapper()").ok();
1697        writeln!(out, "            .findAndRegisterModules()").ok();
1698        writeln!(
1699            out,
1700            "            .setSerializationInclusion(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL)"
1701        )
1702        .ok();
1703        writeln!(
1704            out,
1705            "            .setSerializationInclusion(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_DEFAULT)"
1706        )
1707        .ok();
1708        writeln!(
1709            out,
1710            "            .configure(com.fasterxml.jackson.databind.MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS, true);"
1711        )
1712        .ok();
1713        writeln!(out, "    }}").ok();
1714        writeln!(out).ok();
1715    }
1716
1717    if needs_read_cstring {
1718        writeln!(out, "    private static String readCString(MemorySegment ptr) {{").ok();
1719        writeln!(out, "        if (ptr == null || ptr.address() == 0) {{").ok();
1720        writeln!(out, "            return null;").ok();
1721        writeln!(out, "        }}").ok();
1722        writeln!(out, "        return ptr.getUtf8String(0);").ok();
1723        writeln!(out, "    }}").ok();
1724        writeln!(out).ok();
1725    }
1726
1727    if needs_read_bytes {
1728        writeln!(
1729            out,
1730            "    private static byte[] readBytes(MemorySegment ptr, long len) {{"
1731        )
1732        .ok();
1733        writeln!(out, "        if (ptr == null || ptr.address() == 0) {{").ok();
1734        writeln!(out, "            return new byte[0];").ok();
1735        writeln!(out, "        }}").ok();
1736        writeln!(out, "        byte[] bytes = new byte[(int) len];").ok();
1737        writeln!(
1738            out,
1739            "        MemorySegment.copy(ptr, ValueLayout.JAVA_BYTE.byteSize() * 0, bytes, 0, (int) len);"
1740        )
1741        .ok();
1742        writeln!(out, "        return bytes;").ok();
1743        writeln!(out, "    }}").ok();
1744    }
1745}
1746
1747// ---------------------------------------------------------------------------
1748// Builder class for types with defaults
1749// ---------------------------------------------------------------------------
1750
1751/// Format a default value for an Optional field, wrapping it in Optional.of()
1752/// with proper Java literal syntax.
1753fn format_optional_value(ty: &TypeRef, default: &str) -> String {
1754    // Check if the default is already wrapped (e.g., "Optional.of(...)" or "Optional.empty()")
1755    if default.contains("Optional.") {
1756        return default.to_string();
1757    }
1758
1759    // Unwrap Optional types to get the inner type
1760    let inner_ty = match ty {
1761        TypeRef::Optional(inner) => inner.as_ref(),
1762        other => other,
1763    };
1764
1765    // Determine the proper literal suffix based on type
1766    let formatted_value = match inner_ty {
1767        TypeRef::Primitive(p) => match p {
1768            PrimitiveType::I64 | PrimitiveType::U64 | PrimitiveType::Isize | PrimitiveType::Usize => {
1769                // Add 'L' suffix for long values if not already present
1770                if default.ends_with('L') || default.ends_with('l') {
1771                    default.to_string()
1772                } else if default.parse::<i64>().is_ok() {
1773                    format!("{}L", default)
1774                } else {
1775                    default.to_string()
1776                }
1777            }
1778            PrimitiveType::F32 => {
1779                // Add 'f' suffix for float values if not already present
1780                if default.ends_with('f') || default.ends_with('F') {
1781                    default.to_string()
1782                } else if default.parse::<f32>().is_ok() {
1783                    format!("{}f", default)
1784                } else {
1785                    default.to_string()
1786                }
1787            }
1788            PrimitiveType::F64 => {
1789                // Double defaults can have optional 'd' suffix, but 0.0 is fine
1790                default.to_string()
1791            }
1792            _ => default.to_string(),
1793        },
1794        _ => default.to_string(),
1795    };
1796
1797    format!("Optional.of({})", formatted_value)
1798}
1799
1800fn gen_builder_class(package: &str, typ: &TypeDef) -> String {
1801    let mut body = String::with_capacity(2048);
1802
1803    writeln!(body, "public class {}Builder {{", typ.name).ok();
1804    writeln!(body).ok();
1805
1806    // Generate field declarations with defaults
1807    for field in &typ.fields {
1808        let field_name = safe_java_field_name(&field.name);
1809
1810        // Skip unnamed tuple fields (name is "_0", "_1", "0", "1", etc.) — Java requires named fields
1811        if field.name.starts_with('_') && field.name[1..].chars().all(|c| c.is_ascii_digit())
1812            || field.name.chars().next().is_none_or(|c| c.is_ascii_digit())
1813        {
1814            continue;
1815        }
1816
1817        // Duration maps to primitive `long` in the public record, but in builder
1818        // classes we use boxed `Long` so that `null` can represent "not set".
1819        let field_type = if field.optional {
1820            format!("Optional<{}>", java_boxed_type(&field.ty))
1821        } else if matches!(field.ty, TypeRef::Duration) {
1822            java_boxed_type(&field.ty).to_string()
1823        } else {
1824            java_type(&field.ty).to_string()
1825        };
1826
1827        let default_value = if field.optional {
1828            // For Optional fields, always use Optional.empty() or Optional.of(value)
1829            if let Some(default) = &field.default {
1830                // If there's an explicit default, wrap it in Optional.of()
1831                format_optional_value(&field.ty, default)
1832            } else {
1833                // If no default, use Optional.empty()
1834                "Optional.empty()".to_string()
1835            }
1836        } else {
1837            // For non-Optional fields, use regular defaults
1838            if let Some(default) = &field.default {
1839                default.clone()
1840            } else {
1841                match &field.ty {
1842                    TypeRef::String | TypeRef::Char | TypeRef::Path | TypeRef::Json => "\"\"".to_string(),
1843                    TypeRef::Bytes => "new byte[0]".to_string(),
1844                    TypeRef::Primitive(p) => match p {
1845                        PrimitiveType::Bool => "false".to_string(),
1846                        PrimitiveType::F32 | PrimitiveType::F64 => "0.0".to_string(),
1847                        _ => "0".to_string(),
1848                    },
1849                    TypeRef::Vec(_) => "List.of()".to_string(),
1850                    TypeRef::Map(_, _) => "Map.of()".to_string(),
1851                    TypeRef::Optional(_) => "Optional.empty()".to_string(),
1852                    TypeRef::Duration => "null".to_string(),
1853                    _ => "null".to_string(),
1854                }
1855            }
1856        };
1857
1858        writeln!(body, "    private {} {} = {};", field_type, field_name, default_value).ok();
1859    }
1860
1861    writeln!(body).ok();
1862
1863    // Generate withXxx() methods
1864    for field in &typ.fields {
1865        // Skip unnamed tuple fields (name is "_0", "_1", "0", "1", etc.) — Java requires named fields
1866        if field.name.starts_with('_') && field.name[1..].chars().all(|c| c.is_ascii_digit())
1867            || field.name.chars().next().is_none_or(|c| c.is_ascii_digit())
1868        {
1869            continue;
1870        }
1871
1872        let field_name = safe_java_field_name(&field.name);
1873        let field_name_pascal = to_class_name(&field.name);
1874        let field_type = if field.optional {
1875            format!("Optional<{}>", java_boxed_type(&field.ty))
1876        } else if matches!(field.ty, TypeRef::Duration) {
1877            java_boxed_type(&field.ty).to_string()
1878        } else {
1879            java_type(&field.ty).to_string()
1880        };
1881
1882        writeln!(
1883            body,
1884            "    public {}Builder with{}({} value) {{",
1885            typ.name, field_name_pascal, field_type
1886        )
1887        .ok();
1888        writeln!(body, "        this.{} = value;", field_name).ok();
1889        writeln!(body, "        return this;").ok();
1890        writeln!(body, "    }}").ok();
1891        writeln!(body).ok();
1892    }
1893
1894    // Generate build() method
1895    writeln!(body, "    public {} build() {{", typ.name).ok();
1896    writeln!(body, "        return new {}(", typ.name).ok();
1897    let non_tuple_fields: Vec<_> = typ
1898        .fields
1899        .iter()
1900        .filter(|f| {
1901            // Include named fields (skip unnamed tuple fields)
1902            !(f.name.starts_with('_') && f.name[1..].chars().all(|c| c.is_ascii_digit())
1903                || f.name.chars().next().is_none_or(|c| c.is_ascii_digit()))
1904        })
1905        .collect();
1906    for (i, field) in non_tuple_fields.iter().enumerate() {
1907        let field_name = safe_java_field_name(&field.name);
1908        let comma = if i < non_tuple_fields.len() - 1 { "," } else { "" };
1909        writeln!(body, "            {}{}", field_name, comma).ok();
1910    }
1911    writeln!(body, "        );").ok();
1912    writeln!(body, "    }}").ok();
1913
1914    writeln!(body, "}}").ok();
1915
1916    // Now assemble with conditional imports based on what's actually used in the body
1917    let mut out = String::with_capacity(body.len() + 512);
1918
1919    writeln!(out, "// DO NOT EDIT - auto-generated by alef").ok();
1920    writeln!(out, "package {};", package).ok();
1921    writeln!(out).ok();
1922
1923    if body.contains("List<") {
1924        writeln!(out, "import java.util.List;").ok();
1925    }
1926    if body.contains("Map<") {
1927        writeln!(out, "import java.util.Map;").ok();
1928    }
1929    if body.contains("Optional<") {
1930        writeln!(out, "import java.util.Optional;").ok();
1931    }
1932
1933    writeln!(out).ok();
1934    out.push_str(&body);
1935
1936    out
1937}