Skip to main content

alef_backend_java/gen_bindings/
mod.rs

1use ahash::AHashSet;
2use alef_codegen::naming::to_class_name;
3use alef_core::backend::{Backend, BuildConfig, BuildDependency, Capabilities, GeneratedFile};
4use alef_core::config::{BridgeBinding, Language, ResolvedCrateConfig};
5use alef_core::ir::ApiSurface;
6use std::collections::HashSet;
7use std::path::PathBuf;
8
9mod facade;
10mod ffi_class;
11mod helpers;
12mod marshal;
13mod native_lib;
14mod trait_bridge;
15mod types;
16
17use facade::gen_facade_class;
18use ffi_class::gen_main_class;
19use helpers::{gen_exception_class, gen_infrastructure_exception_class};
20use native_lib::gen_native_lib;
21use types::{gen_builder_class, gen_enum_class, gen_opaque_handle_class, gen_record_type};
22
23pub struct JavaBackend;
24
25impl JavaBackend {
26    /// Convert crate name to main class name (PascalCase + "Rs" suffix).
27    ///
28    /// The "Rs" suffix ensures the raw FFI wrapper class has a distinct name from
29    /// the public facade class (which strips the "Rs" suffix). Without this, the
30    /// facade would delegate to itself, causing infinite recursion.
31    fn resolve_main_class(api: &ApiSurface) -> String {
32        let base = to_class_name(&api.crate_name.replace('-', "_"));
33        if base.ends_with("Rs") {
34            base
35        } else {
36            format!("{}Rs", base)
37        }
38    }
39}
40
41impl Backend for JavaBackend {
42    fn name(&self) -> &str {
43        "java"
44    }
45
46    fn language(&self) -> Language {
47        Language::Java
48    }
49
50    fn capabilities(&self) -> Capabilities {
51        Capabilities {
52            supports_async: true,
53            supports_classes: true,
54            supports_enums: true,
55            supports_option: true,
56            supports_result: true,
57            ..Capabilities::default()
58        }
59    }
60
61    fn generate_bindings(&self, api: &ApiSurface, config: &ResolvedCrateConfig) -> anyhow::Result<Vec<GeneratedFile>> {
62        let package = config.java_package();
63        let prefix = config.ffi_prefix();
64        let main_class = Self::resolve_main_class(api);
65        let package_path = package.replace('.', "/");
66
67        let output_dir = config
68            .output_for("java")
69            .map(|p| p.to_string_lossy().into_owned())
70            .unwrap_or_else(|| "packages/java/src/main/java/".to_string());
71
72        // If output_dir already ends with the package path (user configured the full path),
73        // use it as-is. Otherwise, append the package path.
74        let base_path = if output_dir.ends_with(&package_path) || output_dir.ends_with(&format!("{}/", package_path)) {
75            PathBuf::from(&output_dir)
76        } else {
77            PathBuf::from(&output_dir).join(&package_path)
78        };
79
80        // Collect bridge param names and type aliases so we can strip them from generated
81        // function signatures and emit convertWithVisitor instead.
82        let bridge_param_names: HashSet<String> = config
83            .trait_bridges
84            .iter()
85            .filter_map(|b| b.param_name.clone())
86            .collect();
87        let bridge_type_aliases: HashSet<String> = config
88            .trait_bridges
89            .iter()
90            .filter_map(|b| b.type_alias.clone())
91            .collect();
92        // Generate visitor support when visitor_callbacks is enabled in FFI config (canonical check),
93        // OR when any trait bridge is bound via options_field (Java-specific activation path).
94        let has_visitor_pattern = config.ffi.as_ref().map(|f| f.visitor_callbacks).unwrap_or(false)
95            || config
96                .trait_bridges
97                .iter()
98                .any(|b| b.bind_via == BridgeBinding::OptionsField);
99
100        let mut files = Vec::new();
101
102        // 0. package-info.java - required by Checkstyle
103        let description = config
104            .scaffold
105            .as_ref()
106            .and_then(|s| s.description.as_deref())
107            .unwrap_or("High-performance HTML to Markdown converter.");
108        files.push(GeneratedFile {
109            path: base_path.join("package-info.java"),
110            content: format!(
111                "/**\n * {description}\n */\npackage {package};\n",
112                description = description,
113                package = package,
114            ),
115            generated_header: true,
116        });
117
118        // 1. NativeLib.java - FFI method handles
119        files.push(GeneratedFile {
120            path: base_path.join("NativeLib.java"),
121            content: gen_native_lib(api, config, &package, &prefix, has_visitor_pattern),
122            generated_header: true,
123        });
124
125        // 2. Main wrapper class
126        files.push(GeneratedFile {
127            path: base_path.join(format!("{}.java", main_class)),
128            content: gen_main_class(
129                api,
130                config,
131                &package,
132                &main_class,
133                &prefix,
134                &bridge_param_names,
135                &bridge_type_aliases,
136                has_visitor_pattern,
137            ),
138            generated_header: true,
139        });
140
141        // 3. Exception class
142        files.push(GeneratedFile {
143            path: base_path.join(format!("{}Exception.java", main_class)),
144            content: gen_exception_class(&package, &main_class),
145            generated_header: true,
146        });
147
148        // 3b. Infrastructure exception classes for FFI error codes 1 and 2.
149        // These are always emitted because checkLastError() hardcodes:
150        //   case 1 -> throw new InvalidInputException(msg);
151        //   case 2 -> throw new ConversionErrorException(msg);
152        // Code 1 = null pointer / invalid UTF-8 in an input arg (invalid input).
153        // Code 2 = JSON serialisation/deserialisation failure (type conversion).
154        for (class_name, code, doc) in [
155            (
156                "InvalidInputException",
157                1i32,
158                "Exception thrown when input validation fails.",
159            ),
160            (
161                "ConversionErrorException",
162                2i32,
163                "Exception thrown when type conversion fails.",
164            ),
165        ] {
166            files.push(GeneratedFile {
167                path: base_path.join(format!("{}.java", class_name)),
168                content: gen_infrastructure_exception_class(&package, &main_class, class_name, code, doc),
169                generated_header: true,
170            });
171        }
172
173        // Collect complex enums (enums with data variants and no serde tag) — use Object for these fields.
174        // Tagged unions (serde_tag is set) are now generated as proper sealed interfaces
175        // and can be deserialized as their concrete types, so they are NOT complex_enums.
176        let complex_enums: AHashSet<String> = api
177            .enums
178            .iter()
179            .filter(|e| e.serde_tag.is_none() && e.variants.iter().any(|v| !v.fields.is_empty()))
180            .map(|e| e.name.clone())
181            .collect();
182
183        // Resolve language-level serde rename strategy (always wins over IR type-level).
184        let lang_rename_all = config.serde_rename_all_for_language(Language::Java);
185
186        // 4. Record types
187        // Include non-opaque types that either have fields OR are serializable unit structs
188        // (has_serde + has_default, empty fields). Unit structs like `ExcelMetadata` need a
189        // concrete Java class so they can be referenced as record components in tagged-union
190        // variant records (e.g. FormatMetadata.Excel(@JsonUnwrapped ExcelMetadata value)).
191        for typ in api.types.iter().filter(|typ| !typ.is_trait) {
192            let is_unit_serde = !typ.is_opaque && typ.fields.is_empty() && typ.has_serde;
193            if !typ.is_opaque && (!typ.fields.is_empty() || is_unit_serde) {
194                // Skip types that gen_visitor handles with richer visitor-specific versions
195                if has_visitor_pattern && (typ.name == "NodeContext" || typ.name == "VisitResult") {
196                    continue;
197                }
198                files.push(GeneratedFile {
199                    path: base_path.join(format!("{}.java", typ.name)),
200                    content: gen_record_type(&package, typ, &complex_enums, &lang_rename_all, has_visitor_pattern),
201                    generated_header: true,
202                });
203                // Generate builder class for types with defaults
204                if typ.has_default {
205                    files.push(GeneratedFile {
206                        path: base_path.join(format!("{}Builder.java", typ.name)),
207                        content: gen_builder_class(&package, typ, has_visitor_pattern),
208                        generated_header: true,
209                    });
210                }
211            }
212        }
213
214        // Collect builder class names generated from record types with defaults,
215        // so we can skip opaque types that would collide with them.
216        let builder_class_names: AHashSet<String> = api
217            .types
218            .iter()
219            .filter(|t| !t.is_opaque && (!t.fields.is_empty() || (t.has_serde && t.fields.is_empty())) && t.has_default)
220            .map(|t| format!("{}Builder", t.name))
221            .collect();
222
223        // 4b. Opaque handle types (skip if a pure-Java builder already covers this name)
224        for typ in api.types.iter().filter(|typ| !typ.is_trait) {
225            if typ.is_opaque && !builder_class_names.contains(&typ.name) {
226                files.push(GeneratedFile {
227                    path: base_path.join(format!("{}.java", typ.name)),
228                    content: gen_opaque_handle_class(&package, typ, &prefix),
229                    generated_header: true,
230                });
231            }
232        }
233
234        // 5. Enums
235        for enum_def in &api.enums {
236            // Skip enums that gen_visitor handles with richer visitor-specific versions
237            if has_visitor_pattern && enum_def.name == "VisitResult" {
238                continue;
239            }
240            files.push(GeneratedFile {
241                path: base_path.join(format!("{}.java", enum_def.name)),
242                content: gen_enum_class(&package, enum_def),
243                generated_header: true,
244            });
245        }
246
247        // 6. Error exception classes
248        for error in &api.errors {
249            for (class_name, content) in alef_codegen::error_gen::gen_java_error_types(error, &package) {
250                files.push(GeneratedFile {
251                    path: base_path.join(format!("{}.java", class_name)),
252                    content,
253                    generated_header: true,
254                });
255            }
256        }
257
258        // 7. Visitor support files (only when ConversionOptions/ConversionResult types exist)
259        if has_visitor_pattern {
260            for (filename, content) in crate::gen_visitor::gen_visitor_files(&package, &main_class) {
261                files.push(GeneratedFile {
262                    path: base_path.join(filename),
263                    content,
264                    generated_header: false, // already has header comment
265                });
266            }
267        }
268
269        // 8. Trait bridge plugin registration files
270        // Emits two files per trait: I{Trait}.java (managed interface) and
271        // {Trait}Bridge.java (Panama upcall stubs + register/unregister helpers).
272        for bridge_cfg in &config.trait_bridges {
273            if bridge_cfg.exclude_languages.contains(&Language::Java.to_string()) {
274                continue;
275            }
276
277            // When visitor_callbacks is active, visitor traits bound via options_field are
278            // surfaced through Visitor.java + VisitorBridge.java (generated by gen_visitor_files).
279            // The raw trait bridge I{Trait}.java emitted here would be an unreferenced orphan
280            // with snake_case method names. Suppress it for options_field-bound visitor traits.
281            if has_visitor_pattern && bridge_cfg.bind_via == BridgeBinding::OptionsField {
282                continue;
283            }
284
285            if let Some(trait_def) = api.types.iter().find(|t| t.name == bridge_cfg.trait_name && t.is_trait) {
286                let has_super_trait = bridge_cfg.super_trait.is_some();
287                let trait_bridge::BridgeFiles {
288                    interface_content,
289                    bridge_content,
290                } = trait_bridge::gen_trait_bridge_files(trait_def, &prefix, &package, has_super_trait);
291
292                files.push(GeneratedFile {
293                    path: base_path.join(format!("I{}.java", trait_def.name)),
294                    content: interface_content,
295                    generated_header: true,
296                });
297                files.push(GeneratedFile {
298                    path: base_path.join(format!("{}Bridge.java", trait_def.name)),
299                    content: bridge_content,
300                    generated_header: true,
301                });
302            }
303        }
304
305        Ok(files)
306    }
307
308    fn generate_public_api(
309        &self,
310        api: &ApiSurface,
311        config: &ResolvedCrateConfig,
312    ) -> anyhow::Result<Vec<GeneratedFile>> {
313        let package = config.java_package();
314        let prefix = config.ffi_prefix();
315        let main_class = Self::resolve_main_class(api);
316        let package_path = package.replace('.', "/");
317
318        let output_dir = config
319            .output_for("java")
320            .map(|p| p.to_string_lossy().into_owned())
321            .unwrap_or_else(|| "packages/java/src/main/java/".to_string());
322
323        // If output_dir already ends with the package path (user configured the full path),
324        // use it as-is. Otherwise, append the package path.
325        let base_path = if output_dir.ends_with(&package_path) || output_dir.ends_with(&format!("{}/", package_path)) {
326            PathBuf::from(&output_dir)
327        } else {
328            PathBuf::from(&output_dir).join(&package_path)
329        };
330
331        // Collect bridge param names/aliases to strip from the public facade.
332        let bridge_param_names: HashSet<String> = config
333            .trait_bridges
334            .iter()
335            .filter_map(|b| b.param_name.clone())
336            .collect();
337        let bridge_type_aliases: HashSet<String> = config
338            .trait_bridges
339            .iter()
340            .filter_map(|b| b.type_alias.clone())
341            .collect();
342        let has_visitor_pattern = config.ffi.as_ref().map(|f| f.visitor_callbacks).unwrap_or(false)
343            || config
344                .trait_bridges
345                .iter()
346                .any(|b| b.bind_via == BridgeBinding::OptionsField);
347
348        // Generate a high-level public API class that wraps the raw FFI class.
349        // Class name = main_class without "Rs" suffix (e.g., HtmlToMarkdownRs -> HtmlToMarkdown)
350        let public_class = main_class.trim_end_matches("Rs").to_string();
351        let facade_content = gen_facade_class(
352            api,
353            &package,
354            &public_class,
355            &main_class,
356            &prefix,
357            &bridge_param_names,
358            &bridge_type_aliases,
359            has_visitor_pattern,
360        );
361
362        Ok(vec![GeneratedFile {
363            path: base_path.join(format!("{}.java", public_class)),
364            content: facade_content,
365            generated_header: true,
366        }])
367    }
368
369    fn build_config(&self) -> Option<BuildConfig> {
370        Some(BuildConfig {
371            tool: "mvn",
372            crate_suffix: "",
373            build_dep: BuildDependency::Ffi,
374            post_build: vec![],
375        })
376    }
377}