Debian Codegraph @

options/cli.rs

raw
1 #![allow(unused_qualifications)] // Clap somehow generates a lot of these
2
3 use crate::{
4 builder,
5 callbacks::{
6 AttributeInfo, DeriveInfo, ItemInfo, ParseCallbacks, TypeKind,
7 },
8 features::{RustEdition, EARLIEST_STABLE_RUST},
9 regex_set::RegexSet,
10 Abi, AliasVariation, Builder, CodegenConfig, EnumVariation,
11 FieldVisibilityKind, Formatter, MacroTypeVariation, NonCopyUnionStyle,
12 RustTarget,
13 };
14 use clap::{
15 error::{Error, ErrorKind},
16 CommandFactory, Parser,
17 };
18 use proc_macro2::TokenStream;
19 use std::io;
20 use std::path::{Path, PathBuf};
21 use std::str::FromStr;
22 use std::{fs::File, process::exit};
23
24 fn rust_target_help() -> String {
25 format!(
26 "Version of the Rust compiler to target. Any Rust version after {EARLIEST_STABLE_RUST} is supported. Defaults to {}.",
27 RustTarget::default()
28 )
29 }
30
31 fn rust_edition_help() -> String {
32 format!("Rust edition to target. Defaults to the latest edition supported by the chosen Rust target. Possible values: ({}). ", RustEdition::ALL.map(|e| e.to_string()).join("|"))
33 }
34
35 fn parse_codegen_config(
36 what_to_generate: &str,
37 ) -> Result<CodegenConfig, Error> {
38 let mut config = CodegenConfig::empty();
39 for what in what_to_generate.split(',') {
40 match what {
41 "functions" => config.insert(CodegenConfig::FUNCTIONS),
42 "types" => config.insert(CodegenConfig::TYPES),
43 "vars" => config.insert(CodegenConfig::VARS),
44 "methods" => config.insert(CodegenConfig::METHODS),
45 "constructors" => config.insert(CodegenConfig::CONSTRUCTORS),
46 "destructors" => config.insert(CodegenConfig::DESTRUCTORS),
47 otherwise => {
48 return Err(Error::raw(
49 ErrorKind::InvalidValue,
50 format!("Unknown codegen item kind: {otherwise}"),
51 ));
52 }
53 }
54 }
55
56 Ok(config)
57 }
58
59 fn parse_rustfmt_config_path(path_str: &str) -> Result<PathBuf, Error> {
60 let path = Path::new(path_str);
61
62 if !path.is_absolute() {
63 return Err(Error::raw(
64 ErrorKind::InvalidValue,
65 "--rustfmt-configuration-file needs to be an absolute path!",
66 ));
67 }
68
69 if path.to_str().is_none() {
70 return Err(Error::raw(
71 ErrorKind::InvalidUtf8,
72 "--rustfmt-configuration-file contains non-valid UTF8 characters.",
73 ));
74 }
75
76 Ok(path.to_path_buf())
77 }
78
79 fn parse_abi_override(abi_override: &str) -> Result<(Abi, String), Error> {
80 let (regex, abi_str) = abi_override
81 .rsplit_once('=')
82 .ok_or_else(|| Error::raw(ErrorKind::InvalidValue, "Missing `=`"))?;
83
84 let abi = abi_str
85 .parse()
86 .map_err(|err| Error::raw(ErrorKind::InvalidValue, err))?;
87
88 Ok((abi, regex.to_owned()))
89 }
90
91 fn parse_custom_derive(
92 custom_derive: &str,
93 ) -> Result<(Vec<String>, String), Error> {
94 let (regex, derives) = custom_derive
95 .rsplit_once('=')
96 .ok_or_else(|| Error::raw(ErrorKind::InvalidValue, "Missing `=`"))?;
97
98 let derives = derives.split(',').map(|s| s.to_owned()).collect();
99
100 Ok((derives, regex.to_owned()))
101 }
102
103 fn parse_custom_attribute(
104 custom_attribute: &str,
105 ) -> Result<(Vec<String>, String), Error> {
106 let mut brace_level = 0;
107 let (regex, attributes) = custom_attribute
108 .rsplit_once(|c| {
109 match c {
110 ']' => brace_level += 1,
111 '[' => brace_level -= 1,
112 _ => {}
113 }
114 c == '=' && brace_level == 0
115 })
116 .ok_or_else(|| Error::raw(ErrorKind::InvalidValue, "Missing `=`"))?;
117
118 let mut brace_level = 0;
119 let attributes = attributes
120 .split(|c| {
121 match c {
122 ']' => brace_level += 1,
123 '[' => brace_level -= 1,
124 _ => {}
125 }
126 c == ',' && brace_level == 0
127 })
128 .map(|s| s.to_owned())
129 .collect::<Vec<_>>();
130
131 for attribute in &attributes {
132 if let Err(err) = TokenStream::from_str(attribute) {
133 return Err(Error::raw(ErrorKind::InvalidValue, err));
134 }
135 }
136
137 Ok((attributes, regex.to_owned()))
138 }
139
140 #[derive(Parser, Debug)]
141 #[clap(
142 about = "Generates Rust bindings from C/C++ headers.",
143 override_usage = "bindgen <FLAGS> <OPTIONS> <HEADER> -- <CLANG_ARGS>...",
144 trailing_var_arg = true
145 )]
146 #[allow(clippy::doc_markdown)]
147 struct BindgenCommand {
148 /// C or C++ header file.
149 header: Option<String>,
150 /// Path to write depfile to.
151 #[arg(long)]
152 depfile: Option<String>,
153 /// The default STYLE of code used to generate enums.
154 #[arg(long, value_name = "STYLE")]
155 default_enum_style: Option<EnumVariation>,
156 /// Mark any enum whose name matches REGEX as a set of bitfield flags.
157 #[arg(long, value_name = "REGEX")]
158 bitfield_enum: Vec<String>,
159 /// Mark any enum whose name matches REGEX as a newtype.
160 #[arg(long, value_name = "REGEX")]
161 newtype_enum: Vec<String>,
162 /// Mark any enum whose name matches REGEX as a global newtype.
163 #[arg(long, value_name = "REGEX")]
164 newtype_global_enum: Vec<String>,
165 /// Mark any enum whose name matches REGEX as a Rust enum.
166 #[arg(long, value_name = "REGEX")]
167 rustified_enum: Vec<String>,
168 /// Mark any enum whose name matches REGEX as a non-exhaustive Rust enum.
169 #[arg(long, value_name = "REGEX")]
170 rustified_non_exhaustive_enum: Vec<String>,
171 /// Mark any enum whose name matches REGEX as a series of constants.
172 #[arg(long, value_name = "REGEX")]
173 constified_enum: Vec<String>,
174 /// Mark any enum whose name matches REGEX as a module of constants.
175 #[arg(long, value_name = "REGEX")]
176 constified_enum_module: Vec<String>,
177 /// The default signed/unsigned TYPE for C macro constants.
178 #[arg(long, value_name = "TYPE")]
179 default_macro_constant_type: Option<MacroTypeVariation>,
180 /// The default STYLE of code used to generate typedefs.
181 #[arg(long, value_name = "STYLE")]
182 default_alias_style: Option<AliasVariation>,
183 /// Mark any typedef alias whose name matches REGEX to use normal type aliasing.
184 #[arg(long, value_name = "REGEX")]
185 normal_alias: Vec<String>,
186 /// Mark any typedef alias whose name matches REGEX to have a new type generated for it.
187 #[arg(long, value_name = "REGEX")]
188 new_type_alias: Vec<String>,
189 /// Mark any typedef alias whose name matches REGEX to have a new type with Deref and DerefMut to the inner type.
190 #[arg(long, value_name = "REGEX")]
191 new_type_alias_deref: Vec<String>,
192 /// The default STYLE of code used to generate unions with non-Copy members. Note that ManuallyDrop was first stabilized in Rust 1.20.0.
193 #[arg(long, value_name = "STYLE")]
194 default_non_copy_union_style: Option<NonCopyUnionStyle>,
195 /// Mark any union whose name matches REGEX and who has a non-Copy member to use a bindgen-generated wrapper for fields.
196 #[arg(long, value_name = "REGEX")]
197 bindgen_wrapper_union: Vec<String>,
198 /// Mark any union whose name matches REGEX and who has a non-Copy member to use ManuallyDrop (stabilized in Rust 1.20.0) for fields.
199 #[arg(long, value_name = "REGEX")]
200 manually_drop_union: Vec<String>,
201 /// Mark TYPE as hidden.
202 #[arg(long, value_name = "TYPE")]
203 blocklist_type: Vec<String>,
204 /// Mark FUNCTION as hidden.
205 #[arg(long, value_name = "FUNCTION")]
206 blocklist_function: Vec<String>,
207 /// Mark ITEM as hidden.
208 #[arg(long, value_name = "ITEM")]
209 blocklist_item: Vec<String>,
210 /// Mark FILE as hidden.
211 #[arg(long, value_name = "FILE")]
212 blocklist_file: Vec<String>,
213 /// Mark VAR as hidden.
214 #[arg(long, value_name = "VAR")]
215 blocklist_var: Vec<String>,
216 /// Avoid generating layout tests for any type.
217 #[arg(long)]
218 no_layout_tests: bool,
219 /// Avoid deriving Copy on any type.
220 #[arg(long)]
221 no_derive_copy: bool,
222 /// Avoid deriving Debug on any type.
223 #[arg(long)]
224 no_derive_debug: bool,
225 /// Avoid deriving Default on any type.
226 #[arg(long, hide = true)]
227 no_derive_default: bool,
228 /// Create a Debug implementation if it cannot be derived automatically.
229 #[arg(long)]
230 impl_debug: bool,
231 /// Create a PartialEq implementation if it cannot be derived automatically.
232 #[arg(long)]
233 impl_partialeq: bool,
234 /// Derive Default on any type.
235 #[arg(long)]
236 with_derive_default: bool,
237 /// Derive Hash on any type.
238 #[arg(long)]
239 with_derive_hash: bool,
240 /// Derive PartialEq on any type.
241 #[arg(long)]
242 with_derive_partialeq: bool,
243 /// Derive PartialOrd on any type.
244 #[arg(long)]
245 with_derive_partialord: bool,
246 /// Derive Eq on any type.
247 #[arg(long)]
248 with_derive_eq: bool,
249 /// Derive Ord on any type.
250 #[arg(long)]
251 with_derive_ord: bool,
252 /// Avoid including doc comments in the output, see: <https://github.com/rust-lang/rust-bindgen/issues/426>
253 #[arg(long)]
254 no_doc_comments: bool,
255 /// Disable allowlisting types recursively. This will cause bindgen to emit Rust code that won't compile! See the `bindgen::Builder::allowlist_recursively` method's documentation for details.
256 #[arg(long)]
257 no_recursive_allowlist: bool,
258 /// Use extern crate instead of use for objc.
259 #[arg(long)]
260 objc_extern_crate: bool,
261 /// Generate block signatures instead of void pointers.
262 #[arg(long)]
263 generate_block: bool,
264 /// Generate string constants as `&CStr` instead of `&[u8]`.
265 #[arg(long)]
266 generate_cstr: bool,
267 /// Use extern crate instead of use for block.
268 #[arg(long)]
269 block_extern_crate: bool,
270 /// Do not trust the libclang-provided mangling
271 #[arg(long)]
272 distrust_clang_mangling: bool,
273 /// Output bindings for builtin definitions, e.g. __builtin_va_list.
274 #[arg(long)]
275 builtins: bool,
276 /// Use the given PREFIX before raw types instead of ::std::os::raw.
277 #[arg(long, value_name = "PREFIX")]
278 ctypes_prefix: Option<String>,
279 /// Use the given PREFIX for anonymous fields.
280 #[arg(long, value_name = "PREFIX")]
281 anon_fields_prefix: Option<String>,
282 /// Time the different bindgen phases and print to stderr
283 #[arg(long)]
284 time_phases: bool,
285 /// Output the Clang AST for debugging purposes.
286 #[arg(long)]
287 emit_clang_ast: bool,
288 /// Output our internal IR for debugging purposes.
289 #[arg(long)]
290 emit_ir: bool,
291 /// Dump a graphviz dot file to PATH.
292 #[arg(long, value_name = "PATH")]
293 emit_ir_graphviz: Option<String>,
294 /// Enable support for C++ namespaces.
295 #[arg(long)]
296 enable_cxx_namespaces: bool,
297 /// Disable namespacing via mangling, causing bindgen to generate names like `Baz` instead of `foo_bar_Baz` for an input name `foo::bar::Baz`.
298 #[arg(long)]
299 disable_name_namespacing: bool,
300 /// Disable nested struct naming, causing bindgen to generate names like `bar` instead of `foo_bar` for a nested definition `struct foo { struct bar { } b; };`.
301 #[arg(long)]
302 disable_nested_struct_naming: bool,
303 /// Disable support for native Rust unions.
304 #[arg(long)]
305 disable_untagged_union: bool,
306 /// Suppress insertion of bindgen's version identifier into generated bindings.
307 #[arg(long)]
308 disable_header_comment: bool,
309 /// Do not generate bindings for functions or methods. This is useful when you only care about struct layouts.
310 #[arg(long)]
311 ignore_functions: bool,
312 /// Generate only given items, split by commas. Valid values are `functions`,`types`, `vars`, `methods`, `constructors` and `destructors`.
313 #[arg(long, value_parser = parse_codegen_config)]
314 generate: Option<CodegenConfig>,
315 /// Do not generate bindings for methods.
316 #[arg(long)]
317 ignore_methods: bool,
318 /// Do not automatically convert floats to f32/f64.
319 #[arg(long)]
320 no_convert_floats: bool,
321 /// Do not prepend the enum name to constant or newtype variants.
322 #[arg(long)]
323 no_prepend_enum_name: bool,
324 /// Do not try to detect default include paths
325 #[arg(long)]
326 no_include_path_detection: bool,
327 /// Try to fit macro constants into types smaller than u32/i32
328 #[arg(long)]
329 fit_macro_constant_types: bool,
330 /// Mark TYPE as opaque.
331 #[arg(long, value_name = "TYPE")]
332 opaque_type: Vec<String>,
333 /// Write Rust bindings to OUTPUT.
334 #[arg(long, short, value_name = "OUTPUT")]
335 output: Option<String>,
336 /// Add a raw line of Rust code at the beginning of output.
337 #[arg(long)]
338 raw_line: Vec<String>,
339 /// Add a RAW_LINE of Rust code to a given module with name MODULE_NAME.
340 #[arg(long, number_of_values = 2, value_names = ["MODULE_NAME", "RAW_LINE"])]
341 module_raw_line: Vec<String>,
342 #[arg(long, help = rust_target_help())]
343 rust_target: Option<RustTarget>,
344 #[arg(long, value_name = "EDITION", help = rust_edition_help())]
345 rust_edition: Option<RustEdition>,
346 /// Use types from Rust core instead of std.
347 #[arg(long)]
348 use_core: bool,
349 /// Conservatively generate inline namespaces to avoid name conflicts.
350 #[arg(long)]
351 conservative_inline_namespaces: bool,
352 /// Allowlist all the free-standing functions matching REGEX. Other non-allowlisted functions will not be generated.
353 #[arg(long, value_name = "REGEX")]
354 allowlist_function: Vec<String>,
355 /// Generate inline functions.
356 #[arg(long)]
357 generate_inline_functions: bool,
358 /// Only generate types matching REGEX. Other non-allowlisted types will not be generated.
359 #[arg(long, value_name = "REGEX")]
360 allowlist_type: Vec<String>,
361 /// Allowlist all the free-standing variables matching REGEX. Other non-allowlisted variables will not be generated.
362 #[arg(long, value_name = "REGEX")]
363 allowlist_var: Vec<String>,
364 /// Allowlist all contents of PATH.
365 #[arg(long, value_name = "PATH")]
366 allowlist_file: Vec<String>,
367 /// Allowlist all items matching REGEX. Other non-allowlisted items will not be generated.
368 #[arg(long, value_name = "REGEX")]
369 allowlist_item: Vec<String>,
370 /// Print verbose error messages.
371 #[arg(long)]
372 verbose: bool,
373 /// Preprocess and dump the input header files to disk. Useful when debugging bindgen, using C-Reduce, or when filing issues. The resulting file will be named something like `__bindgen.i` or `__bindgen.ii`.
374 #[arg(long)]
375 dump_preprocessed_input: bool,
376 /// Do not record matching items in the regex sets. This disables reporting of unused items.
377 #[arg(long)]
378 no_record_matches: bool,
379 /// Do not bind size_t as usize (useful on platforms where those types are incompatible).
380 #[arg(long = "no-size_t-is-usize")]
381 no_size_t_is_usize: bool,
382 /// Do not format the generated bindings with rustfmt. This option is deprecated, please use
383 /// `--formatter=none` instead.
384 #[arg(long)]
385 no_rustfmt_bindings: bool,
386 /// Which FORMATTER should be used for the bindings
387 #[arg(
388 long,
389 value_name = "FORMATTER",
390 conflicts_with = "no_rustfmt_bindings"
391 )]
392 formatter: Option<Formatter>,
393 /// The absolute PATH to the rustfmt configuration file. The configuration file will be used for formatting the bindings. This parameter sets `formatter` to `rustfmt`.
394 #[arg(long, value_name = "PATH", conflicts_with = "no_rustfmt_bindings", value_parser=parse_rustfmt_config_path)]
395 rustfmt_configuration_file: Option<PathBuf>,
396 /// Avoid deriving PartialEq for types matching REGEX.
397 #[arg(long, value_name = "REGEX")]
398 no_partialeq: Vec<String>,
399 /// Avoid deriving Copy and Clone for types matching REGEX.
400 #[arg(long, value_name = "REGEX")]
401 no_copy: Vec<String>,
402 /// Avoid deriving Debug for types matching REGEX.
403 #[arg(long, value_name = "REGEX")]
404 no_debug: Vec<String>,
405 /// Avoid deriving/implementing Default for types matching REGEX.
406 #[arg(long, value_name = "REGEX")]
407 no_default: Vec<String>,
408 /// Avoid deriving Hash for types matching REGEX.
409 #[arg(long, value_name = "REGEX")]
410 no_hash: Vec<String>,
411 /// Add `#[must_use]` annotation to types matching REGEX.
412 #[arg(long, value_name = "REGEX")]
413 must_use_type: Vec<String>,
414 /// Enables detecting unexposed attributes in functions (slow). Used to generate `#[must_use]` annotations.
415 #[arg(long)]
416 enable_function_attribute_detection: bool,
417 /// Use `*const [T; size]` instead of `*const T` for C arrays
418 #[arg(long)]
419 use_array_pointers_in_arguments: bool,
420 /// The NAME to be used in a #[link(wasm_import_module = ...)] statement
421 #[arg(long, value_name = "NAME")]
422 wasm_import_module_name: Option<String>,
423 /// Use dynamic loading mode with the given library NAME.
424 #[arg(long, value_name = "NAME")]
425 dynamic_loading: Option<String>,
426 /// Require successful linkage to all functions in the library.
427 #[arg(long)]
428 dynamic_link_require_all: bool,
429 /// Prefix the name of exported symbols.
430 #[arg(long)]
431 prefix_link_name: Option<String>,
432 /// Makes generated bindings `pub` only for items if the items are publicly accessible in C++.
433 #[arg(long)]
434 respect_cxx_access_specs: bool,
435 /// Always translate enum integer types to native Rust integer types.
436 #[arg(long)]
437 translate_enum_integer_types: bool,
438 /// Generate types with C style naming.
439 #[arg(long)]
440 c_naming: bool,
441 /// Always output explicit padding fields.
442 #[arg(long)]
443 explicit_padding: bool,
444 /// Always be specific about the 'receiver' of a virtual function.
445 #[arg(long)]
446 use_specific_virtual_function_receiver: bool,
447 /// Use distinct char16_t
448 #[arg(long)]
449 use_distinct_char16_t: bool,
450 /// Output C++ overloaded operators
451 #[arg(long)]
452 represent_cxx_operators: bool,
453 /// Enables generation of vtable functions.
454 #[arg(long)]
455 vtable_generation: bool,
456 /// Enables sorting of code generation in a predefined manner.
457 #[arg(long)]
458 sort_semantically: bool,
459 /// Deduplicates extern blocks.
460 #[arg(long)]
461 merge_extern_blocks: bool,
462 /// Overrides the ABI of functions matching REGEX. The OVERRIDE value must be of the shape REGEX=ABI where ABI can be one of C, stdcall, efiapi, fastcall, thiscall, aapcs, win64 or C-unwind<.>
463 #[arg(long, value_name = "OVERRIDE", value_parser = parse_abi_override)]
464 override_abi: Vec<(Abi, String)>,
465 /// Wrap unsafe operations in unsafe blocks.
466 #[arg(long)]
467 wrap_unsafe_ops: bool,
468 /// Enable fallback for clang macro parsing.
469 #[arg(long)]
470 clang_macro_fallback: bool,
471 /// Set path for temporary files generated by fallback for clang macro parsing.
472 #[arg(long)]
473 clang_macro_fallback_build_dir: Option<PathBuf>,
474 /// Use DSTs to represent structures with flexible array members.
475 #[arg(long)]
476 flexarray_dst: bool,
477 /// Derive custom traits on any kind of type. The CUSTOM value must be of the shape REGEX=DERIVE where DERIVE is a coma-separated list of derive macros.
478 #[arg(long, value_name = "CUSTOM", value_parser = parse_custom_derive)]
479 with_derive_custom: Vec<(Vec<String>, String)>,
480 /// Derive custom traits on a `struct`. The CUSTOM value must be of the shape REGEX=DERIVE where DERIVE is a coma-separated list of derive macros.
481 #[arg(long, value_name = "CUSTOM", value_parser = parse_custom_derive)]
482 with_derive_custom_struct: Vec<(Vec<String>, String)>,
483 /// Derive custom traits on an `enum`. The CUSTOM value must be of the shape REGEX=DERIVE where DERIVE is a coma-separated list of derive macros.
484 #[arg(long, value_name = "CUSTOM", value_parser = parse_custom_derive)]
485 with_derive_custom_enum: Vec<(Vec<String>, String)>,
486 /// Derive custom traits on a `union`. The CUSTOM value must be of the shape REGEX=DERIVE where DERIVE is a coma-separated list of derive macros.
487 #[arg(long, value_name = "CUSTOM", value_parser = parse_custom_derive)]
488 with_derive_custom_union: Vec<(Vec<String>, String)>,
489 /// Add custom attributes on any kind of type. The CUSTOM value must be of the shape REGEX=ATTRIBUTE where ATTRIBUTE is a coma-separated list of attributes.
490 #[arg(long, value_name = "CUSTOM", value_parser = parse_custom_attribute)]
491 with_attribute_custom: Vec<(Vec<String>, String)>,
492 /// Add custom attributes on a `struct`. The CUSTOM value must be of the shape REGEX=ATTRIBUTE where ATTRIBUTE is a coma-separated list of attributes.
493 #[arg(long, value_name = "CUSTOM", value_parser = parse_custom_attribute)]
494 with_attribute_custom_struct: Vec<(Vec<String>, String)>,
495 /// Add custom attributes on an `enum`. The CUSTOM value must be of the shape REGEX=ATTRIBUTE where ATTRIBUTE is a coma-separated list of attributes.
496 #[arg(long, value_name = "CUSTOM", value_parser = parse_custom_attribute)]
497 with_attribute_custom_enum: Vec<(Vec<String>, String)>,
498 /// Add custom attributes on a `union`. The CUSTOM value must be of the shape REGEX=ATTRIBUTE where ATTRIBUTE is a coma-separated list of attributes.
499 #[arg(long, value_name = "CUSTOM", value_parser = parse_custom_attribute)]
500 with_attribute_custom_union: Vec<(Vec<String>, String)>,
501 /// Generate wrappers for `static` and `static inline` functions.
502 #[arg(long)]
503 wrap_static_fns: bool,
504 /// Sets the PATH for the source file that must be created due to the presence of `static` and
505 /// `static inline` functions.
506 #[arg(long, value_name = "PATH")]
507 wrap_static_fns_path: Option<PathBuf>,
508 /// Sets the SUFFIX added to the extern wrapper functions generated for `static` and `static
509 /// inline` functions.
510 #[arg(long, value_name = "SUFFIX")]
511 wrap_static_fns_suffix: Option<String>,
512 /// Set the default VISIBILITY of fields, including bitfields and accessor methods for
513 /// bitfields. This flag is ignored if the `--respect-cxx-access-specs` flag is used.
514 #[arg(long, value_name = "VISIBILITY")]
515 default_visibility: Option<FieldVisibilityKind>,
516 /// Whether to generate C++ functions marked with "=delete" even though they
517 /// can't be called.
518 #[arg(long)]
519 generate_deleted_functions: bool,
520 /// Whether to generate C++ "pure virtual" functions even though they can't
521 /// be called.
522 #[arg(long)]
523 generate_pure_virtual_functions: bool,
524 /// Whether to generate C++ private functions even though they can't
525 /// be called.
526 #[arg(long)]
527 generate_private_functions: bool,
528 /// Whether to emit diagnostics or not.
529 #[cfg(feature = "experimental")]
530 #[arg(long, requires = "experimental")]
531 emit_diagnostics: bool,
532 /// Generates completions for the specified SHELL, sends them to `stdout` and exits.
533 #[arg(long, value_name = "SHELL")]
534 generate_shell_completions: Option<clap_complete::Shell>,
535 /// Enables experimental features.
536 #[arg(long)]
537 experimental: bool,
538 /// Prints the version, and exits
539 #[arg(short = 'V', long)]
540 version: bool,
541 /// Arguments to be passed straight through to clang.
542 clang_args: Vec<String>,
543 }
544
545 /// Construct a new [`Builder`](./struct.Builder.html) from command line flags.
546 pub fn builder_from_flags<I>(
547 args: I,
548 ) -> Result<(Builder, Box<dyn io::Write>, bool), io::Error>
549 where
550 I: Iterator<Item = String>,
551 {
552 let command = BindgenCommand::parse_from(args);
553
554 let BindgenCommand {
555 header,
556 depfile,
557 default_enum_style,
558 bitfield_enum,
559 newtype_enum,
560 newtype_global_enum,
561 rustified_enum,
562 rustified_non_exhaustive_enum,
563 constified_enum,
564 constified_enum_module,
565 default_macro_constant_type,
566 default_alias_style,
567 normal_alias,
568 new_type_alias,
569 new_type_alias_deref,
570 default_non_copy_union_style,
571 bindgen_wrapper_union,
572 manually_drop_union,
573 blocklist_type,
574 blocklist_function,
575 blocklist_item,
576 blocklist_file,
577 blocklist_var,
578 no_layout_tests,
579 no_derive_copy,
580 no_derive_debug,
581 no_derive_default,
582 impl_debug,
583 impl_partialeq,
584 with_derive_default,
585 with_derive_hash,
586 with_derive_partialeq,
587 with_derive_partialord,
588 with_derive_eq,
589 with_derive_ord,
590 no_doc_comments,
591 no_recursive_allowlist,
592 objc_extern_crate,
593 generate_block,
594 generate_cstr,
595 block_extern_crate,
596 distrust_clang_mangling,
597 builtins,
598 ctypes_prefix,
599 anon_fields_prefix,
600 time_phases,
601 emit_clang_ast,
602 emit_ir,
603 emit_ir_graphviz,
604 enable_cxx_namespaces,
605 disable_name_namespacing,
606 disable_nested_struct_naming,
607 disable_untagged_union,
608 disable_header_comment,
609 ignore_functions,
610 generate,
611 ignore_methods,
612 no_convert_floats,
613 no_prepend_enum_name,
614 no_include_path_detection,
615 fit_macro_constant_types,
616 opaque_type,
617 output,
618 raw_line,
619 module_raw_line,
620 rust_target,
621 rust_edition,
622 use_core,
623 conservative_inline_namespaces,
624 allowlist_function,
625 generate_inline_functions,
626 allowlist_type,
627 allowlist_var,
628 allowlist_file,
629 allowlist_item,
630 verbose,
631 dump_preprocessed_input,
632 no_record_matches,
633 no_size_t_is_usize,
634 no_rustfmt_bindings,
635 formatter,
636 rustfmt_configuration_file,
637 no_partialeq,
638 no_copy,
639 no_debug,
640 no_default,
641 no_hash,
642 must_use_type,
643 enable_function_attribute_detection,
644 use_array_pointers_in_arguments,
645 wasm_import_module_name,
646 dynamic_loading,
647 dynamic_link_require_all,
648 prefix_link_name,
649 respect_cxx_access_specs,
650 translate_enum_integer_types,
651 c_naming,
652 explicit_padding,
653 use_specific_virtual_function_receiver,
654 use_distinct_char16_t,
655 represent_cxx_operators,
656 vtable_generation,
657 sort_semantically,
658 merge_extern_blocks,
659 override_abi,
660 wrap_unsafe_ops,
661 clang_macro_fallback,
662 clang_macro_fallback_build_dir,
663 flexarray_dst,
664 with_derive_custom,
665 with_derive_custom_struct,
666 with_derive_custom_enum,
667 with_derive_custom_union,
668 with_attribute_custom,
669 with_attribute_custom_struct,
670 with_attribute_custom_enum,
671 with_attribute_custom_union,
672 wrap_static_fns,
673 wrap_static_fns_path,
674 wrap_static_fns_suffix,
675 default_visibility,
676 generate_deleted_functions,
677 generate_pure_virtual_functions,
678 generate_private_functions,
679 #[cfg(feature = "experimental")]
680 emit_diagnostics,
681 generate_shell_completions,
682 experimental: _,
683 version,
684 clang_args,
685 } = command;
686
687 if let Some(shell) = generate_shell_completions {
688 clap_complete::generate(
689 shell,
690 &mut BindgenCommand::command(),
691 "bindgen",
692 &mut io::stdout(),
693 );
694
695 exit(0)
696 }
697
698 if version {
699 println!(
700 "bindgen {}",
701 option_env!("CARGO_PKG_VERSION").unwrap_or("unknown")
702 );
703 if verbose {
704 println!("Clang: {}", crate::clang_version().full);
705 }
706
707 exit(0)
708 }
709
710 if header.is_none() {
711 return Err(io::Error::new(io::ErrorKind::Other, "Header not found"));
712 }
713
714 let mut builder = builder();
715
716 #[derive(Debug)]
717 struct PrefixLinkNameCallback {
718 prefix: String,
719 }
720
721 impl ParseCallbacks for PrefixLinkNameCallback {
722 fn generated_link_name_override(
723 &self,
724 item_info: ItemInfo<'_>,
725 ) -> Option<String> {
726 let mut prefix = self.prefix.clone();
727 prefix.push_str(item_info.name);
728 Some(prefix)
729 }
730 }
731
732 #[derive(Debug)]
733 struct CustomDeriveCallback {
734 derives: Vec<String>,
735 kind: Option<TypeKind>,
736 regex_set: RegexSet,
737 }
738
739 impl ParseCallbacks for CustomDeriveCallback {
740 fn cli_args(&self) -> Vec<String> {
741 let mut args = vec![];
742
743 let flag = match &self.kind {
744 None => "--with-derive-custom",
745 Some(TypeKind::Struct) => "--with-derive-custom-struct",
746 Some(TypeKind::Enum) => "--with-derive-custom-enum",
747 Some(TypeKind::Union) => "--with-derive-custom-union",
748 };
749
750 let derives = self.derives.join(",");
751
752 for item in self.regex_set.get_items() {
753 args.extend_from_slice(&[
754 flag.to_owned(),
755 format!("{item}={derives}"),
756 ]);
757 }
758
759 args
760 }
761
762 fn add_derives(&self, info: &DeriveInfo<'_>) -> Vec<String> {
763 if self.kind.map_or(true, |kind| kind == info.kind) &&
764 self.regex_set.matches(info.name)
765 {
766 return self.derives.clone();
767 }
768 vec![]
769 }
770 }
771
772 #[derive(Debug)]
773 struct CustomAttributeCallback {
774 attributes: Vec<String>,
775 kind: Option<TypeKind>,
776 regex_set: RegexSet,
777 }
778
779 impl ParseCallbacks for CustomAttributeCallback {
780 fn cli_args(&self) -> Vec<String> {
781 let mut args = vec![];
782
783 let flag = match &self.kind {
784 None => "--with-attribute-custom",
785 Some(TypeKind::Struct) => "--with-attribute-custom-struct",
786 Some(TypeKind::Enum) => "--with-attribute-custom-enum",
787 Some(TypeKind::Union) => "--with-attribute-custom-union",
788 };
789
790 let attributes = self.attributes.join(",");
791
792 for item in self.regex_set.get_items() {
793 args.extend_from_slice(&[
794 flag.to_owned(),
795 format!("{item}={attributes}"),
796 ]);
797 }
798
799 args
800 }
801
802 fn add_attributes(&self, info: &AttributeInfo<'_>) -> Vec<String> {
803 if self.kind.map_or(true, |kind| kind == info.kind) &&
804 self.regex_set.matches(info.name)
805 {
806 return self.attributes.clone();
807 }
808 vec![]
809 }
810 }
811
812 /// Macro used to apply CLI arguments to a builder.
813 ///
814 /// This is done by passing an identifier for each argument and a function to be applied over
815 /// the builder. For example:
816 /// ```rust,ignore
817 /// fn apply_arg(builder: Builder, arg_value: Value) -> Builder {
818 /// todo!()
819 /// }
820 ///
821 /// apply_args!(
822 /// builder {
823 /// arg => apply_arg,
824 /// }
825 /// );
826 /// ```
827 ///
828 /// If the identifier of the argument is the same as an already existing builder method then
829 /// you can omit the second part:
830 /// ```rust,ignore
831 /// apply_args!(
832 /// builder {
833 /// arg
834 /// }
835 /// );
836 /// ```
837 /// Which expands to the same code as:
838 /// ```rust,ignore
839 /// apply_args!(
840 /// builder {
841 /// arg => Builder::arg,
842 /// }
843 /// );
844 /// ```
845 macro_rules! apply_args {
846 ($builder:ident {}) => { $builder };
847 ($builder:ident {$arg:ident => $function:expr, $($token:tt)*}) => {
848 {
849 $builder = CliArg::apply($arg, $builder, $function);
850 apply_args!($builder {$($token)*})
851 }
852 };
853 ($builder:ident {$arg:ident, $($token:tt)*}) => {
854 {
855 $builder = CliArg::apply($arg, $builder, Builder::$arg);
856 apply_args!($builder {$($token)*})
857 }
858 }
859 }
860
861 builder = apply_args!(
862 builder {
863 header,
864 rust_target,
865 rust_edition,
866 default_enum_style,
867 bitfield_enum,
868 newtype_enum,
869 newtype_global_enum,
870 rustified_enum,
871 rustified_non_exhaustive_enum,
872 constified_enum,
873 constified_enum_module,
874 default_macro_constant_type,
875 default_alias_style,
876 normal_alias => Builder::type_alias,
877 new_type_alias,
878 new_type_alias_deref,
879 default_non_copy_union_style,
880 bindgen_wrapper_union,
881 manually_drop_union,
882 blocklist_type,
883 blocklist_function,
884 blocklist_item,
885 blocklist_file,
886 blocklist_var,
887 builtins => |b, _| b.emit_builtins(),
888 no_layout_tests => |b, _| b.layout_tests(false),
889 no_derive_copy => |b, _| b.derive_copy(false),
890 no_derive_debug => |b, _| b.derive_debug(false),
891 impl_debug,
892 impl_partialeq,
893 with_derive_default => Builder::derive_default,
894 with_derive_hash => Builder::derive_hash,
895 with_derive_partialeq => Builder::derive_partialeq,
896 with_derive_partialord => Builder::derive_partialord,
897 with_derive_eq => Builder::derive_eq,
898 with_derive_ord => Builder::derive_ord,
899 no_derive_default => |b, _| b.derive_default(false),
900 no_prepend_enum_name => |b, _| b.prepend_enum_name(false),
901 no_include_path_detection => |b, _| b.detect_include_paths(false),
902 fit_macro_constant_types => Builder::fit_macro_constants,
903 time_phases,
904 use_array_pointers_in_arguments => Builder::array_pointers_in_arguments,
905 wasm_import_module_name,
906 ctypes_prefix,
907 anon_fields_prefix,
908 generate => Builder::with_codegen_config,
909 emit_clang_ast => |b, _| b.emit_clang_ast(),
910 emit_ir => |b, _| b.emit_ir(),
911 emit_ir_graphviz,
912 enable_cxx_namespaces => |b, _| b.enable_cxx_namespaces(),
913 enable_function_attribute_detection => |b, _| b.enable_function_attribute_detection(),
914 disable_name_namespacing => |b, _| b.disable_name_namespacing(),
915 disable_nested_struct_naming => |b, _| b.disable_nested_struct_naming(),
916 disable_untagged_union => |b, _| b.disable_untagged_union(),
917 disable_header_comment => |b, _| b.disable_header_comment(),
918 ignore_functions => |b, _| b.ignore_functions(),
919 ignore_methods => |b, _| b.ignore_methods(),
920 no_convert_floats => |b, _| b.no_convert_floats(),
921 no_doc_comments => |b, _| b.generate_comments(false),
922 no_recursive_allowlist => |b, _| b.allowlist_recursively(false),
923 objc_extern_crate,
924 generate_block,
925 generate_cstr,
926 block_extern_crate,
927 opaque_type,
928 raw_line,
929 use_core => |b, _| b.use_core(),
930 distrust_clang_mangling => |b, _| b.trust_clang_mangling(false),
931 conservative_inline_namespaces => |b, _| b.conservative_inline_namespaces(),
932 generate_inline_functions,
933 allowlist_function,
934 allowlist_type,
935 allowlist_var,
936 allowlist_file,
937 allowlist_item,
938 clang_args => Builder::clang_arg,
939 no_record_matches => |b, _| b.record_matches(false),
940 no_size_t_is_usize => |b, _| b.size_t_is_usize(false),
941 no_rustfmt_bindings => |b, _| b.formatter(Formatter::None),
942 formatter,
943 no_partialeq,
944 no_copy,
945 no_debug,
946 no_default,
947 no_hash,
948 must_use_type,
949 dynamic_loading => Builder::dynamic_library_name,
950 dynamic_link_require_all,
951 prefix_link_name => |b, prefix| b.parse_callbacks(Box::new(PrefixLinkNameCallback { prefix })),
952 respect_cxx_access_specs,
953 translate_enum_integer_types,
954 c_naming,
955 explicit_padding,
956 use_specific_virtual_function_receiver,
957 use_distinct_char16_t,
958 represent_cxx_operators,
959 vtable_generation,
960 sort_semantically,
961 merge_extern_blocks,
962 override_abi => |b, (abi, regex)| b.override_abi(abi, regex),
963 wrap_unsafe_ops,
964 clang_macro_fallback => |b, _| b.clang_macro_fallback(),
965 clang_macro_fallback_build_dir,
966 flexarray_dst,
967 wrap_static_fns,
968 wrap_static_fns_path,
969 wrap_static_fns_suffix,
970 default_visibility,
971 generate_deleted_functions,
972 generate_pure_virtual_functions,
973 generate_private_functions,
974 }
975 );
976
977 let mut values = module_raw_line.into_iter();
978 while let Some(module) = values.next() {
979 let line = values.next().unwrap();
980 builder = builder.module_raw_line(module, line);
981 }
982
983 let output = if let Some(path) = &output {
984 let file = File::create(path)?;
985 if let Some(depfile) = depfile {
986 builder = builder.depfile(path, depfile);
987 }
988 Box::new(io::BufWriter::new(file)) as Box<dyn io::Write>
989 } else {
990 if let Some(depfile) = depfile {
991 builder = builder.depfile("-", depfile);
992 }
993 Box::new(io::BufWriter::new(io::stdout())) as Box<dyn io::Write>
994 };
995
996 if dump_preprocessed_input {
997 builder.dump_preprocessed_input()?;
998 }
999
1000 if let Some(path) = rustfmt_configuration_file {
1001 builder = builder.rustfmt_configuration_file(Some(path));
1002 }
1003
1004 for (custom_derives, kind, _name) in [
1005 (with_derive_custom, None, "--with-derive-custom"),
1006 (
1007 with_derive_custom_struct,
1008 Some(TypeKind::Struct),
1009 "--with-derive-custom-struct",
1010 ),
1011 (
1012 with_derive_custom_enum,
1013 Some(TypeKind::Enum),
1014 "--with-derive-custom-enum",
1015 ),
1016 (
1017 with_derive_custom_union,
1018 Some(TypeKind::Union),
1019 "--with-derive-custom-union",
1020 ),
1021 ] {
1022 #[cfg(feature = "experimental")]
1023 let name = emit_diagnostics.then_some(_name);
1024
1025 for (derives, regex) in custom_derives {
1026 let mut regex_set = RegexSet::default();
1027 regex_set.insert(regex);
1028
1029 #[cfg(feature = "experimental")]
1030 regex_set.build_with_diagnostics(false, name);
1031 #[cfg(not(feature = "experimental"))]
1032 regex_set.build(false);
1033
1034 builder = builder.parse_callbacks(Box::new(CustomDeriveCallback {
1035 derives,
1036 kind,
1037 regex_set,
1038 }));
1039 }
1040 }
1041
1042 for (custom_attributes, kind, _name) in [
1043 (with_attribute_custom, None, "--with-attribute-custom"),
1044 (
1045 with_attribute_custom_struct,
1046 Some(TypeKind::Struct),
1047 "--with-attribute-custom-struct",
1048 ),
1049 (
1050 with_attribute_custom_enum,
1051 Some(TypeKind::Enum),
1052 "--with-attribute-custom-enum",
1053 ),
1054 (
1055 with_attribute_custom_union,
1056 Some(TypeKind::Union),
1057 "--with-attribute-custom-union",
1058 ),
1059 ] {
1060 #[cfg(feature = "experimental")]
1061 let name = emit_diagnostics.then_some(_name);
1062
1063 for (attributes, regex) in custom_attributes {
1064 let mut regex_set = RegexSet::default();
1065 regex_set.insert(regex);
1066
1067 #[cfg(feature = "experimental")]
1068 regex_set.build_with_diagnostics(false, name);
1069 #[cfg(not(feature = "experimental"))]
1070 regex_set.build(false);
1071
1072 builder =
1073 builder.parse_callbacks(Box::new(CustomAttributeCallback {
1074 attributes,
1075 kind,
1076 regex_set,
1077 }));
1078 }
1079 }
1080
1081 #[cfg(feature = "experimental")]
1082 if emit_diagnostics {
1083 builder = builder.emit_diagnostics();
1084 }
1085
1086 Ok((builder, output, verbose))
1087 }
1088
1089 /// Trait for CLI arguments that can be applied to a [`Builder`].
1090 trait CliArg {
1091 /// The value of this argument.
1092 type Value;
1093
1094 /// Apply the current argument to the passed [`Builder`].
1095 fn apply(
1096 self,
1097 builder: Builder,
1098 f: impl Fn(Builder, Self::Value) -> Builder,
1099 ) -> Builder;
1100 }
1101
1102 /// Boolean arguments are applied when they evaluate to `true`.
1103 impl CliArg for bool {
1104 type Value = bool;
1105
1106 fn apply(
1107 self,
1108 mut builder: Builder,
1109 f: impl Fn(Builder, Self::Value) -> Builder,
1110 ) -> Builder {
1111 if self {
1112 builder = f(builder, self);
1113 }
1114
1115 builder
1116 }
1117 }
1118
1119 /// Optional arguments are applied when they are `Some`.
1120 impl<T> CliArg for Option<T> {
1121 type Value = T;
1122
1123 fn apply(
1124 self,
1125 mut builder: Builder,
1126 f: impl Fn(Builder, Self::Value) -> Builder,
1127 ) -> Builder {
1128 if let Some(value) = self {
1129 builder = f(builder, value);
1130 }
1131
1132 builder
1133 }
1134 }
1135
1136 /// Multiple valued arguments are applied once for each value.
1137 impl<T> CliArg for Vec<T> {
1138 type Value = T;
1139
1140 fn apply(
1141 self,
1142 mut builder: Builder,
1143 f: impl Fn(Builder, Self::Value) -> Builder,
1144 ) -> Builder {
1145 for value in self {
1146 builder = f(builder, value);
1147 }
1148
1149 builder
1150 }
1151 }