Skip to main content

uniffi_bindgen_java/
lib.rs

1use anyhow::{Context, Result};
2use camino::{Utf8Path, Utf8PathBuf};
3use clap::{Parser, Subcommand};
4use std::collections::HashMap;
5use std::fs;
6use uniffi_bindgen::{
7    BindgenLoader, BindgenPaths, Component, ComponentInterface, GlobalConfig, interface::rename,
8};
9
10mod gen_java;
11use gen_java::Config;
12
13/// Options for generating Java bindings
14pub struct GenerateOptions {
15    /// Path to the source file (UDL or library)
16    pub source: Utf8PathBuf,
17    /// Directory to write generated files
18    pub out_dir: Utf8PathBuf,
19    /// Whether to format generated code (currently not implemented)
20    pub format: bool,
21    /// Optional crate filter - only generate bindings for this crate
22    pub crate_filter: Option<String>,
23}
24
25pub fn generate(loader: &BindgenLoader, options: &GenerateOptions) -> Result<()> {
26    let metadata = loader.load_metadata(&options.source)?;
27    let cis = loader.load_cis(metadata)?;
28    let cdylib = loader.library_name(&options.source).map(|l| l.to_string());
29    let mut components =
30        loader.load_components(cis, |ci, toml| parse_config(ci, toml, cdylib.clone()))?;
31
32    // Apply renames and update external package mappings (must happen before derive_ffi_funcs)
33    apply_renames_and_external_packages(&mut components);
34
35    // Derive FFI functions for each component (after renames)
36    for c in components.iter_mut() {
37        c.ci.derive_ffi_funcs()?;
38    }
39
40    // Generate and write bindings for each component
41    let filename_capture = regex::Regex::new(
42        r"(?m)^(?:public\s)?(?:final\s)?(?:sealed\s)?(?:abstract\s)?(?:static\s)?(?:class|interface|enum|record)\s(\w+)",
43    )
44    .unwrap();
45
46    for Component { ci, config, .. } in components {
47        if let Some(crate_filter) = &options.crate_filter
48            && ci.crate_name() != crate_filter
49        {
50            continue;
51        }
52
53        let bindings_str = gen_java::generate_bindings(&config, &ci)?;
54        let java_package_out_dir = options.out_dir.join(
55            config
56                .package_name()
57                .split('.')
58                .collect::<Vec<_>>()
59                .join("/"),
60        );
61        fs::create_dir_all(&java_package_out_dir)?;
62
63        let package_line = format!("package {};", config.package_name());
64        let split_classes = bindings_str.split(&package_line);
65        let writable = split_classes
66            .map(|file| (filename_capture.captures(file), file))
67            .filter(|(x, _)| x.is_some())
68            .map(|(captures, file)| (captures.unwrap().get(1).unwrap().as_str(), file))
69            .collect::<Vec<_>>();
70
71        for (filename, file) in writable {
72            let java_file_location = java_package_out_dir.join(format!("{}.java", filename));
73            fs::write(&java_file_location, format!("{}\n{}", package_line, file))?;
74        }
75
76        if config.nullness_annotations() {
77            let package_info = format!("@org.jspecify.annotations.NullMarked\n{}", package_line);
78            fs::write(java_package_out_dir.join("package-info.java"), package_info)?;
79        }
80
81        if options.format {
82            // TODO: if there's a CLI formatter that makes sense to use here, use it, PRs welcome
83            // seems like palantir-java-format is popular, but it's only exposed through plugins
84            // google-java-format is legacy popular and does have an executable all-deps JAR, but
85            // must be called with the full jar path including version numbers
86            // prettier sorta works but requires npm and packages be around for a java generator
87        }
88    }
89    Ok(())
90}
91
92/// Parse Java configuration from TOML
93fn parse_config(
94    ci: &ComponentInterface,
95    root_toml: toml::Value,
96    cdylib: Option<String>,
97) -> Result<Config> {
98    let mut config: Config = match root_toml.get("bindings").and_then(|b| b.get("java")) {
99        Some(v) => v.clone().try_into()?,
100        None => Default::default(),
101    };
102    config
103        .package_name
104        .get_or_insert_with(|| format!("uniffi.{}", ci.namespace()));
105    config.cdylib_name.get_or_insert_with(|| {
106        cdylib
107            .clone()
108            .unwrap_or_else(|| format!("uniffi_{}", ci.namespace()))
109    });
110    Ok(config)
111}
112
113/// Apply rename configurations and update external package mappings across all components.
114/// This must be called before derive_ffi_funcs() since renames affect FFI function names.
115fn apply_renames_and_external_packages(components: &mut Vec<Component<Config>>) {
116    // Collect all rename configurations from all components, keyed by module_path (crate name)
117    let mut module_renames = HashMap::new();
118    for c in components.iter() {
119        if !c.config.rename.is_empty() {
120            let module_path = c.ci.crate_name().to_string();
121            module_renames.insert(module_path, c.config.rename.clone());
122        }
123    }
124
125    // Apply rename configurations to all components
126    if !module_renames.is_empty() {
127        for c in &mut *components {
128            rename(&mut c.ci, &module_renames);
129        }
130    }
131
132    // Update external package mappings
133    let packages = HashMap::<String, String>::from_iter(
134        components
135            .iter()
136            .map(|c| (c.ci.crate_name().to_string(), c.config.package_name())),
137    );
138    for c in components {
139        for (ext_crate, ext_package) in &packages {
140            if ext_crate != c.ci.crate_name() && !c.config.external_packages.contains_key(ext_crate)
141            {
142                c.config
143                    .external_packages
144                    .insert(ext_crate.to_string(), ext_package.clone());
145            }
146        }
147    }
148}
149
150fn create_bindgen_paths(
151    global_config_path: Option<&Utf8Path>,
152    metadata_no_deps: bool,
153) -> Result<(BindgenPaths, GlobalConfig)> {
154    let mut paths = BindgenPaths::default();
155
156    // `BindgenPaths` resolves through layers first-added-wins, so `[crate-roots]` has to land
157    // before cargo metadata to override it.
158    let global_config = match global_config_path {
159        Some(path) => {
160            let (config, crate_roots) = GlobalConfig::from_file(path)
161                .with_context(|| format!("Failed to load global config: {path}"))?;
162            if let Some(layer) = crate_roots {
163                paths.add_layer(layer);
164            }
165            config
166        }
167        None => GlobalConfig::default(),
168    };
169
170    paths
171        .add_cargo_metadata_layer(metadata_no_deps)
172        .context("Failed to load cargo metadata")?;
173
174    Ok((paths, global_config))
175}
176
177#[derive(Parser)]
178#[clap(name = "uniffi-bindgen-java")]
179#[clap(version = clap::crate_version!())]
180#[clap(propagate_version = true, disable_help_subcommand = true)]
181/// Java scaffolding and bindings generator for Rust
182struct Cli {
183    #[clap(subcommand)]
184    command: Commands,
185}
186
187#[derive(Subcommand)]
188enum Commands {
189    /// Generate Java bindings
190    Generate {
191        /// Directory in which to write generated files. Default is same folder as .udl file.
192        #[clap(long, short)]
193        out_dir: Option<Utf8PathBuf>,
194
195        /// Do not try to format the generated bindings.
196        #[clap(long, short)]
197        no_format: bool,
198
199        /// Path to an optional uniffi global config file, with `[defaults]`, `[crates.<name>]`
200        /// and/or `[crate-roots]` sections. Merged with each crate's `uniffi.toml`.
201        #[clap(long, short)]
202        config: Option<Utf8PathBuf>,
203
204        /// When a library is passed as SOURCE, only generate bindings for this crate.
205        /// When a UDL file is passed, use this as the crate name instead of attempting to
206        /// locate and parse Cargo.toml.
207        #[clap(long = "crate")]
208        crate_name: Option<String>,
209
210        /// Path to the UDL file or compiled library (.so, .dll, .dylib, or .a)
211        source: Utf8PathBuf,
212
213        /// Whether we should exclude dependencies when running "cargo metadata".
214        /// This will mean external types may not be resolved if they are implemented in crates
215        /// outside of this workspace.
216        /// This can be used in environments when all types are in the namespace and fetching
217        /// all sub-dependencies causes obscure platform specific problems.
218        #[clap(long)]
219        metadata_no_deps: bool,
220    },
221    /// Generate Rust scaffolding code
222    Scaffolding {
223        /// Directory in which to write generated files. Default is same folder as .udl file.
224        #[clap(long, short)]
225        out_dir: Option<Utf8PathBuf>,
226
227        /// Do not try to format the generated bindings.
228        #[clap(long, short)]
229        no_format: bool,
230
231        /// Path to the UDL file.
232        udl_file: Utf8PathBuf,
233    },
234    /// Print a debug representation of the interface from a dynamic library
235    PrintRepr {
236        /// Path to the library file (.so, .dll, .dylib, or .a)
237        path: Utf8PathBuf,
238    },
239}
240
241pub fn run_main() -> Result<()> {
242    let cli = Cli::parse();
243    match cli.command {
244        Commands::Generate {
245            out_dir,
246            no_format,
247            config,
248            crate_name,
249            source,
250            metadata_no_deps,
251        } => {
252            let out_dir = out_dir.unwrap_or_else(|| {
253                source
254                    .parent()
255                    .map(|p| p.to_path_buf())
256                    .unwrap_or_else(|| Utf8PathBuf::from("."))
257            });
258
259            let (paths, global_config) = create_bindgen_paths(config.as_deref(), metadata_no_deps)?;
260            let loader = BindgenLoader::new(paths, global_config);
261
262            fs::create_dir_all(&out_dir)?;
263
264            generate(
265                &loader,
266                &GenerateOptions {
267                    source,
268                    out_dir,
269                    format: !no_format,
270                    crate_filter: crate_name,
271                },
272            )?;
273        }
274        Commands::Scaffolding {
275            out_dir,
276            no_format,
277            udl_file,
278        } => {
279            uniffi_bindgen::generate_component_scaffolding(
280                &udl_file,
281                out_dir.as_deref(),
282                !no_format,
283            )?;
284        }
285        Commands::PrintRepr { path } => {
286            uniffi_bindgen::print_repr(&path)?;
287        }
288    };
289    Ok(())
290}