Debian Codegraph @

third_party/rust/uniffi_bindgen/src/library_mode.rs

raw
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 /// Alternative implementation for the `generate` command, that we plan to eventually replace the current default with.
6 ///
7 /// Traditionally, users would invoke `uniffi-bindgen generate` to generate bindings for a single crate, passing it the UDL file, config file, etc.
8 ///
9 /// library_mode is a new way to generate bindings for multiple crates at once.
10 /// Users pass the path to the build cdylib file and UniFFI figures everything out, leveraging `cargo_metadata`, the metadata UniFFI stores inside exported symbols in the dylib, etc.
11 ///
12 /// This brings several advantages.:
13 /// - No more need to specify the dylib in the `uniffi.toml` file(s)
14 /// - UniFFI can figure out the dependencies based on the dylib exports and generate the sources for
15 /// all of them at once.
16 /// - UniFFI can figure out the package/module names for each crate, eliminating the external
17 /// package maps.
18 use crate::{
19 macro_metadata, overridden_config_value, BindgenCrateConfigSupplier, BindingGenerator,
20 Component, ComponentInterface, GenerationSettings, Result,
21 };
22 use anyhow::{bail, Context};
23 use camino::Utf8Path;
24 use std::{collections::BTreeMap, fs};
25 use toml::value::Table as TomlTable;
26 use uniffi_meta::{
27 create_metadata_groups, group_metadata, Metadata, MetadataGroup, NamespaceMetadata,
28 };
29
30 /// Generate foreign bindings
31 ///
32 /// This replicates the current process used for generating the builtin bindings.
33 /// External bindings authors should consider using [find_components], which provides a simpler
34 /// interface and allows for more flexibility in how the external bindings are generated.
35 ///
36 /// Returns the list of sources used to generate the bindings, in no particular order.
37 pub fn generate_bindings<T: BindingGenerator>(
38 library_path: &Utf8Path,
39 crate_name: Option<String>,
40 binding_generator: &T,
41 config_supplier: &dyn BindgenCrateConfigSupplier,
42 config_file_override: Option<&Utf8Path>,
43 out_dir: &Utf8Path,
44 try_format_code: bool,
45 ) -> Result<Vec<Component<T::Config>>> {
46 let mut components = find_components(library_path, config_supplier)
47 .with_context(|| format!("finding components in '{library_path}'"))?
48 .into_iter()
49 .map(|Component { ci, config }| {
50 let toml_value = overridden_config_value(config, config_file_override)?;
51 let config = binding_generator
52 .new_config(&toml_value)
53 .context("loading toml")?;
54 Ok(Component { ci, config })
55 })
56 .collect::<Result<Vec<_>>>()?;
57
58 let settings = GenerationSettings {
59 out_dir: out_dir.to_owned(),
60 try_format_code,
61 cdylib: calc_cdylib_name(library_path).map(ToOwned::to_owned),
62 };
63 binding_generator.update_component_configs(&settings, &mut components)?;
64
65 fs::create_dir_all(out_dir)?;
66 if let Some(crate_name) = &crate_name {
67 let old_elements = components.drain(..);
68 let mut matches: Vec<_> = old_elements
69 .filter(|s| s.ci.crate_name() == crate_name)
70 .collect();
71 match matches.len() {
72 0 => bail!("Crate {crate_name} not found in {library_path}"),
73 1 => components.push(matches.pop().unwrap()),
74 n => bail!("{n} crates named {crate_name} found in {library_path}"),
75 }
76 }
77
78 binding_generator.write_bindings(&settings, &components)?;
79
80 Ok(components)
81 }
82
83 // If `library_path` is a C dynamic library, return its name
84 pub fn calc_cdylib_name(library_path: &Utf8Path) -> Option<&str> {
85 let cdylib_extensions = [".so", ".dll", ".dylib"];
86 let filename = library_path.file_name()?;
87 let filename = filename.strip_prefix("lib").unwrap_or(filename);
88 for ext in cdylib_extensions {
89 if let Some(f) = filename.strip_suffix(ext) {
90 return Some(f);
91 }
92 }
93 None
94 }
95
96 /// Find UniFFI components from a shared library file
97 ///
98 /// This method inspects the library file and creates [ComponentInterface] instances for each
99 /// component used to build it. It parses the UDL files from `uniffi::include_scaffolding!` macro
100 /// calls.
101 ///
102 /// `config_supplier` is used to find UDL files on disk and load config data.
103 pub fn find_components(
104 library_path: &Utf8Path,
105 config_supplier: &dyn BindgenCrateConfigSupplier,
106 ) -> Result<Vec<Component<TomlTable>>> {
107 let items = macro_metadata::extract_from_library(library_path)?;
108 let mut metadata_groups = create_metadata_groups(&items);
109 group_metadata(&mut metadata_groups, items)?;
110
111 for group in metadata_groups.values_mut() {
112 let crate_name = group.namespace.crate_name.clone();
113 if let Some(udl_group) = load_udl_metadata(group, &crate_name, config_supplier)? {
114 let mut udl_items = udl_group
115 .items
116 .into_iter()
117 // some items are both in UDL and library metadata. For many that's fine but
118 // uniffi-traits aren't trivial to compare meaning we end up with dupes.
119 // We filter out such problematic items here.
120 .filter(|item| !matches!(item, Metadata::UniffiTrait { .. }))
121 .collect();
122 group.items.append(&mut udl_items);
123 if group.namespace_docstring.is_none() {
124 group.namespace_docstring = udl_group.namespace_docstring;
125 }
126 };
127 }
128
129 let crate_to_namespace_map: BTreeMap<String, NamespaceMetadata> = metadata_groups
130 .iter()
131 .map(|(k, v)| (k.clone(), v.namespace.clone()))
132 .collect();
133
134 metadata_groups
135 .into_values()
136 .map(|group| {
137 let crate_name = &group.namespace.crate_name;
138 let mut ci = ComponentInterface::new(crate_name);
139 ci.add_metadata(group)?;
140 let config = config_supplier
141 .get_toml(ci.crate_name())?
142 .unwrap_or_default();
143 ci.set_crate_to_namespace_map(crate_to_namespace_map.clone());
144 Ok(Component { ci, config })
145 })
146 .collect()
147 }
148
149 fn load_udl_metadata(
150 group: &MetadataGroup,
151 crate_name: &str,
152 config_supplier: &dyn BindgenCrateConfigSupplier,
153 ) -> Result<Option<MetadataGroup>> {
154 let udl_items = group
155 .items
156 .iter()
157 .filter_map(|i| match i {
158 Metadata::UdlFile(meta) => Some(meta),
159 _ => None,
160 })
161 .collect::<Vec<_>>();
162 // We only support 1 UDL file per crate, for no good reason!
163 match udl_items.len() {
164 0 => Ok(None),
165 1 => {
166 if udl_items[0].module_path != crate_name {
167 bail!(
168 "UDL is for crate '{}' but this crate name is '{}'",
169 udl_items[0].module_path,
170 crate_name
171 );
172 }
173 let udl = config_supplier.get_udl(crate_name, &udl_items[0].file_stub)?;
174 let udl_group = uniffi_udl::parse_udl(&udl, crate_name)?;
175 Ok(Some(udl_group))
176 }
177 n => bail!("{n} UDL files found for {crate_name}"),
178 }
179 }
180
181 #[cfg(test)]
182 mod test {
183 use super::*;
184
185 #[test]
186 fn calc_cdylib_name_is_correct() {
187 assert_eq!(
188 "uniffi",
189 calc_cdylib_name("/path/to/libuniffi.so".into()).unwrap()
190 );
191 assert_eq!(
192 "uniffi",
193 calc_cdylib_name("/path/to/libuniffi.dylib".into()).unwrap()
194 );
195 assert_eq!(
196 "uniffi",
197 calc_cdylib_name("/path/to/uniffi.dll".into()).unwrap()
198 );
199 }
200
201 /// Right now we unconditionally strip the `lib` prefix.
202 ///
203 /// Technically Windows DLLs do not start with a `lib` prefix,
204 /// but a library name could start with a `lib` prefix.
205 /// On Linux/macOS this would result in a `liblibuniffi.{so,dylib}` file.
206 #[test]
207 #[ignore] // Currently fails.
208 fn calc_cdylib_name_is_correct_on_windows() {
209 assert_eq!(
210 "libuniffi",
211 calc_cdylib_name("/path/to/libuniffi.dll".into()).unwrap()
212 );
213 }
214 }