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::{AlefConfig, Language, resolve_output_dir};
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;
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: &AlefConfig) -> 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 = resolve_output_dir(
68            config.output.java.as_ref(),
69            &config.crate_config.name,
70            "packages/java/src/main/java/",
71        );
72
73        // If output_dir already ends with the package path (user configured the full path),
74        // use it as-is. Otherwise, append the package path.
75        let base_path = if output_dir.ends_with(&package_path) || output_dir.ends_with(&format!("{}/", package_path)) {
76            PathBuf::from(&output_dir)
77        } else {
78            PathBuf::from(&output_dir).join(&package_path)
79        };
80
81        // Collect bridge param names and type aliases so we can strip them from generated
82        // function signatures and emit convertWithVisitor instead.
83        let bridge_param_names: HashSet<String> = config
84            .trait_bridges
85            .iter()
86            .filter_map(|b| b.param_name.clone())
87            .collect();
88        let bridge_type_aliases: HashSet<String> = config
89            .trait_bridges
90            .iter()
91            .filter_map(|b| b.type_alias.clone())
92            .collect();
93        // Only generate visitor support if visitor_callbacks is explicitly enabled in FFI config
94        let has_visitor_pattern = config.ffi.as_ref().map(|f| f.visitor_callbacks).unwrap_or(false);
95
96        let mut files = Vec::new();
97
98        // 0. package-info.java - required by Checkstyle
99        let description = config
100            .scaffold
101            .as_ref()
102            .and_then(|s| s.description.as_deref())
103            .unwrap_or("High-performance HTML to Markdown converter.");
104        files.push(GeneratedFile {
105            path: base_path.join("package-info.java"),
106            content: format!(
107                "/**\n * {description}\n */\npackage {package};\n",
108                description = description,
109                package = package,
110            ),
111            generated_header: true,
112        });
113
114        // 1. NativeLib.java - FFI method handles
115        files.push(GeneratedFile {
116            path: base_path.join("NativeLib.java"),
117            content: gen_native_lib(api, config, &package, &prefix, has_visitor_pattern),
118            generated_header: true,
119        });
120
121        // 2. Main wrapper class
122        files.push(GeneratedFile {
123            path: base_path.join(format!("{}.java", main_class)),
124            content: gen_main_class(
125                api,
126                config,
127                &package,
128                &main_class,
129                &prefix,
130                &bridge_param_names,
131                &bridge_type_aliases,
132                has_visitor_pattern,
133            ),
134            generated_header: true,
135        });
136
137        // 3. Exception class
138        files.push(GeneratedFile {
139            path: base_path.join(format!("{}Exception.java", main_class)),
140            content: gen_exception_class(&package, &main_class),
141            generated_header: true,
142        });
143
144        // Collect complex enums (enums with data variants and no serde tag) — use Object for these fields.
145        // Tagged unions (serde_tag is set) are now generated as proper sealed interfaces
146        // and can be deserialized as their concrete types, so they are NOT complex_enums.
147        let complex_enums: AHashSet<String> = api
148            .enums
149            .iter()
150            .filter(|e| e.serde_tag.is_none() && e.variants.iter().any(|v| !v.fields.is_empty()))
151            .map(|e| e.name.clone())
152            .collect();
153
154        // Resolve language-level serde rename strategy (always wins over IR type-level).
155        let lang_rename_all = config.serde_rename_all_for_language(Language::Java);
156
157        // 4. Record types
158        for typ in api.types.iter().filter(|typ| !typ.is_trait) {
159            if !typ.is_opaque && !typ.fields.is_empty() {
160                // Skip types that gen_visitor handles with richer visitor-specific versions
161                if has_visitor_pattern && (typ.name == "NodeContext" || typ.name == "VisitResult") {
162                    continue;
163                }
164                files.push(GeneratedFile {
165                    path: base_path.join(format!("{}.java", typ.name)),
166                    content: gen_record_type(&package, typ, &complex_enums, &lang_rename_all),
167                    generated_header: true,
168                });
169                // Generate builder class for types with defaults
170                if typ.has_default {
171                    files.push(GeneratedFile {
172                        path: base_path.join(format!("{}Builder.java", typ.name)),
173                        content: gen_builder_class(&package, typ),
174                        generated_header: true,
175                    });
176                }
177            }
178        }
179
180        // Collect builder class names generated from record types with defaults,
181        // so we can skip opaque types that would collide with them.
182        let builder_class_names: AHashSet<String> = api
183            .types
184            .iter()
185            .filter(|t| !t.is_opaque && !t.fields.is_empty() && t.has_default)
186            .map(|t| format!("{}Builder", t.name))
187            .collect();
188
189        // 4b. Opaque handle types (skip if a pure-Java builder already covers this name)
190        for typ in api.types.iter().filter(|typ| !typ.is_trait) {
191            if typ.is_opaque && !builder_class_names.contains(&typ.name) {
192                files.push(GeneratedFile {
193                    path: base_path.join(format!("{}.java", typ.name)),
194                    content: gen_opaque_handle_class(&package, typ, &prefix),
195                    generated_header: true,
196                });
197            }
198        }
199
200        // 5. Enums
201        for enum_def in &api.enums {
202            // Skip enums that gen_visitor handles with richer visitor-specific versions
203            if has_visitor_pattern && enum_def.name == "VisitResult" {
204                continue;
205            }
206            files.push(GeneratedFile {
207                path: base_path.join(format!("{}.java", enum_def.name)),
208                content: gen_enum_class(&package, enum_def),
209                generated_header: true,
210            });
211        }
212
213        // 6. Error exception classes
214        for error in &api.errors {
215            for (class_name, content) in alef_codegen::error_gen::gen_java_error_types(error, &package) {
216                files.push(GeneratedFile {
217                    path: base_path.join(format!("{}.java", class_name)),
218                    content,
219                    generated_header: true,
220                });
221            }
222        }
223
224        // 7. Visitor support files (only when ConversionOptions/ConversionResult types exist)
225        if has_visitor_pattern {
226            for (filename, content) in crate::gen_visitor::gen_visitor_files(&package, &main_class) {
227                files.push(GeneratedFile {
228                    path: base_path.join(filename),
229                    content,
230                    generated_header: false, // already has header comment
231                });
232            }
233        }
234
235        // 8. Trait bridge plugin registration files
236        // Emits two files per trait: I{Trait}.java (managed interface) and
237        // {Trait}Bridge.java (Panama upcall stubs + register/unregister helpers).
238        for bridge_cfg in &config.trait_bridges {
239            if bridge_cfg.exclude_languages.contains(&Language::Java.to_string()) {
240                continue;
241            }
242
243            if let Some(trait_def) = api.types.iter().find(|t| t.name == bridge_cfg.trait_name && t.is_trait) {
244                let has_super_trait = bridge_cfg.super_trait.is_some();
245                let trait_bridge::BridgeFiles {
246                    interface_content,
247                    bridge_content,
248                } = trait_bridge::gen_trait_bridge_files(trait_def, &prefix, &package, has_super_trait);
249
250                files.push(GeneratedFile {
251                    path: base_path.join(format!("I{}.java", trait_def.name)),
252                    content: interface_content,
253                    generated_header: true,
254                });
255                files.push(GeneratedFile {
256                    path: base_path.join(format!("{}Bridge.java", trait_def.name)),
257                    content: bridge_content,
258                    generated_header: true,
259                });
260            }
261        }
262
263        // Build adapter body map (consumed by generators via body substitution)
264        let _adapter_bodies = alef_adapters::build_adapter_bodies(config, Language::Java)?;
265
266        Ok(files)
267    }
268
269    fn generate_public_api(&self, api: &ApiSurface, config: &AlefConfig) -> anyhow::Result<Vec<GeneratedFile>> {
270        let package = config.java_package();
271        let prefix = config.ffi_prefix();
272        let main_class = Self::resolve_main_class(api);
273        let package_path = package.replace('.', "/");
274
275        let output_dir = resolve_output_dir(
276            config.output.java.as_ref(),
277            &config.crate_config.name,
278            "packages/java/src/main/java/",
279        );
280
281        // If output_dir already ends with the package path (user configured the full path),
282        // use it as-is. Otherwise, append the package path.
283        let base_path = if output_dir.ends_with(&package_path) || output_dir.ends_with(&format!("{}/", package_path)) {
284            PathBuf::from(&output_dir)
285        } else {
286            PathBuf::from(&output_dir).join(&package_path)
287        };
288
289        // Collect bridge param names/aliases to strip from the public facade.
290        let bridge_param_names: HashSet<String> = config
291            .trait_bridges
292            .iter()
293            .filter_map(|b| b.param_name.clone())
294            .collect();
295        let bridge_type_aliases: HashSet<String> = config
296            .trait_bridges
297            .iter()
298            .filter_map(|b| b.type_alias.clone())
299            .collect();
300
301        // Generate a high-level public API class that wraps the raw FFI class.
302        // Class name = main_class without "Rs" suffix (e.g., HtmlToMarkdownRs -> HtmlToMarkdown)
303        let public_class = main_class.trim_end_matches("Rs").to_string();
304        let facade_content = gen_facade_class(
305            api,
306            &package,
307            &public_class,
308            &main_class,
309            &prefix,
310            &bridge_param_names,
311            &bridge_type_aliases,
312        );
313
314        Ok(vec![GeneratedFile {
315            path: base_path.join(format!("{}.java", public_class)),
316            content: facade_content,
317            generated_header: true,
318        }])
319    }
320
321    fn build_config(&self) -> Option<BuildConfig> {
322        Some(BuildConfig {
323            tool: "mvn",
324            crate_suffix: "",
325            build_dep: BuildDependency::Ffi,
326            post_build: vec![],
327        })
328    }
329}