use crate::{
bindings::GenerateOptions,
interface::{apply_exclusions, rename},
BindgenLoader, BindgenPaths, Component, ComponentInterface, GlobalConfig,
};
use anyhow::{bail, Result};
use camino::Utf8PathBuf;
use fs_err as fs;
use std::collections::HashMap;
use std::process::Command;
mod gen_swift;
use gen_swift::{generate_bindings, generate_header, generate_modulemap, generate_swift, Config};
#[cfg(feature = "bindgen-tests")]
pub mod test;
struct Bindings {
library: String,
header: String,
modulemap: Option<String>,
}
pub fn generate(
loader: &BindgenLoader,
options: GenerateOptions,
) -> Result<Vec<Component<Config>>> {
let metadata = loader.load_metadata(&options.source)?;
if let Some(crate_filter) = &options.crate_filter {
if !metadata.contains_key(crate_filter) {
bail!("No UniFFI metadata found for crate {crate_filter}");
}
}
let cis = loader.load_cis(metadata)?;
let mut components = loader.load_components(cis, parse_config)?;
apply_renames(&mut components);
for c in components.iter_mut() {
c.ci.derive_ffi_funcs()?;
}
for Component { ci, config, .. } in components.iter_mut() {
if let Some(crate_filter) = &options.crate_filter {
if ci.crate_name() != crate_filter {
continue;
}
}
let Bindings {
header,
library,
modulemap,
} = generate_bindings(config, ci)?;
let source_file = options
.out_dir
.join(format!("{}.swift", config.module_name()));
fs::write(&source_file, library)?;
let header_file = options.out_dir.join(config.header_filename());
fs::write(header_file, header)?;
if let Some(modulemap) = modulemap {
let modulemap_file = options.out_dir.join(config.modulemap_filename());
fs::write(modulemap_file, modulemap)?;
}
if options.format {
let commands_to_try = [
vec!["xcrun", "swift-format"],
vec!["swift-format"],
vec!["swift", "format"],
vec!["swiftformat"],
];
let successful_output = commands_to_try.into_iter().find_map(|command| {
Command::new(command[0])
.args(&command[1..])
.arg(source_file.as_str())
.output()
.ok()
});
if successful_output.is_none() {
println!(
"Warning: Unable to auto-format {} using swift-format. Please make sure it is installed.",
source_file.as_str()
);
}
}
}
Ok(components)
}
pub fn generate_swift_bindings(options: SwiftBindingsOptions) -> Result<()> {
#[cfg(not(feature = "cargo-metadata"))]
let mut paths = BindgenPaths::default();
#[cfg(feature = "cargo-metadata")]
let mut paths = BindgenPaths::default();
let global_config = if let Some(ref path) = options.config {
let (config, crate_roots_layer) = GlobalConfig::from_file(path)?;
if let Some(layer) = crate_roots_layer {
paths.add_layer(layer);
}
config
} else {
GlobalConfig::default()
};
#[cfg(feature = "cargo-metadata")]
paths.add_cargo_metadata_layer(options.metadata_no_deps)?;
fs::create_dir_all(&options.out_dir)?;
let loader = BindgenLoader::new(paths, global_config);
let metadata = loader.load_metadata(&options.source)?;
let cis = loader.load_cis(metadata)?;
let mut components = loader.load_components(cis, parse_config)?;
apply_renames(&mut components);
for Component { ci, .. } in components.iter_mut() {
ci.derive_ffi_funcs()?;
}
for Component { ci, config } in &components {
if options.generate_swift_sources {
let source_file = options
.out_dir
.join(format!("{}.swift", config.module_name()));
fs::write(&source_file, generate_swift(config, ci)?)?;
}
if options.generate_headers {
let header_file = options.out_dir.join(config.header_filename());
fs::write(header_file, generate_header(config, ci)?)?;
}
}
let source_basename = loader.source_basename(&options.source);
let module_name = options
.module_name
.unwrap_or_else(|| source_basename.to_string());
let modulemap_filename = options
.modulemap_filename
.unwrap_or_else(|| format!("{source_basename}.modulemap"));
if options.generate_modulemap {
let mut header_filenames: Vec<_> = components
.iter()
.map(|Component { config, .. }| config.header_filename())
.collect();
header_filenames.sort();
let modulemap_source = generate_modulemap(
module_name,
header_filenames,
options.xcframework,
options.link_frameworks,
)?;
let modulemap_path = options.out_dir.join(modulemap_filename);
fs::write(modulemap_path, modulemap_source)?;
}
Ok(())
}
fn parse_config(ci: &ComponentInterface, root_toml: toml::Value) -> Result<Config> {
let mut config: Config = match root_toml.get("bindings").and_then(|b| b.get("swift")) {
Some(v) => v.clone().try_into()?,
None => Default::default(),
};
config
.module_name
.get_or_insert_with(|| ci.namespace().into());
Ok(config)
}
#[derive(Debug, Default)]
pub struct SwiftBindingsOptions {
pub generate_swift_sources: bool,
pub generate_headers: bool,
pub generate_modulemap: bool,
pub source: Utf8PathBuf,
pub out_dir: Utf8PathBuf,
pub xcframework: bool,
pub module_name: Option<String>,
pub modulemap_filename: Option<String>,
pub metadata_no_deps: bool,
pub link_frameworks: Vec<String>,
pub config: Option<Utf8PathBuf>,
}
fn apply_renames(components: &mut Vec<Component<Config>>) {
for c in components.iter_mut() {
apply_exclusions(&mut c.ci, &c.config.exclude);
}
let mut module_renames = HashMap::new();
for c in components.iter() {
if !c.config.rename.is_empty() {
let module_path = c.ci.crate_name().to_string();
module_renames.insert(module_path, c.config.rename.clone());
}
}
if !module_renames.is_empty() {
for c in &mut *components {
rename(&mut c.ci, &module_renames);
}
}
}