Debian Codegraph @

third_party/rust/uniffi_bindgen/src/lib.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 //! # Uniffi: easily build cross-platform software components in Rust
6 //!
7 //! This is a highly-experimental crate for building cross-language software components
8 //! in Rust, based on things we've learned and patterns we've developed in the
9 //! [mozilla/application-services](https://github.com/mozilla/application-services) project.
10 //!
11 //! The idea is to let you write your code once, in Rust, and then re-use it from many
12 //! other programming languages via Rust's C-compatible FFI layer and some automagically
13 //! generated binding code. If you think of it as a kind of [wasm-bindgen](https://github.com/rustwasm/wasm-bindgen)
14 //! wannabe, with a clunkier developer experience but support for more target languages,
15 //! you'll be pretty close to the mark.
16 //!
17 //! Currently supported target languages include Kotlin, Swift and Python.
18 //!
19 //! ## Usage
20 //
21 //! To build a cross-language component using `uniffi`, follow these steps.
22 //!
23 //! ### 1) Specify your Component Interface
24 //!
25 //! Start by thinking about the interface you want to expose for use
26 //! from other languages. Use the Interface Definition Language to specify your interface
27 //! in a `.udl` file, where it can be processed by the tools from this crate.
28 //! For example you might define an interface like this:
29 //!
30 //! ```text
31 //! namespace example {
32 //! u32 foo(u32 bar);
33 //! }
34 //!
35 //! dictionary MyData {
36 //! u32 num_foos;
37 //! bool has_a_bar;
38 //! }
39 //! ```
40 //!
41 //! ### 2) Implement the Component Interface as a Rust crate
42 //!
43 //! With the interface, defined, provide a corresponding implementation of that interface
44 //! as a standard-looking Rust crate, using functions and structs and so-on. For example
45 //! an implementation of the above Component Interface might look like this:
46 //!
47 //! ```text
48 //! fn foo(bar: u32) -> u32 {
49 //! // TODO: a better example!
50 //! bar + 42
51 //! }
52 //!
53 //! struct MyData {
54 //! num_foos: u32,
55 //! has_a_bar: bool
56 //! }
57 //! ```
58 //!
59 //! ### 3) Generate and include component scaffolding from the UDL file
60 //!
61 //! Add to your crate `uniffi_build` under `[build-dependencies]`,
62 //! then add a `build.rs` script to your crate and have it call `uniffi_build::generate_scaffolding`
63 //! to process your `.udl` file. This will generate some Rust code to be included in the top-level source
64 //! code of your crate. If your UDL file is named `example.udl`, then your build script would call:
65 //!
66 //! ```text
67 //! uniffi_build::generate_scaffolding("src/example.udl")
68 //! ```
69 //!
70 //! This would output a rust file named `example.uniffi.rs`, ready to be
71 //! included into the code of your rust crate like this:
72 //!
73 //! ```text
74 //! include_scaffolding!("example");
75 //! ```
76 //!
77 //! ### 4) Generate foreign language bindings for the library
78 //!
79 //! You will need ensure a local `uniffi-bindgen` - see <https://mozilla.github.io/uniffi-rs/tutorial/foreign_language_bindings.html>
80 //! This utility provides a command-line tool that can produce code to
81 //! consume the Rust library in any of several supported languages.
82 //! It is done by calling (in kotlin for example):
83 //!
84 //! ```text
85 //! cargo run --bin -p uniffi-bindgen --language kotlin ./src/example.udl
86 //! ```
87 //!
88 //! This will produce a file `example.kt` in the same directory as the .udl file, containing kotlin bindings
89 //! to load and use the compiled rust code via its C-compatible FFI.
90 //!
91
92 #![warn(rust_2018_idioms, unused_qualifications)]
93 #![allow(unknown_lints)]
94
95 use anyhow::{anyhow, bail, Context, Result};
96 use camino::{Utf8Path, Utf8PathBuf};
97 use fs_err::{self as fs, File};
98 use serde::Deserialize;
99 use std::io::prelude::*;
100 use std::io::ErrorKind;
101 use std::process::Command;
102
103 pub mod backend;
104 pub mod bindings;
105 pub mod interface;
106 pub mod library_mode;
107 pub mod macro_metadata;
108 pub mod pipeline;
109 pub mod scaffolding;
110
111 #[cfg(feature = "cargo-metadata")]
112 pub mod cargo_metadata;
113
114 use crate::interface::{
115 Argument, Constructor, Enum, FfiArgument, FfiField, Field, Function, Method, Object, Record,
116 Variant,
117 };
118 pub use interface::ComponentInterface;
119 pub use library_mode::find_components;
120 use scaffolding::RustScaffolding;
121 use uniffi_meta::Type;
122
123 /// The options used when creating bindings. Named such
124 /// it doesn't cause confusion that it's settings specific to
125 /// the generator itself.
126 // TODO: We should try and move the public interface of the module to
127 // this struct. For now, only the BindingGenerator uses it.
128 #[derive(Debug, Default)]
129 pub struct GenerationSettings {
130 pub out_dir: Utf8PathBuf,
131 pub try_format_code: bool,
132 pub cdylib: Option<String>,
133 }
134
135 /// A trait representing a UniFFI Binding Generator
136 ///
137 /// External crates that implement binding generators, should implement this type
138 /// and call the [`generate_external_bindings`] using a type that implements this trait.
139 pub trait BindingGenerator: Sized {
140 /// Handles configuring the bindings
141 type Config;
142
143 /// Creates a new config.
144 fn new_config(&self, root_toml: &toml::Value) -> Result<Self::Config>;
145
146 /// Update the various config items in preparation to write one or more of them.
147 ///
148 /// # Arguments
149 /// - `cdylib`: The name of the cdylib file, if known.
150 /// - `library_path`: The name of library used to extract the symbols.
151 /// - `components`: A mutable array of [`Component`]s to be updated.
152 fn update_component_configs(
153 &self,
154 settings: &GenerationSettings,
155 components: &mut Vec<Component<Self::Config>>,
156 ) -> Result<()>;
157
158 /// Writes the bindings to the output directory
159 ///
160 /// # Arguments
161 /// - `components`: An array of [`Component`]s representing the items to be generated.
162 /// - `out_dir`: The path to where the binding generator should write the output bindings
163 fn write_bindings(
164 &self,
165 settings: &GenerationSettings,
166 components: &[Component<Self::Config>],
167 ) -> Result<()>;
168 }
169
170 /// A trait to alter language specific type representations.
171 ///
172 /// It is meant to be implemented by each language oracle. It takes a
173 /// ['ComponentInterface'] and uses its own specific language adjustment
174 /// functions to be able to generate language specific templates.
175 pub trait VisitMut {
176 /// Go through each `Record` of a [`ComponentInterface`] and
177 /// adjust it to language specific naming conventions.
178 fn visit_record(&self, record: &mut Record);
179
180 /// Change the name of an `Object` of a [`ComponentInterface`
181 /// to language specific naming conventions.
182 fn visit_object(&self, object: &mut Object);
183
184 /// Change the name of a `Field` of an `Enum` `Variant`
185 /// to language specific naming conventions.
186 fn visit_field(&self, field: &mut Field);
187
188 /// Change the name of a `FfiField` inside a `FfiStruct`
189 /// to language specific naming conventions.
190 fn visit_ffi_field(&self, ffi_field: &mut FfiField);
191
192 /// Change the `Arugment` of a `FfiFunction` in the [`ComponentInterface`]
193 /// to language specific naming conventions.
194 fn visit_ffi_argument(&self, ffi_argument: &mut FfiArgument);
195
196 /// Go through each `Enum` of a [`ComponentInterface`] and
197 /// adjust it to language specific naming conventions.
198 fn visit_enum(&self, is_error: bool, enum_: &mut Enum);
199
200 /// Change the naming of the key in the [`ComponentInterface`]
201 /// `BTreeMap` where all `Enum`s are stored to reflect the changed
202 /// name of an `Enum`.
203 fn visit_enum_key(&self, key: &mut String) -> String;
204
205 /// Go through each `Variant` of an `Enum` and
206 /// adjust it to language specific naming conventions.
207 fn visit_variant(&self, is_error: bool, variant: &mut Variant);
208
209 /// Go through each `Type` in the `TypeUniverse` of
210 /// a [`ComponentInterface`] and adjust it to language specific
211 /// naming conventions.
212 fn visit_type(&self, type_: &mut Type);
213
214 /// Go through each error name in the interface and adjust it to language specific naming
215 /// conventions. The new name must match the name of the Enum/Object definition after it's
216 /// visited.
217 fn visit_error_name(&self, name: &mut String);
218
219 /// Go through each `Method` of an `Object` and
220 /// adjust it to language specific naming conventions.
221 fn visit_method(&self, method: &mut Method);
222
223 /// Go through each `Argument` of a `Function` and
224 /// adjust it to language specific naming conventions.
225 fn visit_argument(&self, argument: &mut Argument);
226
227 /// Go through each `Constructor` of a [`ComponentInterface`] and
228 /// adjust it to language specific naming conventions.
229 fn visit_constructor(&self, constructor: &mut Constructor);
230
231 /// Go through each `Function` of a [`ComponentInterface`] and
232 /// adjust it to language specific naming conventions.
233 fn visit_function(&self, function: &mut Function);
234 }
235
236 /// Everything needed to generate a ComponentInterface.
237 #[derive(Debug)]
238 pub struct Component<Config> {
239 pub ci: ComponentInterface,
240 pub config: Config,
241 }
242
243 /// A trait used by the bindgen to obtain config information about a source crate
244 /// which was found in the metadata for the library.
245 ///
246 /// This is an abstraction around needing the source directory for a crate.
247 /// In most cases `cargo_metadata` can be used, but this should be able to work in
248 /// more environments.
249 pub trait BindgenCrateConfigSupplier {
250 /// Get a `toml::value::Table` instance for the crate.
251 fn get_toml(&self, _crate_name: &str) -> Result<Option<toml::value::Table>> {
252 Ok(None)
253 }
254
255 /// Get the path to the TOML file for a crate.
256 ///
257 /// This is usually the `uniffi.toml` path in the root of the crate source.
258 fn get_toml_path(&self, _crate_name: &str) -> Option<Utf8PathBuf> {
259 None
260 }
261
262 /// Obtains the contents of the named UDL file which was referenced by the type metadata.
263 fn get_udl(&self, crate_name: &str, udl_name: &str) -> Result<String> {
264 bail!("Crate {crate_name} has no UDL {udl_name}")
265 }
266 }
267
268 pub struct EmptyCrateConfigSupplier;
269 impl BindgenCrateConfigSupplier for EmptyCrateConfigSupplier {}
270
271 /// A convenience function for the CLI to help avoid using static libs
272 /// in places cdylibs are required.
273 pub fn is_cdylib(library_file: impl AsRef<Utf8Path>) -> bool {
274 library_mode::calc_cdylib_name(library_file.as_ref()).is_some()
275 }
276
277 /// Generate bindings for an external binding generator
278 /// Ideally, this should replace the [`generate_bindings`] function below
279 ///
280 /// Implements an entry point for external binding generators.
281 /// The function does the following:
282 /// - It parses the `udl` in a [`ComponentInterface`]
283 /// - Creates an instance of [`BindingGenerator`], based on type argument `B`, and run [`BindingGenerator::write_bindings`] on it
284 ///
285 /// # Arguments
286 /// - `binding_generator`: Type that implements BindingGenerator
287 /// - `udl_file`: The path to the UDL file
288 /// - `config_file_override`: The path to the configuration toml file, most likely called `uniffi.toml`. If [`None`], the function will try to guess based on the crate's root.
289 /// - `out_dir_override`: The path to write the bindings to. If [`None`], it will be the path to the parent directory of the `udl_file`
290 /// - `library_file`: The path to a dynamic library to attempt to extract the definitions from and extend the component interface with. No extensions to component interface occur if it's [`None`]
291 /// - `crate_name`: Override the default crate name that is guessed from UDL file path.
292 pub fn generate_external_bindings<T: BindingGenerator>(
293 binding_generator: &T,
294 udl_file: impl AsRef<Utf8Path>,
295 config_file_override: Option<impl AsRef<Utf8Path>>,
296 out_dir_override: Option<impl AsRef<Utf8Path>>,
297 library_file: Option<impl AsRef<Utf8Path>>,
298 crate_name: Option<&str>,
299 try_format_code: bool,
300 ) -> Result<()> {
301 let crate_name = crate_name
302 .map(|c| Ok(c.to_string()))
303 .unwrap_or_else(|| crate_name_from_cargo_toml(udl_file.as_ref()))?;
304 let mut ci = parse_udl(udl_file.as_ref(), &crate_name)?;
305 if let Some(ref library_file) = library_file {
306 macro_metadata::add_to_ci_from_library(&mut ci, library_file.as_ref())?;
307 }
308 let crate_root = &guess_crate_root(udl_file.as_ref()).context("Failed to guess crate root")?;
309
310 let config_file_override = config_file_override.as_ref().map(|p| p.as_ref());
311
312 let config = {
313 let crate_config = load_toml_file(Some(&crate_root.join("uniffi.toml")))
314 .context("failed to load {crate_root}/uniffi.toml")?;
315 let toml_value =
316 overridden_config_value(crate_config.unwrap_or_default(), config_file_override)?;
317 binding_generator.new_config(&toml_value)?
318 };
319
320 let settings = GenerationSettings {
321 cdylib: match library_file {
322 Some(ref library_file) => {
323 library_mode::calc_cdylib_name(library_file.as_ref()).map(ToOwned::to_owned)
324 }
325 None => None,
326 },
327 out_dir: get_out_dir(
328 udl_file.as_ref(),
329 out_dir_override.as_ref().map(|p| p.as_ref()),
330 )?,
331 try_format_code,
332 };
333
334 let mut components = vec![Component { ci, config }];
335 binding_generator.update_component_configs(&settings, &mut components)?;
336 binding_generator.write_bindings(&settings, &components)
337 }
338
339 // Generate the infrastructural Rust code for implementing the UDL interface,
340 // such as the `extern "C"` function definitions and record data types.
341 // Locates and parses Cargo.toml to determine the name of the crate.
342 pub fn generate_component_scaffolding(
343 udl_file: &Utf8Path,
344 out_dir_override: Option<&Utf8Path>,
345 format_code: bool,
346 ) -> Result<()> {
347 let component = parse_udl(udl_file, &crate_name_from_cargo_toml(udl_file)?)
348 .with_context(|| format!("parsing udl file {udl_file}"))?;
349 generate_component_scaffolding_inner(component, udl_file, out_dir_override, format_code)
350 }
351
352 // Generate the infrastructural Rust code for implementing the UDL interface,
353 // such as the `extern "C"` function definitions and record data types, using
354 // the specified crate name.
355 pub fn generate_component_scaffolding_for_crate(
356 udl_file: &Utf8Path,
357 crate_name: &str,
358 out_dir_override: Option<&Utf8Path>,
359 format_code: bool,
360 ) -> Result<()> {
361 let component =
362 parse_udl(udl_file, crate_name).with_context(|| format!("parsing udl file {udl_file}"))?;
363 generate_component_scaffolding_inner(component, udl_file, out_dir_override, format_code)
364 }
365
366 fn generate_component_scaffolding_inner(
367 component: ComponentInterface,
368 udl_file: &Utf8Path,
369 out_dir_override: Option<&Utf8Path>,
370 format_code: bool,
371 ) -> Result<()> {
372 let file_stem = udl_file.file_stem().context("not a file")?;
373 let filename = format!("{file_stem}.uniffi.rs");
374 let out_path = get_out_dir(udl_file, out_dir_override)?.join(filename);
375 let mut f = File::create(&out_path)?;
376 write!(f, "{}", RustScaffolding::new(&component, file_stem))
377 .context("Failed to write output file")?;
378 if format_code {
379 format_code_with_rustfmt(&out_path).context("formatting generated Rust code")?;
380 }
381 Ok(())
382 }
383
384 // Generate the bindings in the target languages that call the scaffolding
385 // Rust code.
386 pub fn generate_bindings<T: BindingGenerator>(
387 udl_file: &Utf8Path,
388 config_file_override: Option<&Utf8Path>,
389 binding_generator: T,
390 out_dir_override: Option<&Utf8Path>,
391 library_file: Option<&Utf8Path>,
392 crate_name: Option<&str>,
393 try_format_code: bool,
394 ) -> Result<()> {
395 generate_external_bindings(
396 &binding_generator,
397 udl_file,
398 config_file_override,
399 out_dir_override,
400 library_file,
401 crate_name,
402 try_format_code,
403 )
404 }
405
406 pub fn print_repr(library_path: &Utf8Path) -> Result<()> {
407 let metadata = macro_metadata::extract_from_library(library_path)?;
408 println!("{metadata:#?}");
409 Ok(())
410 }
411
412 // Given the path to a UDL file, locate and parse the corresponding Cargo.toml to determine
413 // the library crate name.
414 // Note that this is largely a copy of code in uniffi_macros/src/util.rs, but sharing it
415 // isn't trivial and it's not particularly complicated so we've just copied it.
416 fn crate_name_from_cargo_toml(udl_file: &Utf8Path) -> Result<String> {
417 #[derive(Deserialize)]
418 struct CargoToml {
419 package: Package,
420 #[serde(default)]
421 lib: Lib,
422 }
423
424 #[derive(Deserialize)]
425 struct Package {
426 name: String,
427 }
428
429 #[derive(Default, Deserialize)]
430 struct Lib {
431 name: Option<String>,
432 }
433
434 let file = guess_crate_root(udl_file)?.join("Cargo.toml");
435 let cargo_toml_bytes =
436 fs::read(file).context("Can't find Cargo.toml to determine the crate name")?;
437
438 let cargo_toml = toml::from_slice::<CargoToml>(&cargo_toml_bytes)?;
439
440 let lib_crate_name = cargo_toml
441 .lib
442 .name
443 .unwrap_or_else(|| cargo_toml.package.name.replace('-', "_"));
444
445 Ok(lib_crate_name)
446 }
447
448 /// Guess the root directory of the crate from the path of its UDL file.
449 ///
450 /// For now, we assume that the UDL file is in `./src/something.udl` relative
451 /// to the crate root. We might consider something more sophisticated in
452 /// future.
453 pub fn guess_crate_root(udl_file: &Utf8Path) -> Result<&Utf8Path> {
454 let path_guess = udl_file
455 .parent()
456 .context("UDL file has no parent folder!")?
457 .parent()
458 .context("UDL file has no grand-parent folder!")?;
459 if !path_guess.join("Cargo.toml").is_file() {
460 bail!("UDL file does not appear to be inside a crate")
461 }
462 Ok(path_guess)
463 }
464
465 fn get_out_dir(udl_file: &Utf8Path, out_dir_override: Option<&Utf8Path>) -> Result<Utf8PathBuf> {
466 Ok(match out_dir_override {
467 Some(s) => {
468 // Create the directory if it doesn't exist yet.
469 fs::create_dir_all(s)?;
470 s.canonicalize_utf8().context("Unable to find out-dir")?
471 }
472 None => udl_file
473 .parent()
474 .context("File has no parent directory")?
475 .to_owned(),
476 })
477 }
478
479 fn parse_udl(udl_file: &Utf8Path, crate_name: &str) -> Result<ComponentInterface> {
480 let udl = fs::read_to_string(udl_file)
481 .with_context(|| format!("Failed to read UDL from {udl_file}"))?;
482 let group = uniffi_udl::parse_udl(&udl, crate_name)?;
483 ComponentInterface::from_metadata(group)
484 }
485
486 fn format_code_with_rustfmt(path: &Utf8Path) -> Result<()> {
487 let status = Command::new("rustfmt").arg(path).status().map_err(|e| {
488 let ctx = match e.kind() {
489 ErrorKind::NotFound => "formatting was requested, but rustfmt was not found",
490 _ => "unknown error when calling rustfmt",
491 };
492 anyhow!(e).context(ctx)
493 })?;
494 if !status.success() {
495 bail!("rustmt failed when formatting scaffolding. Note: --no-format can be used to skip formatting");
496 }
497 Ok(())
498 }
499
500 /// Load TOML from file if the file exists.
501 fn load_toml_file(source: Option<&Utf8Path>) -> Result<Option<toml::value::Table>> {
502 if let Some(source) = source {
503 if source.exists() {
504 let contents =
505 fs::read_to_string(source).with_context(|| format!("read file: {:?}", source))?;
506 return Ok(Some(
507 toml::de::from_str(&contents)
508 .with_context(|| format!("parse toml: {:?}", source))?,
509 ));
510 }
511 }
512
513 Ok(None)
514 }
515
516 /// Load the default `uniffi.toml` config, merge TOML trees with `config_file_override` if specified.
517 fn overridden_config_value(
518 mut config: toml::value::Table,
519 config_file_override: Option<&Utf8Path>,
520 ) -> Result<toml::Value> {
521 let override_config = load_toml_file(config_file_override).context("override config")?;
522 if let Some(override_config) = override_config {
523 merge_toml(&mut config, override_config);
524 }
525 Ok(toml::Value::from(config))
526 }
527
528 fn merge_toml(a: &mut toml::value::Table, b: toml::value::Table) {
529 for (key, value) in b.into_iter() {
530 match a.get_mut(&key) {
531 Some(existing_value) => match (existing_value, value) {
532 (toml::Value::Table(ref mut t0), toml::Value::Table(t1)) => {
533 merge_toml(t0, t1);
534 }
535 (v, value) => *v = value,
536 },
537 None => {
538 a.insert(key, value);
539 }
540 }
541 }
542 }
543
544 // FIXME(HACK):
545 // Include the askama config file into the build.
546 // That way cargo tracks the file and other tools relying on file tracking see it as well.
547 // See https://bugzilla.mozilla.org/show_bug.cgi?id=1774585
548 // In the future askama should handle that itself by using the `track_path::path` API,
549 // see https://github.com/rust-lang/rust/pull/84029
550 #[allow(dead_code)]
551 mod __unused {
552 const _: &[u8] = include_bytes!("../askama.toml");
553 }
554
555 #[cfg(test)]
556 mod test {
557 use super::*;
558
559 #[test]
560 fn test_guessing_of_crate_root_directory_from_udl_file() {
561 // When running this test, this will be the ./uniffi_bindgen directory.
562 let this_crate_root = Utf8PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap());
563
564 let example_crate_root = this_crate_root
565 .parent()
566 .expect("should have a parent directory")
567 .join("examples/arithmetic");
568 assert_eq!(
569 guess_crate_root(&example_crate_root.join("src/arthmetic.udl")).unwrap(),
570 example_crate_root
571 );
572
573 let not_a_crate_root = &this_crate_root.join("src/templates");
574 assert!(guess_crate_root(&not_a_crate_root.join("src/example.udl")).is_err());
575 }
576
577 #[test]
578 fn test_merge_toml() {
579 let default = r#"
580 foo = "foo"
581 bar = "bar"
582
583 [table1]
584 foo = "foo"
585 bar = "bar"
586 "#;
587 let mut default = toml::de::from_str(default).unwrap();
588
589 let override_toml = r#"
590 # update key
591 bar = "BAR"
592 # insert new key
593 baz = "BAZ"
594
595 [table1]
596 # update key
597 bar = "BAR"
598 # insert new key
599 baz = "BAZ"
600
601 # new table
602 [table1.table2]
603 bar = "BAR"
604 baz = "BAZ"
605 "#;
606 let override_toml = toml::de::from_str(override_toml).unwrap();
607
608 let expected = r#"
609 foo = "foo"
610 bar = "BAR"
611 baz = "BAZ"
612
613 [table1]
614 foo = "foo"
615 bar = "BAR"
616 baz = "BAZ"
617
618 [table1.table2]
619 bar = "BAR"
620 baz = "BAZ"
621 "#;
622 let expected: toml::value::Table = toml::de::from_str(expected).unwrap();
623
624 merge_toml(&mut default, override_toml);
625
626 assert_eq!(&expected, &default);
627 }
628 }