| 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 |
//! # Swift bindings backend for UniFFI |
| 6 |
//! |
| 7 |
//! This module generates Swift bindings from a [`crate::ComponentInterface`] definition, |
| 8 |
//! using Swift's builtin support for loading C header files. |
| 9 |
//! |
| 10 |
//! Conceptually, the generated bindings are split into two Swift modules, one for the low-level |
| 11 |
//! C FFI layer and one for the higher-level Swift bindings. For a UniFFI component named "example" |
| 12 |
//! we generate: |
| 13 |
//! |
| 14 |
//! * A C header file `exampleFFI.h` declaring the low-level structs and functions for calling |
| 15 |
//! into Rust, along with a corresponding `exampleFFI.modulemap` to expose them to Swift. |
| 16 |
//! |
| 17 |
//! * A Swift source file `example.swift` that imports the `exampleFFI` module and wraps it |
| 18 |
//! to provide the higher-level Swift API. |
| 19 |
//! |
| 20 |
//! Most of the concepts in a [`crate::ComponentInterface`] have an obvious counterpart in Swift, |
| 21 |
//! with the details documented in inline comments where appropriate. |
| 22 |
//! |
| 23 |
//! To handle lifting/lowering/serializing types across the FFI boundary, the Swift code |
| 24 |
//! defines a `protocol ViaFfi` that is analogous to the `uniffi::ViaFfi` Rust trait. |
| 25 |
//! Each type that can traverse the FFI conforms to the `ViaFfi` protocol, which specifies: |
| 26 |
//! |
| 27 |
//! * The corresponding low-level type. |
| 28 |
//! * How to lift from and lower into into that type. |
| 29 |
//! * How to read from and write into a byte buffer. |
| 30 |
//! |
| 31 |
|
| 32 |
use crate::{BindingGenerator, Component, GenerationSettings}; |
| 33 |
use anyhow::{Context, Result}; |
| 34 |
use camino::Utf8PathBuf; |
| 35 |
use fs_err as fs; |
| 36 |
use std::process::Command; |
| 37 |
|
| 38 |
mod gen_swift; |
| 39 |
use gen_swift::{generate_bindings, generate_header, generate_modulemap, generate_swift, Config}; |
| 40 |
|
| 41 |
#[cfg(feature = "bindgen-tests")] |
| 42 |
pub mod test; |
| 43 |
|
| 44 |
/// The Swift bindings generated from a [`crate::ComponentInterface`]. |
| 45 |
/// |
| 46 |
struct Bindings { |
| 47 |
/// The contents of the generated `.swift` file, as a string. |
| 48 |
library: String, |
| 49 |
/// The contents of the generated `.h` file, as a string. |
| 50 |
header: String, |
| 51 |
/// The contents of the generated `.modulemap` file, as a string. |
| 52 |
modulemap: Option<String>, |
| 53 |
} |
| 54 |
|
| 55 |
pub struct SwiftBindingGenerator; |
| 56 |
impl BindingGenerator for SwiftBindingGenerator { |
| 57 |
type Config = Config; |
| 58 |
|
| 59 |
fn new_config(&self, root_toml: &toml::Value) -> Result<Self::Config> { |
| 60 |
Ok( |
| 61 |
match root_toml.get("bindings").and_then(|b| b.get("swift")) { |
| 62 |
Some(v) => v.clone().try_into()?, |
| 63 |
None => Default::default(), |
| 64 |
}, |
| 65 |
) |
| 66 |
} |
| 67 |
|
| 68 |
fn update_component_configs( |
| 69 |
&self, |
| 70 |
_settings: &GenerationSettings, |
| 71 |
components: &mut Vec<Component<Self::Config>>, |
| 72 |
) -> Result<()> { |
| 73 |
for c in &mut *components { |
| 74 |
c.config |
| 75 |
.module_name |
| 76 |
.get_or_insert_with(|| c.ci.namespace().into()); |
| 77 |
} |
| 78 |
Ok(()) |
| 79 |
} |
| 80 |
|
| 81 |
/// Unlike other target languages, binding to Rust code from Swift involves more than just |
| 82 |
/// generating a `.swift` file. We also need to produce a `.h` file with the C-level API |
| 83 |
/// declarations, and a `.modulemap` file to tell Swift how to use it. |
| 84 |
fn write_bindings( |
| 85 |
&self, |
| 86 |
settings: &GenerationSettings, |
| 87 |
components: &[Component<Self::Config>], |
| 88 |
) -> Result<()> { |
| 89 |
for Component { ci, config, .. } in components { |
| 90 |
let Bindings { |
| 91 |
header, |
| 92 |
library, |
| 93 |
modulemap, |
| 94 |
} = generate_bindings(config, ci)?; |
| 95 |
|
| 96 |
let source_file = settings |
| 97 |
.out_dir |
| 98 |
.join(format!("{}.swift", config.module_name())); |
| 99 |
fs::write(&source_file, library)?; |
| 100 |
|
| 101 |
let header_file = settings.out_dir.join(config.header_filename()); |
| 102 |
fs::write(header_file, header)?; |
| 103 |
|
| 104 |
if let Some(modulemap) = modulemap { |
| 105 |
let modulemap_file = settings.out_dir.join(config.modulemap_filename()); |
| 106 |
fs::write(modulemap_file, modulemap)?; |
| 107 |
} |
| 108 |
|
| 109 |
if settings.try_format_code { |
| 110 |
let commands_to_try = [ |
| 111 |
// Available in Xcode 16. |
| 112 |
vec!["xcrun", "swift-format"], |
| 113 |
// The official swift-format command name. |
| 114 |
vec!["swift-format"], |
| 115 |
// Shortcut for the swift-format command. |
| 116 |
vec!["swift", "format"], |
| 117 |
vec!["swiftformat"], |
| 118 |
]; |
| 119 |
|
| 120 |
let successful_output = commands_to_try.into_iter().find_map(|command| { |
| 121 |
Command::new(command[0]) |
| 122 |
.args(&command[1..]) |
| 123 |
.arg(source_file.as_str()) |
| 124 |
.output() |
| 125 |
.ok() |
| 126 |
}); |
| 127 |
if successful_output.is_none() { |
| 128 |
println!( |
| 129 |
"Warning: Unable to auto-format {} using swift-format. Please make sure it is installed.", |
| 130 |
source_file.as_str() |
| 131 |
); |
| 132 |
} |
| 133 |
} |
| 134 |
} |
| 135 |
|
| 136 |
Ok(()) |
| 137 |
} |
| 138 |
} |
| 139 |
|
| 140 |
/// Generate Swift bindings |
| 141 |
/// |
| 142 |
/// This is used by the uniffi-bindgen-swift command, which supports Swift-specific options. |
| 143 |
/// |
| 144 |
/// In the future, we may want to replace the generalized `uniffi-bindgen` with a set of |
| 145 |
/// specialized `uniffi-bindgen-[language]` commands. |
| 146 |
pub fn generate_swift_bindings(options: SwiftBindingsOptions) -> Result<()> { |
| 147 |
#[cfg(feature = "cargo-metadata")] |
| 148 |
let config_supplier = { |
| 149 |
use crate::cargo_metadata::CrateConfigSupplier; |
| 150 |
let mut cmd = cargo_metadata::MetadataCommand::new(); |
| 151 |
if options.metadata_no_deps { |
| 152 |
cmd.no_deps(); |
| 153 |
} |
| 154 |
let metadata = cmd.exec().context("error running cargo metadata")?; |
| 155 |
CrateConfigSupplier::from(metadata) |
| 156 |
}; |
| 157 |
#[cfg(not(feature = "cargo-metadata"))] |
| 158 |
let config_supplier = crate::EmptyCrateConfigSupplier; |
| 159 |
|
| 160 |
fs::create_dir_all(&options.out_dir)?; |
| 161 |
|
| 162 |
let mut components = |
| 163 |
crate::library_mode::find_components(&options.library_path, &config_supplier)? |
| 164 |
// map the TOML configs into a our Config struct |
| 165 |
.into_iter() |
| 166 |
.map(|Component { ci, config }| { |
| 167 |
let config = SwiftBindingGenerator.new_config(&config.into())?; |
| 168 |
Ok(Component { ci, config }) |
| 169 |
}) |
| 170 |
.collect::<Result<Vec<_>>>()?; |
| 171 |
SwiftBindingGenerator |
| 172 |
.update_component_configs(&GenerationSettings::default(), &mut components)?; |
| 173 |
|
| 174 |
for Component { ci, config } in &components { |
| 175 |
if options.generate_swift_sources { |
| 176 |
let source_file = options |
| 177 |
.out_dir |
| 178 |
.join(format!("{}.swift", config.module_name())); |
| 179 |
fs::write(&source_file, generate_swift(config, ci)?)?; |
| 180 |
} |
| 181 |
|
| 182 |
if options.generate_headers { |
| 183 |
let header_file = options.out_dir.join(config.header_filename()); |
| 184 |
fs::write(header_file, generate_header(config, ci)?)?; |
| 185 |
} |
| 186 |
} |
| 187 |
|
| 188 |
// find the library name by stripping the extension and leading `lib` from the library path |
| 189 |
let library_name = { |
| 190 |
let stem = options |
| 191 |
.library_path |
| 192 |
.file_stem() |
| 193 |
.with_context(|| format!("Invalid library path {}", options.library_path))?; |
| 194 |
match stem.strip_prefix("lib") { |
| 195 |
Some(name) => name, |
| 196 |
None => stem, |
| 197 |
} |
| 198 |
}; |
| 199 |
|
| 200 |
let module_name = options |
| 201 |
.module_name |
| 202 |
.unwrap_or_else(|| library_name.to_string()); |
| 203 |
let modulemap_filename = options |
| 204 |
.modulemap_filename |
| 205 |
.unwrap_or_else(|| format!("{library_name}.modulemap")); |
| 206 |
|
| 207 |
if options.generate_modulemap { |
| 208 |
let mut header_filenames: Vec<_> = components |
| 209 |
.iter() |
| 210 |
.map(|Component { config, .. }| config.header_filename()) |
| 211 |
.collect(); |
| 212 |
header_filenames.sort(); |
| 213 |
let modulemap_source = generate_modulemap( |
| 214 |
module_name, |
| 215 |
header_filenames, |
| 216 |
options.xcframework, |
| 217 |
options.link_frameworks, |
| 218 |
)?; |
| 219 |
let modulemap_path = options.out_dir.join(modulemap_filename); |
| 220 |
fs::write(modulemap_path, modulemap_source)?; |
| 221 |
} |
| 222 |
|
| 223 |
Ok(()) |
| 224 |
} |
| 225 |
|
| 226 |
#[derive(Debug, Default)] |
| 227 |
pub struct SwiftBindingsOptions { |
| 228 |
pub generate_swift_sources: bool, |
| 229 |
pub generate_headers: bool, |
| 230 |
pub generate_modulemap: bool, |
| 231 |
pub library_path: Utf8PathBuf, |
| 232 |
pub out_dir: Utf8PathBuf, |
| 233 |
pub xcframework: bool, |
| 234 |
pub module_name: Option<String>, |
| 235 |
pub modulemap_filename: Option<String>, |
| 236 |
pub metadata_no_deps: bool, |
| 237 |
pub link_frameworks: Vec<String>, |
| 238 |
} |