Debian Codegraph @

third_party/rust/uniffi/src/cli/uniffi_bindgen.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 use anyhow::{bail, Context, Result};
6 use camino::Utf8PathBuf;
7 use clap::{Args, Parser, Subcommand, ValueEnum};
8 use std::fmt;
9 use uniffi_bindgen::bindings::*;
10 use uniffi_bindgen::pipeline::initial;
11 use uniffi_pipeline::PrintOptions;
12
13 /// Enumeration of all foreign language targets currently supported by our CLI.
14 ///
15 #[derive(Copy, Clone, Eq, PartialEq, Hash, ValueEnum)]
16 enum TargetLanguage {
17 Kotlin,
18 Swift,
19 Python,
20 Ruby,
21 }
22
23 impl fmt::Display for TargetLanguage {
24 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
25 match self {
26 Self::Kotlin => write!(f, "kotlin"),
27 Self::Swift => write!(f, "swift"),
28 Self::Python => write!(f, "python"),
29 Self::Ruby => write!(f, "ruby"),
30 }
31 }
32 }
33
34 impl TryFrom<&str> for TargetLanguage {
35 type Error = anyhow::Error;
36 fn try_from(value: &str) -> Result<Self> {
37 Ok(match value.to_ascii_lowercase().as_str() {
38 "kotlin" | "kt" | "kts" => TargetLanguage::Kotlin,
39 "swift" => TargetLanguage::Swift,
40 "python" | "py" => TargetLanguage::Python,
41 "ruby" | "rb" => TargetLanguage::Ruby,
42 _ => bail!("Unknown or unsupported target language: \"{value}\""),
43 })
44 }
45 }
46
47 impl TryFrom<&std::ffi::OsStr> for TargetLanguage {
48 type Error = anyhow::Error;
49 fn try_from(value: &std::ffi::OsStr) -> Result<Self> {
50 match value.to_str() {
51 None => bail!("Unreadable target language"),
52 Some(s) => s.try_into(),
53 }
54 }
55 }
56
57 impl TryFrom<String> for TargetLanguage {
58 type Error = anyhow::Error;
59 fn try_from(value: String) -> Result<Self> {
60 TryFrom::try_from(value.as_str())
61 }
62 }
63
64 // Structs to help our cmdline parsing. Note that docstrings below form part
65 // of the "help" output.
66
67 /// Scaffolding and bindings generator for Rust
68 #[derive(Parser)]
69 #[clap(name = "uniffi-bindgen")]
70 #[clap(version = clap::crate_version!())]
71 #[clap(propagate_version = true)]
72 struct Cli {
73 #[clap(subcommand)]
74 command: Commands,
75 }
76
77 #[derive(Subcommand)]
78 enum Commands {
79 /// Generate foreign language bindings
80 Generate {
81 /// Foreign language(s) for which to build bindings.
82 #[clap(long, short, value_enum)]
83 language: Vec<TargetLanguage>,
84
85 /// Directory in which to write generated files. Default is same folder as .udl file.
86 #[clap(long, short)]
87 out_dir: Option<Utf8PathBuf>,
88
89 /// Do not try to format the generated bindings.
90 #[clap(long, short)]
91 no_format: bool,
92
93 /// Path to optional uniffi config file. This config is merged with the `uniffi.toml` config present in each crate, with its values taking precedence.
94 #[clap(long, short)]
95 config: Option<Utf8PathBuf>,
96
97 /// Extract proc-macro metadata from a native lib (cdylib or staticlib) for this crate.
98 #[clap(long)]
99 lib_file: Option<Utf8PathBuf>,
100
101 /// Pass in a cdylib path rather than a UDL file
102 #[clap(long = "library")]
103 library_mode: bool,
104
105 /// When `--library` is passed, only generate bindings for one crate.
106 /// When `--library` is not passed, use this as the crate name instead of attempting to
107 /// locate and parse Cargo.toml.
108 #[clap(long = "crate")]
109 crate_name: Option<String>,
110
111 /// Path to the UDL file, or cdylib if `library-mode` is specified
112 source: Utf8PathBuf,
113
114 /// Whether we should exclude dependencies when running "cargo metadata".
115 /// This will mean external types may not be resolved if they are implemented in crates
116 /// outside of this workspace.
117 /// This can be used in environments when all types are in the namespace and fetching
118 /// all sub-dependencies causes obscure platform specific problems.
119 #[clap(long)]
120 metadata_no_deps: bool,
121 },
122
123 /// Generate Rust scaffolding code
124 Scaffolding {
125 /// Directory in which to write generated files. Default is same folder as .udl file.
126 #[clap(long, short)]
127 out_dir: Option<Utf8PathBuf>,
128
129 /// Do not try to format the generated bindings.
130 #[clap(long, short)]
131 no_format: bool,
132
133 /// Path to the UDL file.
134 udl_file: Utf8PathBuf,
135 },
136
137 /// Inspect the bindings render pipeline
138 Pipeline(PipelineArgs),
139 }
140
141 #[derive(Args)]
142 struct PipelineArgs {
143 /// Pass in a cdylib path rather than a UDL file
144 #[clap(long = "library")]
145 library_mode: bool,
146
147 /// Path to the UDL file, or cdylib if `library-mode` is specified
148 source: Utf8PathBuf,
149
150 /// When `--library` is passed, only generate bindings for one crate.
151 /// When `--library` is not passed, use this as the crate name instead of attempting to
152 /// locate and parse Cargo.toml.
153 #[clap(long = "crate")]
154 crate_name: Option<String>,
155
156 /// Whether we should exclude dependencies when running "cargo metadata".
157 /// This will mean external types may not be resolved if they are implemented in crates
158 /// outside of this workspace.
159 /// This can be used in environments when all types are in the namespace and fetching
160 /// all sub-dependencies causes obscure platform specific problems.
161 #[clap(long)]
162 metadata_no_deps: bool,
163
164 /// Bindings Language
165 language: TargetLanguage,
166
167 /// Only show passes that match <PASS>
168 ///
169 /// Use `last` to only show the last pass, this can be useful when you're writing new pipelines
170 #[clap(short, long)]
171 pass: Option<String>,
172
173 /// Don't show diffs for middle passes
174 #[clap(long)]
175 no_diff: bool,
176
177 /// Only show data for types with name <FILTER_TYPE>
178 #[clap(short = 't', long = "type")]
179 filter_type: Option<String>,
180
181 /// Only show data for items with fields that match <FILTER>
182 #[clap(short = 'n', long = "name")]
183 filter_name: Option<String>,
184 }
185
186 fn config_supplier(
187 metadata_no_deps: bool,
188 ) -> Result<impl uniffi_bindgen::BindgenCrateConfigSupplier> {
189 #[cfg(feature = "cargo-metadata")]
190 {
191 use uniffi_bindgen::cargo_metadata::CrateConfigSupplier;
192 let mut cmd = cargo_metadata::MetadataCommand::new();
193 if metadata_no_deps {
194 cmd.no_deps();
195 }
196 let metadata = cmd.exec().context("error running cargo metadata")?;
197 Ok(CrateConfigSupplier::from(metadata))
198 }
199 #[cfg(not(feature = "cargo-metadata"))]
200 Ok(uniffi_bindgen::EmptyCrateConfigSupplier)
201 }
202
203 fn gen_library_mode(
204 library_path: &camino::Utf8Path,
205 crate_name: Option<String>,
206 languages: Vec<TargetLanguage>,
207 cfo: Option<&camino::Utf8Path>,
208 out_dir: &camino::Utf8Path,
209 fmt: bool,
210 metadata_no_deps: bool,
211 ) -> anyhow::Result<()> {
212 use uniffi_bindgen::library_mode::generate_bindings;
213
214 let config_supplier = config_supplier(metadata_no_deps)?;
215
216 for language in languages {
217 // to help avoid mistakes we check the library is actually a cdylib, except
218 // for swift where static libs are often used to extract the metadata.
219 if !matches!(language, TargetLanguage::Swift) && !uniffi_bindgen::is_cdylib(library_path) {
220 anyhow::bail!(
221 "Generate bindings for {language} requires a cdylib, but {library_path} was given"
222 );
223 }
224
225 // Type-bounds on trait implementations makes selecting between languages a bit tedious.
226 match language {
227 TargetLanguage::Kotlin => generate_bindings(
228 library_path,
229 crate_name.clone(),
230 &KotlinBindingGenerator,
231 &config_supplier,
232 cfo,
233 out_dir,
234 fmt,
235 )?
236 .len(),
237 TargetLanguage::Python => generate_bindings(
238 library_path,
239 crate_name.clone(),
240 &PythonBindingGenerator,
241 &config_supplier,
242 cfo,
243 out_dir,
244 fmt,
245 )?
246 .len(),
247 TargetLanguage::Ruby => generate_bindings(
248 library_path,
249 crate_name.clone(),
250 &RubyBindingGenerator,
251 &config_supplier,
252 cfo,
253 out_dir,
254 fmt,
255 )?
256 .len(),
257 TargetLanguage::Swift => generate_bindings(
258 library_path,
259 crate_name.clone(),
260 &SwiftBindingGenerator,
261 &config_supplier,
262 cfo,
263 out_dir,
264 fmt,
265 )?
266 .len(),
267 };
268 }
269 Ok(())
270 }
271
272 fn gen_bindings(
273 udl_file: &camino::Utf8Path,
274 cfo: Option<&camino::Utf8Path>,
275 languages: Vec<TargetLanguage>,
276 odo: Option<&camino::Utf8Path>,
277 library_file: Option<&camino::Utf8Path>,
278 crate_name: Option<&str>,
279 fmt: bool,
280 ) -> anyhow::Result<()> {
281 use uniffi_bindgen::generate_bindings;
282 for language in languages {
283 match language {
284 TargetLanguage::Kotlin => generate_bindings(
285 udl_file,
286 cfo,
287 KotlinBindingGenerator,
288 odo,
289 library_file,
290 crate_name,
291 fmt,
292 )?,
293 TargetLanguage::Python => generate_bindings(
294 udl_file,
295 cfo,
296 PythonBindingGenerator,
297 odo,
298 library_file,
299 crate_name,
300 fmt,
301 )?,
302 TargetLanguage::Ruby => generate_bindings(
303 udl_file,
304 cfo,
305 RubyBindingGenerator,
306 odo,
307 library_file,
308 crate_name,
309 fmt,
310 )?,
311 TargetLanguage::Swift => generate_bindings(
312 udl_file,
313 cfo,
314 SwiftBindingGenerator,
315 odo,
316 library_file,
317 crate_name,
318 fmt,
319 )?,
320 };
321 }
322 Ok(())
323 }
324
325 pub fn run_main() -> anyhow::Result<()> {
326 let cli = Cli::parse();
327 match cli.command {
328 Commands::Generate {
329 language,
330 out_dir,
331 no_format,
332 config,
333 lib_file,
334 source,
335 crate_name,
336 library_mode,
337 metadata_no_deps,
338 } => {
339 if library_mode {
340 if lib_file.is_some() {
341 panic!("--lib-file is not compatible with --library.")
342 }
343 let out_dir = out_dir.expect("--out-dir is required when using --library");
344 if language.is_empty() {
345 panic!("please specify at least one language with --language")
346 }
347 gen_library_mode(
348 &source,
349 crate_name,
350 language,
351 config.as_deref(),
352 &out_dir,
353 !no_format,
354 metadata_no_deps,
355 )?;
356 } else {
357 if metadata_no_deps {
358 panic!("--metadata-no-deps makes no sense when not in library mode")
359 }
360 gen_bindings(
361 &source,
362 config.as_deref(),
363 language,
364 out_dir.as_deref(),
365 lib_file.as_deref(),
366 crate_name.as_deref(),
367 !no_format,
368 )?;
369 }
370 }
371 Commands::Scaffolding {
372 out_dir,
373 no_format,
374 udl_file,
375 } => {
376 uniffi_bindgen::generate_component_scaffolding(
377 &udl_file,
378 out_dir.as_deref(),
379 !no_format,
380 )?;
381 }
382 Commands::Pipeline(args) => {
383 let config_supplier = config_supplier(args.metadata_no_deps)?;
384 let initial_root = if args.library_mode {
385 initial::Root::from_library(config_supplier, &args.source, args.crate_name)?
386 } else {
387 initial::Root::from_udl(config_supplier, &args.source, args.crate_name)?
388 };
389
390 let opts = PrintOptions {
391 pass: args.pass,
392 no_diff: args.no_diff,
393 filter_type: args.filter_type,
394 filter_name: args.filter_name,
395 };
396 match args.language {
397 TargetLanguage::Python => python::pipeline().print_passes(initial_root, opts)?,
398 language => unimplemented!("{language} does not use the bindings IR pipeline yet"),
399 };
400 }
401 };
402 Ok(())
403 }