bindgen/options/mod.rs
1//! Declarations and setter methods for `bindgen` options.
2//!
3//! The main entry point of this module is the `options` macro.
4#[macro_use]
5mod helpers;
6mod as_args;
7#[cfg(feature = "__cli")]
8pub(crate) mod cli;
9
10use crate::callbacks::ParseCallbacks;
11use crate::codegen::{
12 AliasVariation, EnumVariation, MacroTypeVariation, NonCopyUnionStyle,
13};
14use crate::deps::DepfileSpec;
15use crate::features::{RustEdition, RustFeatures, RustTarget};
16use crate::regex_set::RegexSet;
17use crate::Abi;
18use crate::Builder;
19use crate::CodegenConfig;
20use crate::FieldVisibilityKind;
21use crate::Formatter;
22use crate::HashMap;
23use crate::DEFAULT_ANON_FIELDS_PREFIX;
24
25use std::env;
26use std::path::{Path, PathBuf};
27use std::rc::Rc;
28
29use as_args::AsArgs;
30use helpers::ignore;
31
32/// Macro used to generate the [`BindgenOptions`] type and the [`Builder`] setter methods for each
33/// one of the fields of `BindgenOptions`.
34///
35/// The input format of this macro resembles a `struct` pattern. Each field of the `BindgenOptions`
36/// type is declared by adding the name of the field and its type using the `name: type` syntax and
37/// a block of code with the following items:
38///
39/// - `default`: The default value for the field. If this item is omitted, `Default::default()` is
40/// used instead, meaning that the type of the field must implement `Default`.
41/// - `methods`: A block of code containing methods for the `Builder` type. These methods should be
42/// related to the field being declared.
43/// - `as_args`: This item declares how the field should be converted into a valid CLI argument for
44/// `bindgen` and is used in the [`Builder::command_line_flags`] method which is used to do a
45/// roundtrip test of the CLI args in the `bindgen-test` crate. This item can take one of the
46/// following:
47/// - A string literal with the flag if the type of the field implements the [`AsArgs`] trait.
48/// - A closure with the signature `|field, args: &mut Vec<String>| -> ()` that pushes arguments
49/// into the `args` buffer based on the value of the field. This is used if the field does not
50/// implement `AsArgs` or if the implementation of the trait is not logically correct for the
51/// option and a custom behavior must be taken into account.
52/// - The `ignore` literal, which does not emit any CLI arguments for this field. This is useful
53/// if the field cannot be used from the `bindgen` CLI.
54///
55/// As an example, this would be the declaration of a `bool` field called `be_fun` whose default
56/// value is `false` (the `Default` value for `bool`):
57/// ```rust,ignore
58/// be_fun: bool {
59/// methods: {
60/// /// Ask `bindgen` to be fun. This option is disabled by default.
61/// fn be_fun(mut self) -> Self {
62/// self.options.be_fun = true;
63/// self
64/// }
65/// },
66/// as_args: "--be-fun",
67/// }
68/// ```
69///
70/// However, we could also set the `be_fun` field to `true` by default and use a `--not-fun` flag
71/// instead. This means that we have to add the `default` item and use a closure in the `as_args`
72/// item:
73/// ```rust,ignore
74/// be_fun: bool {
75/// default: true,
76/// methods: {
77/// /// Ask `bindgen` to not be fun. `bindgen` is fun by default.
78/// fn not_fun(mut self) -> Self {
79/// self.options.be_fun = false;
80/// self
81/// }
82/// },
83/// as_args: |be_fun, args| (!be_fun).as_args(args, "--not-fun"),
84/// }
85/// ```
86/// More complex examples can be found in the sole invocation of this macro.
87macro_rules! options {
88 ($(
89 $(#[doc = $docs:literal])+
90 $field:ident: $ty:ty {
91 $(default: $default:expr,)?
92 methods: {$($methods_tokens:tt)*}$(,)?
93 as_args: $as_args:expr$(,)?
94 }$(,)?
95 )*) => {
96 #[derive(Debug, Clone)]
97 pub(crate) struct BindgenOptions {
98 $($(#[doc = $docs])* pub(crate) $field: $ty,)*
99 }
100
101 impl Default for BindgenOptions {
102 fn default() -> Self {
103 Self {
104 $($field: default!($($default)*),)*
105 }
106 }
107 }
108
109 impl Builder {
110 /// Generates the command line flags used to create this [`Builder`].
111 pub fn command_line_flags(&self) -> Vec<String> {
112 let mut args = vec![];
113
114 let headers = match self.options.input_headers.split_last() {
115 Some((header, headers)) => {
116 // The last input header is passed as an argument in the first position.
117 args.push(header.clone().into());
118 headers
119 },
120 None => &[]
121 };
122
123 $({
124 let func: fn(&$ty, &mut Vec<String>) = as_args!($as_args);
125 func(&self.options.$field, &mut args);
126 })*
127
128 // Add the `--experimental` flag if `bindgen` is built with the `experimental`
129 // feature.
130 if cfg!(feature = "experimental") {
131 args.push("--experimental".to_owned());
132 }
133
134 // Add all the clang arguments.
135 args.push("--".to_owned());
136
137 if !self.options.clang_args.is_empty() {
138 args.extend(self.options.clang_args.iter().map(|s| s.clone().into()));
139 }
140
141 // We need to pass all but the last header via the `-include` clang argument.
142 for header in headers {
143 args.push("-include".to_owned());
144 args.push(header.clone().into());
145 }
146
147 args
148 }
149
150 $($($methods_tokens)*)*
151 }
152 };
153}
154
155options! {
156 /// Whether to specify the type of a virtual function receiver
157 use_specific_virtual_function_receiver: bool {
158 methods: {
159 /// Normally, virtual functions have void* as their 'this' type.
160 /// If this flag is enabled, override that behavior to indicate a
161 /// pointer of the specific type.
162 /// Disabled by default.
163 pub fn use_specific_virtual_function_receiver(mut self, doit: bool) -> Builder {
164 self.options.use_specific_virtual_function_receiver = doit;
165 self
166 }
167 },
168 as_args: "--use-specific-virtual-function-receiver",
169 },
170
171 /// Whether we should distinguish between C++'s `char16_t` and `u16`.
172 /// The C++ type `char16_t` is its own special type; it's not a typedef
173 /// of some other integer (this differs from C).
174 /// As standard, bindgen represents C++ `char16_t` as `u16`.
175 /// Rust does not have a `std::os::raw::c_char16_t` type, and thus
176 /// we can't use a built-in Rust type in the generated bindings (and
177 /// nor would it be appropriate as it's a C++-specific type.)
178 /// But for some uses of bindgen, especially when downstream
179 /// post-processing occurs, it's important to distinguish `char16_t`
180 /// from normal `uint16_t`. When this option is enabled, bindgen
181 /// generates a fake type called `bindgen_cchar16_t`. Downstream
182 /// code post-processors should arrange to replace this with a
183 /// real type.
184 use_distinct_char16_t: bool {
185 methods: {
186 /// If this is true, denote `char16_t` as a separate type from `u16`.
187 /// Disabled by default.
188 pub fn use_distinct_char16_t(mut self, doit: bool) -> Builder {
189 self.options.use_distinct_char16_t = doit;
190 self
191 }
192 },
193 as_args: "--use-distinct-char16-t",
194 },
195 /// Whether we should output C++ overloaded operators. By itself,
196 /// this option is not sufficient to produce valid output, because
197 /// such operators will have names that are not acceptable Rust
198 /// names (for example `operator=`). If you use this option, you'll also
199 /// have to rename the resulting functions - for example by using
200 /// [`ParseCallbacks::generated_name_override`].
201 represent_cxx_operators: bool {
202 methods: {
203 /// If this is true, output existence of C++ overloaded operators.
204 /// At present, only operator= is noted.
205 /// Disabled by default.
206 pub fn represent_cxx_operators(mut self, doit: bool) -> Builder {
207 self.options.represent_cxx_operators = doit;
208 self
209 }
210 },
211 as_args: "--represent-cxx-operators",
212 },
213
214 /// Types that have been blocklisted and should not appear anywhere in the generated code.
215 blocklisted_types: RegexSet {
216 methods: {
217 regex_option! {
218 /// Do not generate any bindings for the given type.
219 ///
220 /// This option is not recursive, meaning that it will only block types whose names
221 /// explicitly match the argument of this method.
222 pub fn blocklist_type<T: AsRef<str>>(mut self, arg: T) -> Builder {
223 self.options.blocklisted_types.insert(arg);
224 self
225 }
226 }
227 },
228 as_args: "--blocklist-type",
229 },
230 /// Functions that have been blocklisted and should not appear in the generated code.
231 blocklisted_functions: RegexSet {
232 methods: {
233 regex_option! {
234 /// Do not generate any bindings for the given function.
235 ///
236 /// This option is not recursive, meaning that it will only block functions whose
237 /// names explicitly match the argument of this method.
238 pub fn blocklist_function<T: AsRef<str>>(mut self, arg: T) -> Builder {
239 self.options.blocklisted_functions.insert(arg);
240 self
241 }
242 }
243 },
244 as_args: "--blocklist-function",
245 },
246 /// Items that have been blocklisted and should not appear in the generated code.
247 blocklisted_items: RegexSet {
248 methods: {
249 regex_option! {
250 /// Do not generate any bindings for the given item, regardless of whether it is a
251 /// type, function, module, etc.
252 ///
253 /// This option is not recursive, meaning that it will only block items whose names
254 /// explicitly match the argument of this method.
255 pub fn blocklist_item<T: AsRef<str>>(mut self, arg: T) -> Builder {
256 self.options.blocklisted_items.insert(arg);
257 self
258 }
259 }
260 },
261 as_args: "--blocklist-item",
262 },
263 /// Files whose contents should be blocklisted and should not appear in the generated code.
264 blocklisted_files: RegexSet {
265 methods: {
266 regex_option! {
267 /// Do not generate any bindings for the contents of the given file, regardless of
268 /// whether the contents of the file are types, functions, modules, etc.
269 ///
270 /// This option is not recursive, meaning that it will only block files whose names
271 /// explicitly match the argument of this method.
272 ///
273 /// This method will use the argument to match the complete path of the file
274 /// instead of a section of it.
275 pub fn blocklist_file<T: AsRef<str>>(mut self, arg: T) -> Builder {
276 self.options.blocklisted_files.insert(arg);
277 self
278 }
279 }
280 },
281 as_args: "--blocklist-file",
282 },
283 /// Variables that have been blocklisted and should not appear in the generated code.
284 blocklisted_vars: RegexSet {
285 methods: {
286 regex_option! {
287 /// Do not generate any bindings for the given variable.
288 ///
289 /// This option is not recursive, meaning that it will only block variables whose
290 /// names explicitly match the argument of this method.
291 pub fn blocklist_var<T: AsRef<str>>(mut self, arg: T) -> Builder {
292 self.options.blocklisted_vars.insert(arg);
293 self
294 }
295 }
296 },
297 as_args: "--blocklist-var",
298 },
299 /// Types that should be treated as opaque structures in the generated code.
300 opaque_types: RegexSet {
301 methods: {
302 regex_option! {
303 /// Treat the given type as opaque in the generated bindings.
304 ///
305 /// Opaque in this context means that none of the generated bindings will contain
306 /// information about the inner representation of the type and the type itself will
307 /// be represented as a chunk of bytes with the alignment and size of the type.
308 pub fn opaque_type<T: AsRef<str>>(mut self, arg: T) -> Builder {
309 self.options.opaque_types.insert(arg);
310 self
311 }
312 }
313 },
314 as_args: "--opaque-type",
315 },
316 /// The explicit `rustfmt` path.
317 rustfmt_path: Option<PathBuf> {
318 methods: {
319 /// Set an explicit path to the `rustfmt` binary.
320 ///
321 /// This option only comes into effect if `rustfmt` is set to be the formatter used by
322 /// `bindgen`. Check the documentation of the [`Builder::formatter`] method for more
323 /// information.
324 pub fn with_rustfmt<P: Into<PathBuf>>(mut self, path: P) -> Self {
325 self.options.rustfmt_path = Some(path.into());
326 self
327 }
328 },
329 // This option cannot be set from the CLI.
330 as_args: ignore,
331 },
332 /// The path to which we should write a Makefile-syntax depfile (if any).
333 depfile: Option<DepfileSpec> {
334 methods: {
335 /// Add a depfile output which will be written alongside the generated bindings.
336 pub fn depfile<H: Into<String>, D: Into<PathBuf>>(
337 mut self,
338 output_module: H,
339 depfile: D,
340 ) -> Builder {
341 self.options.depfile = Some(DepfileSpec {
342 output_module: output_module.into(),
343 depfile_path: depfile.into(),
344 });
345 self
346 }
347 },
348 as_args: |depfile, args| {
349 if let Some(depfile) = depfile {
350 args.push("--depfile".into());
351 args.push(depfile.depfile_path.display().to_string());
352 }
353 },
354 },
355 /// Types that have been allowlisted and should appear in the generated code.
356 allowlisted_types: RegexSet {
357 methods: {
358 regex_option! {
359 /// Generate bindings for the given type.
360 ///
361 /// This option is transitive by default. Check the documentation of the
362 /// [`Builder::allowlist_recursively`] method for further information.
363 pub fn allowlist_type<T: AsRef<str>>(mut self, arg: T) -> Builder {
364 self.options.allowlisted_types.insert(arg);
365 self
366 }
367 }
368 },
369 as_args: "--allowlist-type",
370 },
371 /// Functions that have been allowlisted and should appear in the generated code.
372 allowlisted_functions: RegexSet {
373 methods: {
374 regex_option! {
375 /// Generate bindings for the given function.
376 ///
377 /// This option is transitive by default. Check the documentation of the
378 /// [`Builder::allowlist_recursively`] method for further information.
379 pub fn allowlist_function<T: AsRef<str>>(mut self, arg: T) -> Builder {
380 self.options.allowlisted_functions.insert(arg);
381 self
382 }
383 }
384 },
385 as_args: "--allowlist-function",
386 },
387 /// Variables that have been allowlisted and should appear in the generated code.
388 allowlisted_vars: RegexSet {
389 methods: {
390 regex_option! {
391 /// Generate bindings for the given variable.
392 ///
393 /// This option is transitive by default. Check the documentation of the
394 /// [`Builder::allowlist_recursively`] method for further information.
395 pub fn allowlist_var<T: AsRef<str>>(mut self, arg: T) -> Builder {
396 self.options.allowlisted_vars.insert(arg);
397 self
398 }
399 }
400 },
401 as_args: "--allowlist-var",
402 },
403 /// Files whose contents have been allowlisted and should appear in the generated code.
404 allowlisted_files: RegexSet {
405 methods: {
406 regex_option! {
407 /// Generate bindings for the content of the given file.
408 ///
409 /// This option is transitive by default. Check the documentation of the
410 /// [`Builder::allowlist_recursively`] method for further information.
411 ///
412 /// This method will use the argument to match the complete path of the file
413 /// instead of a section of it.
414 pub fn allowlist_file<T: AsRef<str>>(mut self, arg: T) -> Builder {
415 self.options.allowlisted_files.insert(arg);
416 self
417 }
418 }
419 },
420 as_args: "--allowlist-file",
421 },
422 /// Items that have been allowlisted and should appear in the generated code.
423 allowlisted_items: RegexSet {
424 methods: {
425 regex_option! {
426 /// Generate bindings for the given item, regardless of whether it is a type,
427 /// function, module, etc.
428 ///
429 /// This option is transitive by default. Check the documentation of the
430 /// [`Builder::allowlist_recursively`] method for further information.
431 pub fn allowlist_item<T: AsRef<str>>(mut self, arg: T) -> Builder {
432 self.options.allowlisted_items.insert(arg);
433 self
434 }
435 }
436 },
437 as_args: "--allowlist-item",
438 },
439 /// The default style of for generated `enum`s.
440 default_enum_style: EnumVariation {
441 methods: {
442 /// Set the default style for generated `enum`s.
443 ///
444 /// If this method is not called, the [`EnumVariation::Consts`] style will be used by
445 /// default.
446 ///
447 /// To set the style for individual `enum`s, use [`Builder::bitfield_enum`],
448 /// [`Builder::newtype_enum`], [`Builder::newtype_global_enum`],
449 /// [`Builder::rustified_enum`], [`Builder::rustified_non_exhaustive_enum`],
450 /// [`Builder::constified_enum_module`] or [`Builder::constified_enum`].
451 pub fn default_enum_style(
452 mut self,
453 arg: EnumVariation,
454 ) -> Builder {
455 self.options.default_enum_style = arg;
456 self
457 }
458 },
459 as_args: |variation, args| {
460 if *variation != Default::default() {
461 args.push("--default-enum-style".to_owned());
462 args.push(variation.to_string());
463 }
464 },
465 },
466 /// `enum`s marked as bitfield-like. This is, newtypes with bitwise operations.
467 bitfield_enums: RegexSet {
468 methods: {
469 regex_option! {
470 /// Mark the given `enum` as being bitfield-like.
471 ///
472 /// This is similar to the [`Builder::newtype_enum`] style, but with the bitwise
473 /// operators implemented.
474 pub fn bitfield_enum<T: AsRef<str>>(mut self, arg: T) -> Builder {
475 self.options.bitfield_enums.insert(arg);
476 self
477 }
478 }
479 },
480 as_args: "--bitfield-enum",
481 },
482 /// `enum`s marked as newtypes.
483 newtype_enums: RegexSet {
484 methods: {
485 regex_option! {
486 /// Mark the given `enum` as a newtype.
487 ///
488 /// This means that an integer newtype will be declared to represent the `enum`
489 /// type and its variants will be represented as constants inside of this type's
490 /// `impl` block.
491 pub fn newtype_enum<T: AsRef<str>>(mut self, arg: T) -> Builder {
492 self.options.newtype_enums.insert(arg);
493 self
494 }
495 }
496 },
497 as_args: "--newtype-enum",
498 },
499 /// `enum`s marked as global newtypes .
500 newtype_global_enums: RegexSet {
501 methods: {
502 regex_option! {
503 /// Mark the given `enum` as a global newtype.
504 ///
505 /// This is similar to the [`Builder::newtype_enum`] style, but the constants for
506 /// each variant are free constants instead of being declared inside an `impl`
507 /// block for the newtype.
508 pub fn newtype_global_enum<T: AsRef<str>>(mut self, arg: T) -> Builder {
509 self.options.newtype_global_enums.insert(arg);
510 self
511 }
512 }
513 },
514 as_args: "--newtype-global-enum",
515 },
516 /// `enum`s marked as Rust `enum`s.
517 rustified_enums: RegexSet {
518 methods: {
519 regex_option! {
520 /// Mark the given `enum` as a Rust `enum`.
521 ///
522 /// This means that each variant of the `enum` will be represented as a Rust `enum`
523 /// variant.
524 ///
525 /// **Use this with caution**, creating an instance of a Rust `enum` with an
526 /// invalid value will cause undefined behaviour. To avoid this, use the
527 /// [`Builder::newtype_enum`] style instead.
528 pub fn rustified_enum<T: AsRef<str>>(mut self, arg: T) -> Builder {
529 self.options.rustified_enums.insert(arg);
530 self
531 }
532 }
533 },
534 as_args: "--rustified-enum",
535 },
536 /// `enum`s marked as non-exhaustive Rust `enum`s.
537 rustified_non_exhaustive_enums: RegexSet {
538 methods: {
539 regex_option! {
540 /// Mark the given `enum` as a non-exhaustive Rust `enum`.
541 ///
542 /// This is similar to the [`Builder::rustified_enum`] style, but the `enum` is
543 /// tagged with the `#[non_exhaustive]` attribute.
544 ///
545 /// **Use this with caution**, creating an instance of a Rust `enum` with an
546 /// invalid value will cause undefined behaviour, even if it's tagged with
547 /// `#[non_exhaustive]`. To avoid this, use the [`Builder::newtype_enum`] style
548 /// instead.
549 pub fn rustified_non_exhaustive_enum<T: AsRef<str>>(mut self, arg: T) -> Builder {
550 self.options.rustified_non_exhaustive_enums.insert(arg);
551 self
552 }
553 }
554 },
555 as_args: "--rustified-non-exhaustive-enum",
556 },
557 /// `enum`s marked as modules of constants.
558 constified_enum_modules: RegexSet {
559 methods: {
560 regex_option! {
561 /// Mark the given `enum` as a module with a set of integer constants.
562 pub fn constified_enum_module<T: AsRef<str>>(mut self, arg: T) -> Builder {
563 self.options.constified_enum_modules.insert(arg);
564 self
565 }
566 }
567 },
568 as_args: "--constified-enum-module",
569 },
570 /// `enum`s marked as a set of constants.
571 constified_enums: RegexSet {
572 methods: {
573 regex_option! {
574 /// Mark the given `enum` as a set of integer constants.
575 ///
576 /// This is similar to the [`Builder::constified_enum_module`] style, but the
577 /// constants are generated in the current module instead of in a new module.
578 pub fn constified_enum<T: AsRef<str>>(mut self, arg: T) -> Builder {
579 self.options.constified_enums.insert(arg);
580 self
581 }
582 }
583 },
584 as_args: "--constified-enum",
585 },
586 /// The default type signedness for C macro constants.
587 default_macro_constant_type: MacroTypeVariation {
588 methods: {
589 /// Set the default type signedness to be used for macro constants.
590 ///
591 /// If this method is not called, [`MacroTypeVariation::Unsigned`] is used by default.
592 ///
593 /// To set the type for individual macro constants, use the
594 /// [`ParseCallbacks::int_macro`] method.
595 pub fn default_macro_constant_type(mut self, arg: MacroTypeVariation) -> Builder {
596 self.options.default_macro_constant_type = arg;
597 self
598 }
599
600 },
601 as_args: |variation, args| {
602 if *variation != Default::default() {
603 args.push("--default-macro-constant-type".to_owned());
604 args.push(variation.to_string());
605 }
606 },
607 },
608 /// The default style of code generation for `typedef`s.
609 default_alias_style: AliasVariation {
610 methods: {
611 /// Set the default style of code generation for `typedef`s.
612 ///
613 /// If this method is not called, the [`AliasVariation::TypeAlias`] style is used by
614 /// default.
615 ///
616 /// To set the style for individual `typedefs`s, use [`Builder::type_alias`],
617 /// [`Builder::new_type_alias`] or [`Builder::new_type_alias_deref`].
618 pub fn default_alias_style(
619 mut self,
620 arg: AliasVariation,
621 ) -> Builder {
622 self.options.default_alias_style = arg;
623 self
624 }
625 },
626 as_args: |variation, args| {
627 if *variation != Default::default() {
628 args.push("--default-alias-style".to_owned());
629 args.push(variation.to_string());
630 }
631 },
632 },
633 /// `typedef` patterns that will use regular type aliasing.
634 type_alias: RegexSet {
635 methods: {
636 regex_option! {
637 /// Mark the given `typedef` as a regular Rust `type` alias.
638 ///
639 /// This is the default behavior, meaning that this method only comes into effect
640 /// if a style different from [`AliasVariation::TypeAlias`] was passed to the
641 /// [`Builder::default_alias_style`] method.
642 pub fn type_alias<T: AsRef<str>>(mut self, arg: T) -> Builder {
643 self.options.type_alias.insert(arg);
644 self
645 }
646 }
647 },
648 as_args: "--type-alias",
649 },
650 /// `typedef` patterns that will be aliased by creating a newtype.
651 new_type_alias: RegexSet {
652 methods: {
653 regex_option! {
654 /// Mark the given `typedef` as a Rust newtype by having the aliased
655 /// type be wrapped in a `struct` with `#[repr(transparent)]`.
656 ///
657 /// This method can be used to enforce stricter type checking.
658 pub fn new_type_alias<T: AsRef<str>>(mut self, arg: T) -> Builder {
659 self.options.new_type_alias.insert(arg);
660 self
661 }
662 }
663 },
664 as_args: "--new-type-alias",
665 },
666 /// `typedef` patterns that will be wrapped in a newtype implementing `Deref` and `DerefMut`.
667 new_type_alias_deref: RegexSet {
668 methods: {
669 regex_option! {
670 /// Mark the given `typedef` to be generated as a newtype that can be dereferenced.
671 ///
672 /// This is similar to the [`Builder::new_type_alias`] style, but the newtype
673 /// implements `Deref` and `DerefMut` with the aliased type as a target.
674 pub fn new_type_alias_deref<T: AsRef<str>>(mut self, arg: T) -> Builder {
675 self.options.new_type_alias_deref.insert(arg);
676 self
677 }
678 }
679 },
680 as_args: "--new-type-alias-deref",
681 },
682 /// The default style of code to generate for `union`s containing non-`Copy` members.
683 default_non_copy_union_style: NonCopyUnionStyle {
684 methods: {
685 /// Set the default style of code to generate for `union`s with non-`Copy` members.
686 ///
687 /// If this method is not called, the [`NonCopyUnionStyle::BindgenWrapper`] style is
688 /// used by default.
689 ///
690 /// To set the style for individual `union`s, use [`Builder::bindgen_wrapper_union`] or
691 /// [`Builder::manually_drop_union`].
692 pub fn default_non_copy_union_style(mut self, arg: NonCopyUnionStyle) -> Self {
693 self.options.default_non_copy_union_style = arg;
694 self
695 }
696 },
697 as_args: |style, args| {
698 if *style != Default::default() {
699 args.push("--default-non-copy-union-style".to_owned());
700 args.push(style.to_string());
701 }
702 },
703 },
704 /// The patterns marking non-`Copy` `union`s as using the `bindgen` generated wrapper.
705 bindgen_wrapper_union: RegexSet {
706 methods: {
707 regex_option! {
708 /// Mark the given `union` to use a `bindgen`-generated wrapper for its members if at
709 /// least one them is not `Copy`.
710 ///
711 /// This is the default behavior, meaning that this method only comes into effect
712 /// if a style different from [`NonCopyUnionStyle::BindgenWrapper`] was passed to
713 /// the [`Builder::default_non_copy_union_style`] method.
714 pub fn bindgen_wrapper_union<T: AsRef<str>>(mut self, arg: T) -> Self {
715 self.options.bindgen_wrapper_union.insert(arg);
716 self
717 }
718 }
719 },
720 as_args: "--bindgen-wrapper-union",
721 },
722 /// The patterns marking non-`Copy` `union`s as using the `ManuallyDrop` wrapper.
723 manually_drop_union: RegexSet {
724 methods: {
725 regex_option! {
726 /// Mark the given `union` to use [`::core::mem::ManuallyDrop`] for its members if
727 /// at least one of them is not `Copy`.
728 ///
729 /// The `ManuallyDrop` type was stabilized in Rust 1.20.0, do not use this option
730 /// if your target version is lower than this.
731 pub fn manually_drop_union<T: AsRef<str>>(mut self, arg: T) -> Self {
732 self.options.manually_drop_union.insert(arg);
733 self
734 }
735 }
736
737 },
738 as_args: "--manually-drop-union",
739 },
740
741
742 /// Whether we should generate built-in definitions.
743 builtins: bool {
744 methods: {
745 /// Generate Rust bindings for built-in definitions (for example `__builtin_va_list`).
746 ///
747 /// Bindings for built-in definitions are not emitted by default.
748 pub fn emit_builtins(mut self) -> Builder {
749 self.options.builtins = true;
750 self
751 }
752 },
753 as_args: "--builtins",
754 },
755 /// Whether we should dump the Clang AST for debugging purposes.
756 emit_ast: bool {
757 methods: {
758 /// Emit the Clang AST to `stdout` for debugging purposes.
759 ///
760 /// The Clang AST is not emitted by default.
761 pub fn emit_clang_ast(mut self) -> Builder {
762 self.options.emit_ast = true;
763 self
764 }
765 },
766 as_args: "--emit-clang-ast",
767 },
768 /// Whether we should dump our IR for debugging purposes.
769 emit_ir: bool {
770 methods: {
771 /// Emit the `bindgen` internal representation to `stdout` for debugging purposes.
772 ///
773 /// This internal representation is not emitted by default.
774 pub fn emit_ir(mut self) -> Builder {
775 self.options.emit_ir = true;
776 self
777 }
778 },
779 as_args: "--emit-ir",
780 },
781 /// Output path for the `graphviz` DOT file.
782 emit_ir_graphviz: Option<String> {
783 methods: {
784 /// Set the path for the file where the`bindgen` internal representation will be
785 /// emitted as a graph using the `graphviz` DOT language.
786 ///
787 /// This graph representation is not emitted by default.
788 pub fn emit_ir_graphviz<T: Into<String>>(mut self, path: T) -> Builder {
789 let path = path.into();
790 self.options.emit_ir_graphviz = Some(path);
791 self
792 }
793 },
794 as_args: "--emit-ir-graphviz",
795 },
796
797 /// Whether we should emulate C++ namespaces with Rust modules.
798 enable_cxx_namespaces: bool {
799 methods: {
800 /// Emulate C++ namespaces using Rust modules in the generated bindings.
801 ///
802 /// C++ namespaces are not emulated by default.
803 pub fn enable_cxx_namespaces(mut self) -> Builder {
804 self.options.enable_cxx_namespaces = true;
805 self
806 }
807 },
808 as_args: "--enable-cxx-namespaces",
809 },
810 /// Whether we should try to find unexposed attributes in functions.
811 enable_function_attribute_detection: bool {
812 methods: {
813 /// Enable detecting function attributes on C functions.
814 ///
815 /// This enables the following features:
816 /// - Add `#[must_use]` attributes to Rust items whose C counterparts are marked as so.
817 /// This feature also requires that the Rust target version supports the attribute.
818 /// - Set `!` as the return type for Rust functions whose C counterparts are marked as
819 /// diverging.
820 ///
821 /// This option can be quite slow in some cases (check [#1465]), so it is disabled by
822 /// default.
823 ///
824 /// [#1465]: https://github.com/rust-lang/rust-bindgen/issues/1465
825 pub fn enable_function_attribute_detection(mut self) -> Self {
826 self.options.enable_function_attribute_detection = true;
827 self
828 }
829
830 },
831 as_args: "--enable-function-attribute-detection",
832 },
833 /// Whether we should avoid mangling names with namespaces.
834 disable_name_namespacing: bool {
835 methods: {
836 /// Disable name auto-namespacing.
837 ///
838 /// By default, `bindgen` mangles names like `foo::bar::Baz` to look like `foo_bar_Baz`
839 /// instead of just `Baz`. This method disables that behavior.
840 ///
841 /// Note that this does not change the names used for allowlisting and blocklisting,
842 /// which should still be mangled with the namespaces. Additionally, this option may
843 /// cause `bindgen` to generate duplicate names.
844 pub fn disable_name_namespacing(mut self) -> Builder {
845 self.options.disable_name_namespacing = true;
846 self
847 }
848 },
849 as_args: "--disable-name-namespacing",
850 },
851 /// Whether we should avoid generating nested `struct` names.
852 disable_nested_struct_naming: bool {
853 methods: {
854 /// Disable nested `struct` naming.
855 ///
856 /// The following `struct`s have different names for C and C++. In C, they are visible
857 /// as `foo` and `bar`. In C++, they are visible as `foo` and `foo::bar`.
858 ///
859 /// ```c
860 /// struct foo {
861 /// struct bar {
862 /// } b;
863 /// };
864 /// ```
865 ///
866 /// `bindgen` tries to avoid duplicate names by default, so it follows the C++ naming
867 /// convention and it generates `foo` and `foo_bar` instead of just `foo` and `bar`.
868 ///
869 /// This method disables this behavior and it is indented to be used only for headers
870 /// that were written in C.
871 pub fn disable_nested_struct_naming(mut self) -> Builder {
872 self.options.disable_nested_struct_naming = true;
873 self
874 }
875 },
876 as_args: "--disable-nested-struct-naming",
877 },
878 /// Whether we should avoid embedding version identifiers into source code.
879 disable_header_comment: bool {
880 methods: {
881 /// Do not insert the `bindgen` version identifier into the generated bindings.
882 ///
883 /// This identifier is inserted by default.
884 pub fn disable_header_comment(mut self) -> Self {
885 self.options.disable_header_comment = true;
886 self
887 }
888
889 },
890 as_args: "--disable-header-comment",
891 },
892 /// Whether we should generate layout tests for generated `struct`s.
893 layout_tests: bool {
894 default: true,
895 methods: {
896 /// Set whether layout tests should be generated.
897 ///
898 /// Layout tests are generated by default.
899 pub fn layout_tests(mut self, doit: bool) -> Self {
900 self.options.layout_tests = doit;
901 self
902 }
903 },
904 as_args: |value, args| (!value).as_args(args, "--no-layout-tests"),
905 },
906 /// Whether we should implement `Debug` for types that cannot derive it.
907 impl_debug: bool {
908 methods: {
909 /// Set whether `Debug` should be implemented for types that cannot derive it.
910 ///
911 /// This option is disabled by default.
912 pub fn impl_debug(mut self, doit: bool) -> Self {
913 self.options.impl_debug = doit;
914 self
915 }
916
917 },
918 as_args: "--impl-debug",
919 },
920 /// Whether we should implement `PartialEq` types that cannot derive it.
921 impl_partialeq: bool {
922 methods: {
923 /// Set whether `PartialEq` should be implemented for types that cannot derive it.
924 ///
925 /// This option is disabled by default.
926 pub fn impl_partialeq(mut self, doit: bool) -> Self {
927 self.options.impl_partialeq = doit;
928 self
929 }
930 },
931 as_args: "--impl-partialeq",
932 },
933 /// Whether we should derive `Copy` when possible.
934 derive_copy: bool {
935 default: true,
936 methods: {
937 /// Set whether the `Copy` trait should be derived when possible.
938 ///
939 /// `Copy` is derived by default.
940 pub fn derive_copy(mut self, doit: bool) -> Self {
941 self.options.derive_copy = doit;
942 self
943 }
944 },
945 as_args: |value, args| (!value).as_args(args, "--no-derive-copy"),
946 },
947
948 /// Whether we should derive `Debug` when possible.
949 derive_debug: bool {
950 default: true,
951 methods: {
952 /// Set whether the `Debug` trait should be derived when possible.
953 ///
954 /// The [`Builder::impl_debug`] method can be used to implement `Debug` for types that
955 /// cannot derive it.
956 ///
957 /// `Debug` is derived by default.
958 pub fn derive_debug(mut self, doit: bool) -> Self {
959 self.options.derive_debug = doit;
960 self
961 }
962 },
963 as_args: |value, args| (!value).as_args(args, "--no-derive-debug"),
964 },
965
966 /// Whether we should derive `Default` when possible.
967 derive_default: bool {
968 methods: {
969 /// Set whether the `Default` trait should be derived when possible.
970 ///
971 /// `Default` is not derived by default.
972 pub fn derive_default(mut self, doit: bool) -> Self {
973 self.options.derive_default = doit;
974 self
975 }
976 },
977 as_args: |&value, args| {
978 let arg = if value {
979 "--with-derive-default"
980 } else {
981 "--no-derive-default"
982 };
983
984 args.push(arg.to_owned());
985 },
986 },
987 /// Whether we should derive `Hash` when possible.
988 derive_hash: bool {
989 methods: {
990 /// Set whether the `Hash` trait should be derived when possible.
991 ///
992 /// `Hash` is not derived by default.
993 pub fn derive_hash(mut self, doit: bool) -> Self {
994 self.options.derive_hash = doit;
995 self
996 }
997 },
998 as_args: "--with-derive-hash",
999 },
1000 /// Whether we should derive `PartialOrd` when possible.
1001 derive_partialord: bool {
1002 methods: {
1003 /// Set whether the `PartialOrd` trait should be derived when possible.
1004 ///
1005 /// Take into account that `Ord` cannot be derived for a type that does not implement
1006 /// `PartialOrd`. For this reason, setting this method to `false` also sets
1007 /// automatically [`Builder::derive_ord`] to `false`.
1008 ///
1009 /// `PartialOrd` is not derived by default.
1010 pub fn derive_partialord(mut self, doit: bool) -> Self {
1011 self.options.derive_partialord = doit;
1012 if !doit {
1013 self.options.derive_ord = false;
1014 }
1015 self
1016 }
1017 },
1018 as_args: "--with-derive-partialord",
1019 },
1020 /// Whether we should derive `Ord` when possible.
1021 derive_ord: bool {
1022 methods: {
1023 /// Set whether the `Ord` trait should be derived when possible.
1024 ///
1025 /// Take into account that `Ord` cannot be derived for a type that does not implement
1026 /// `PartialOrd`. For this reason, the value set with this method will also be set
1027 /// automatically for [`Builder::derive_partialord`].
1028 ///
1029 /// `Ord` is not derived by default.
1030 pub fn derive_ord(mut self, doit: bool) -> Self {
1031 self.options.derive_ord = doit;
1032 self.options.derive_partialord = doit;
1033 self
1034 }
1035 },
1036 as_args: "--with-derive-ord",
1037 },
1038 /// Whether we should derive `PartialEq` when possible.
1039 derive_partialeq: bool {
1040 methods: {
1041 /// Set whether the `PartialEq` trait should be derived when possible.
1042 ///
1043 /// Take into account that `Eq` cannot be derived for a type that does not implement
1044 /// `PartialEq`. For this reason, setting this method to `false` also sets
1045 /// automatically [`Builder::derive_eq`] to `false`.
1046 ///
1047 /// The [`Builder::impl_partialeq`] method can be used to implement `PartialEq` for
1048 /// types that cannot derive it.
1049 ///
1050 /// `PartialEq` is not derived by default.
1051 pub fn derive_partialeq(mut self, doit: bool) -> Self {
1052 self.options.derive_partialeq = doit;
1053 if !doit {
1054 self.options.derive_eq = false;
1055 }
1056 self
1057 }
1058 },
1059 as_args: "--with-derive-partialeq",
1060 },
1061 /// Whether we should derive `Eq` when possible.
1062 derive_eq: bool {
1063 methods: {
1064 /// Set whether the `Eq` trait should be derived when possible.
1065 ///
1066 /// Take into account that `Eq` cannot be derived for a type that does not implement
1067 /// `PartialEq`. For this reason, the value set with this method will also be set
1068 /// automatically for [`Builder::derive_partialeq`].
1069 ///
1070 /// `Eq` is not derived by default.
1071 pub fn derive_eq(mut self, doit: bool) -> Self {
1072 self.options.derive_eq = doit;
1073 if doit {
1074 self.options.derive_partialeq = doit;
1075 }
1076 self
1077 }
1078 },
1079 as_args: "--with-derive-eq",
1080 },
1081 /// Whether we should use `core` instead of `std`.
1082 ///
1083 /// If this option is enabled and the Rust target version is greater than 1.64, the prefix for
1084 /// C platform-specific types will be `::core::ffi` instead of `::core::os::raw`.
1085 use_core: bool {
1086 methods: {
1087 /// Use `core` instead of `std` in the generated bindings.
1088 ///
1089 /// `std` is used by default.
1090 pub fn use_core(mut self) -> Builder {
1091 self.options.use_core = true;
1092 self
1093 }
1094
1095 },
1096 as_args: "--use-core",
1097 },
1098 /// An optional prefix for the C platform-specific types.
1099 ctypes_prefix: Option<String> {
1100 methods: {
1101 /// Use the given prefix for the C platform-specific types instead of `::std::os::raw`.
1102 ///
1103 /// Alternatively, the [`Builder::use_core`] method can be used to set the prefix to
1104 /// `::core::ffi` or `::core::os::raw`.
1105 pub fn ctypes_prefix<T: Into<String>>(mut self, prefix: T) -> Builder {
1106 self.options.ctypes_prefix = Some(prefix.into());
1107 self
1108 }
1109 },
1110 as_args: "--ctypes-prefix",
1111 },
1112 /// The prefix for anonymous fields.
1113 anon_fields_prefix: String {
1114 default: DEFAULT_ANON_FIELDS_PREFIX.into(),
1115 methods: {
1116 /// Use the given prefix for the anonymous fields.
1117 ///
1118 /// An anonymous field, is a field of a C/C++ type that does not have a name. For
1119 /// example, in the following C code:
1120 /// ```c
1121 /// struct integer {
1122 /// struct {
1123 /// int inner;
1124 /// };
1125 /// }
1126 /// ```
1127 ///
1128 /// The only field of the `integer` `struct` is an anonymous field and its Rust
1129 /// representation will be named using this prefix followed by an integer identifier.
1130 ///
1131 /// The default prefix is `__bindgen_anon_`.
1132 pub fn anon_fields_prefix<T: Into<String>>(mut self, prefix: T) -> Builder {
1133 self.options.anon_fields_prefix = prefix.into();
1134 self
1135 }
1136 },
1137 as_args: |prefix, args| {
1138 if prefix != DEFAULT_ANON_FIELDS_PREFIX {
1139 args.push("--anon-fields-prefix".to_owned());
1140 args.push(prefix.clone());
1141 }
1142 },
1143 },
1144 /// Whether to measure the time for each one of the `bindgen` phases.
1145 time_phases: bool {
1146 methods: {
1147 /// Set whether to measure the elapsed time for each one of the `bindgen` phases. This
1148 /// information is printed to `stderr`.
1149 ///
1150 /// The elapsed time is not measured by default.
1151 pub fn time_phases(mut self, doit: bool) -> Self {
1152 self.options.time_phases = doit;
1153 self
1154 }
1155 },
1156 as_args: "--time-phases",
1157 },
1158 /// Whether to convert C float types to `f32` and `f64`.
1159 convert_floats: bool {
1160 default: true,
1161 methods: {
1162 /// Avoid converting C float types to `f32` and `f64`.
1163 pub fn no_convert_floats(mut self) -> Self {
1164 self.options.convert_floats = false;
1165 self
1166 }
1167 },
1168 as_args: |value, args| (!value).as_args(args, "--no-convert-floats"),
1169 },
1170 /// The set of raw lines to be prepended to the top-level module of the generated Rust code.
1171 raw_lines: Vec<Box<str>> {
1172 methods: {
1173 /// Add a line of Rust code at the beginning of the generated bindings. The string is
1174 /// passed through without any modification.
1175 pub fn raw_line<T: Into<String>>(mut self, arg: T) -> Self {
1176 self.options.raw_lines.push(arg.into().into_boxed_str());
1177 self
1178 }
1179 },
1180 as_args: |raw_lines, args| {
1181 for line in raw_lines {
1182 args.push("--raw-line".to_owned());
1183 args.push(line.clone().into());
1184 }
1185 },
1186 },
1187 /// The set of raw lines to prepend to different modules.
1188 module_lines: HashMap<Box<str>, Vec<Box<str>>> {
1189 methods: {
1190 /// Add a given line to the beginning of a given module.
1191 ///
1192 /// This option only comes into effect if the [`Builder::enable_cxx_namespaces`] method
1193 /// is also being called.
1194 pub fn module_raw_line<T, U>(mut self, module: T, line: U) -> Self
1195 where
1196 T: Into<String>,
1197 U: Into<String>,
1198 {
1199 self.options
1200 .module_lines
1201 .entry(module.into().into_boxed_str())
1202 .or_default()
1203 .push(line.into().into_boxed_str());
1204 self
1205 }
1206 },
1207 as_args: |module_lines, args| {
1208 for (module, lines) in module_lines {
1209 for line in lines {
1210 args.push("--module-raw-line".to_owned());
1211 args.push(module.clone().into());
1212 args.push(line.clone().into());
1213 }
1214 }
1215 },
1216 },
1217 /// The input header files.
1218 input_headers: Vec<Box<str>> {
1219 methods: {
1220 /// Add an input C/C++ header to generate bindings for.
1221 ///
1222 /// This can be used to generate bindings for a single header:
1223 ///
1224 /// ```ignore
1225 /// let bindings = bindgen::Builder::default()
1226 /// .header("input.h")
1227 /// .generate()
1228 /// .unwrap();
1229 /// ```
1230 ///
1231 /// Or for multiple headers:
1232 ///
1233 /// ```ignore
1234 /// let bindings = bindgen::Builder::default()
1235 /// .header("first.h")
1236 /// .header("second.h")
1237 /// .header("third.h")
1238 /// .generate()
1239 /// .unwrap();
1240 /// ```
1241 pub fn header<T: Into<String>>(mut self, header: T) -> Builder {
1242 self.options.input_headers.push(header.into().into_boxed_str());
1243 self
1244 }
1245
1246 /// Add input C/C++ header(s) to generate bindings for.
1247 ///
1248 /// This can be used to generate bindings for a single header:
1249 ///
1250 /// ```ignore
1251 /// let bindings = bindgen::Builder::default()
1252 /// .headers(["input.h"])
1253 /// .generate()
1254 /// .unwrap();
1255 /// ```
1256 ///
1257 /// Or for multiple headers:
1258 ///
1259 /// ```ignore
1260 /// let bindings = bindgen::Builder::default()
1261 /// .headers(["first.h", "second.h", "third.h"])
1262 /// .generate()
1263 /// .unwrap();
1264 /// ```
1265 pub fn headers<I: IntoIterator>(mut self, headers: I) -> Builder
1266 where
1267 I::Item: Into<String>,
1268 {
1269 self.options
1270 .input_headers
1271 .extend(headers.into_iter().map(Into::into).map(Into::into));
1272 self
1273 }
1274 },
1275 // This field is handled specially inside the macro.
1276 as_args: ignore,
1277 },
1278 /// The set of arguments to be passed straight through to Clang.
1279 clang_args: Vec<Box<str>> {
1280 methods: {
1281 /// Add an argument to be passed straight through to Clang.
1282 pub fn clang_arg<T: Into<String>>(self, arg: T) -> Builder {
1283 self.clang_args([arg.into().into_boxed_str()])
1284 }
1285
1286 /// Add several arguments to be passed straight through to Clang.
1287 pub fn clang_args<I: IntoIterator>(mut self, args: I) -> Builder
1288 where
1289 I::Item: AsRef<str>,
1290 {
1291 for arg in args {
1292 self.options.clang_args.push(arg.as_ref().to_owned().into_boxed_str());
1293 }
1294 self
1295 }
1296 },
1297 // This field is handled specially inside the macro.
1298 as_args: ignore,
1299 },
1300 /// The set of arguments to be passed straight through to Clang for the macro fallback code.
1301 fallback_clang_args: Vec<Box<str>> {
1302 methods: {},
1303 as_args: ignore,
1304 },
1305 /// Tuples of unsaved file contents of the form (name, contents).
1306 input_header_contents: Vec<(Box<str>, Box<str>)> {
1307 methods: {
1308 /// Add `contents` as an input C/C++ header named `name`.
1309 ///
1310 /// This can be used to inject additional C/C++ code as an input without having to
1311 /// create additional header files.
1312 pub fn header_contents(mut self, name: &str, contents: &str) -> Builder {
1313 // Apparently clang relies on having virtual FS correspondent to
1314 // the real one, so we need absolute paths here
1315 let absolute_path = env::current_dir()
1316 .expect("Cannot retrieve current directory")
1317 .join(name)
1318 .to_str()
1319 .expect("Cannot convert current directory name to string")
1320 .into();
1321 self.options
1322 .input_header_contents
1323 .push((absolute_path, contents.into()));
1324 self
1325 }
1326 },
1327 // Header contents cannot be added from the CLI.
1328 as_args: ignore,
1329 },
1330 /// A user-provided visitor to allow customizing different kinds of situations.
1331 parse_callbacks: Vec<Rc<dyn ParseCallbacks>> {
1332 methods: {
1333 /// Add a new [`ParseCallbacks`] instance to configure types in different situations.
1334 ///
1335 /// This can also be used with [`CargoCallbacks`](struct@crate::CargoCallbacks) to emit
1336 /// `cargo:rerun-if-changed=...` for all `#include`d header files.
1337 pub fn parse_callbacks(mut self, cb: Box<dyn ParseCallbacks>) -> Self {
1338 self.options.parse_callbacks.push(Rc::from(cb));
1339 self
1340 }
1341 },
1342 as_args: |_callbacks, _args| {
1343 #[cfg(feature = "__cli")]
1344 for cb in _callbacks {
1345 _args.extend(cb.cli_args());
1346 }
1347 },
1348 },
1349 /// Which kind of items should we generate. We generate all of them by default.
1350 codegen_config: CodegenConfig {
1351 default: CodegenConfig::all(),
1352 methods: {
1353 /// Do not generate any functions.
1354 ///
1355 /// Functions are generated by default.
1356 pub fn ignore_functions(mut self) -> Builder {
1357 self.options.codegen_config.remove(CodegenConfig::FUNCTIONS);
1358 self
1359 }
1360
1361 /// Do not generate any methods.
1362 ///
1363 /// Methods are generated by default.
1364 pub fn ignore_methods(mut self) -> Builder {
1365 self.options.codegen_config.remove(CodegenConfig::METHODS);
1366 self
1367 }
1368
1369 /// Choose what to generate using a [`CodegenConfig`].
1370 ///
1371 /// This option overlaps with [`Builder::ignore_functions`] and
1372 /// [`Builder::ignore_methods`].
1373 ///
1374 /// All the items in `CodegenConfig` are generated by default.
1375 pub fn with_codegen_config(mut self, config: CodegenConfig) -> Self {
1376 self.options.codegen_config = config;
1377 self
1378 }
1379 },
1380 as_args: |codegen_config, args| {
1381 if !codegen_config.functions() {
1382 args.push("--ignore-functions".to_owned());
1383 }
1384
1385 args.push("--generate".to_owned());
1386
1387 //Temporary placeholder for the 4 options below.
1388 let mut options: Vec<String> = Vec::new();
1389 if codegen_config.functions() {
1390 options.push("functions".to_owned());
1391 }
1392
1393 if codegen_config.types() {
1394 options.push("types".to_owned());
1395 }
1396
1397 if codegen_config.vars() {
1398 options.push("vars".to_owned());
1399 }
1400
1401 if codegen_config.methods() {
1402 options.push("methods".to_owned());
1403 }
1404
1405 if codegen_config.constructors() {
1406 options.push("constructors".to_owned());
1407 }
1408
1409 if codegen_config.destructors() {
1410 options.push("destructors".to_owned());
1411 }
1412
1413 args.push(options.join(","));
1414
1415 if !codegen_config.methods() {
1416 args.push("--ignore-methods".to_owned());
1417 }
1418 },
1419 },
1420 /// Whether to treat inline namespaces conservatively.
1421 conservative_inline_namespaces: bool {
1422 methods: {
1423 /// Treat inline namespaces conservatively.
1424 ///
1425 /// This is tricky, because in C++ is technically legal to override an item
1426 /// defined in an inline namespace:
1427 ///
1428 /// ```cpp
1429 /// inline namespace foo {
1430 /// using Bar = int;
1431 /// }
1432 /// using Bar = long;
1433 /// ```
1434 ///
1435 /// Even though referencing `Bar` is a compiler error.
1436 ///
1437 /// We want to support this (arguably esoteric) use case, but we do not want to make
1438 /// the rest of `bindgen` users pay an usability penalty for that.
1439 ///
1440 /// To support this, we need to keep all the inline namespaces around, but then using
1441 /// `bindgen` becomes a bit more difficult, because you cannot reference paths like
1442 /// `std::string` (you'd need to use the proper inline namespace).
1443 ///
1444 /// We could complicate a lot of the logic to detect name collisions and, in the
1445 /// absence of collisions, generate a `pub use inline_ns::*` or something like that.
1446 ///
1447 /// That is probably something we can do to improve the usability of this option if we
1448 /// realize it is needed way more often. Our guess is that this extra logic is not
1449 /// going to be very useful.
1450 ///
1451 /// This option is disabled by default.
1452 pub fn conservative_inline_namespaces(mut self) -> Builder {
1453 self.options.conservative_inline_namespaces = true;
1454 self
1455 }
1456 },
1457 as_args: "--conservative-inline-namespaces",
1458 },
1459 /// Whether to keep documentation comments in the generated output.
1460 generate_comments: bool {
1461 default: true,
1462 methods: {
1463 /// Set whether the generated bindings should contain documentation comments.
1464 ///
1465 /// Documentation comments are included by default.
1466 ///
1467 /// Note that clang excludes comments from system headers by default, pass
1468 /// `"-fretain-comments-from-system-headers"` to the [`Builder::clang_arg`] method to
1469 /// include them.
1470 ///
1471 /// It is also possible to process all comments and not just documentation using the
1472 /// `"-fparse-all-comments"` flag. Check [these slides on clang comment parsing](
1473 /// https://llvm.org/devmtg/2012-11/Gribenko_CommentParsing.pdf) for more information
1474 /// and examples.
1475 pub fn generate_comments(mut self, doit: bool) -> Self {
1476 self.options.generate_comments = doit;
1477 self
1478 }
1479 },
1480 as_args: |value, args| (!value).as_args(args, "--no-doc-comments"),
1481 },
1482 /// Whether to generate [`NonNull`] pointers for C++ references.
1483 ///
1484 /// [`NonNull`]: core::ptr::NonNull
1485 generate_cxx_nonnull_references: bool {
1486 default: false,
1487 methods: {
1488 /// Generate `NonNull` pointers in place of raw pointers for C++
1489 /// references.
1490 ///
1491 /// This option is disabled by default:
1492 ///
1493 /// Enabling it erases information about constness in generated
1494 /// code, and `NonNull` is more cumbersome to use than raw pointers.
1495 pub fn generate_cxx_nonnull_references(mut self, doit: bool) -> Self {
1496 self.options.generate_cxx_nonnull_references = doit;
1497 self
1498 }
1499 },
1500 as_args: |value, args| value.as_args(args, "--nonnull-references"),
1501 },
1502 /// Whether to generate inline functions.
1503 generate_inline_functions: bool {
1504 methods: {
1505 /// Set whether to generate inline functions.
1506 ///
1507 /// This option is disabled by default.
1508 ///
1509 /// Note that they will usually not work. However you can use `-fkeep-inline-functions`
1510 /// or `-fno-inline-functions` if you are responsible of compiling the library to make
1511 /// them callable.
1512 ///
1513 /// Check the [`Builder::wrap_static_fns`] method for an alternative.
1514 pub fn generate_inline_functions(mut self, doit: bool) -> Self {
1515 self.options.generate_inline_functions = doit;
1516 self
1517 }
1518 },
1519 as_args: "--generate-inline-functions",
1520 },
1521 /// Whether to allowlist types recursively.
1522 allowlist_recursively: bool {
1523 default: true,
1524 methods: {
1525 /// Set whether to recursively allowlist items.
1526 ///
1527 /// Items are allowlisted recursively by default.
1528 ///
1529 /// Given that we have explicitly allowlisted the `initiate_dance_party` function in
1530 /// this C header:
1531 ///
1532 /// ```c
1533 /// typedef struct MoonBoots {
1534 /// int bouncy_level;
1535 /// } MoonBoots;
1536 ///
1537 /// void initiate_dance_party(MoonBoots* boots);
1538 /// ```
1539 ///
1540 /// We would normally generate bindings to both the `initiate_dance_party` function and
1541 /// the `MoonBoots` type that it transitively references. If `false` is passed to this
1542 /// method, `bindgen` will not emit bindings for anything except the explicitly
1543 /// allowlisted items, meaning that the definition for `MoonBoots` would not be
1544 /// generated. However, the `initiate_dance_party` function would still reference
1545 /// `MoonBoots`!
1546 ///
1547 /// **Disabling this feature will almost certainly cause `bindgen` to emit bindings
1548 /// that will not compile!** If you disable this feature, then it is *your*
1549 /// responsibility to provide definitions for every type that is referenced from an
1550 /// explicitly allowlisted item. One way to provide the missing definitions is by using
1551 /// the [`Builder::raw_line`] method, another would be to define them in Rust and then
1552 /// `include!(...)` the bindings immediately afterwards.
1553 pub fn allowlist_recursively(mut self, doit: bool) -> Self {
1554 self.options.allowlist_recursively = doit;
1555 self
1556 }
1557 },
1558 as_args: |value, args| (!value).as_args(args, "--no-recursive-allowlist"),
1559 },
1560 /// Whether to emit `#[macro_use] extern crate objc;` instead of `use objc;` in the prologue of
1561 /// the files generated from objective-c files.
1562 objc_extern_crate: bool {
1563 methods: {
1564 /// Emit `#[macro_use] extern crate objc;` instead of `use objc;` in the prologue of
1565 /// the files generated from objective-c files.
1566 ///
1567 /// `use objc;` is emitted by default.
1568 pub fn objc_extern_crate(mut self, doit: bool) -> Self {
1569 self.options.objc_extern_crate = doit;
1570 self
1571 }
1572 },
1573 as_args: "--objc-extern-crate",
1574 },
1575 /// Whether to generate proper block signatures instead of `void` pointers.
1576 generate_block: bool {
1577 methods: {
1578 /// Generate proper block signatures instead of `void` pointers.
1579 ///
1580 /// `void` pointers are used by default.
1581 pub fn generate_block(mut self, doit: bool) -> Self {
1582 self.options.generate_block = doit;
1583 self
1584 }
1585 },
1586 as_args: "--generate-block",
1587 },
1588 /// Whether to generate strings as `CStr`.
1589 generate_cstr: bool {
1590 methods: {
1591 /// Set whether string constants should be generated as `&CStr` instead of `&[u8]`.
1592 ///
1593 /// A minimum Rust target of 1.59 is required for this to have any effect as support
1594 /// for `CStr::from_bytes_with_nul_unchecked` in `const` contexts is needed.
1595 ///
1596 /// This option is disabled by default but will become enabled by default in a future
1597 /// release, so enabling this is recommended.
1598 pub fn generate_cstr(mut self, doit: bool) -> Self {
1599 self.options.generate_cstr = doit;
1600 self
1601 }
1602 },
1603 as_args: "--generate-cstr",
1604 },
1605 /// Whether to emit `#[macro_use] extern crate block;` instead of `use block;` in the prologue
1606 /// of the files generated from apple block files.
1607 block_extern_crate: bool {
1608 methods: {
1609 /// Emit `#[macro_use] extern crate block;` instead of `use block;` in the prologue of
1610 /// the files generated from apple block files.
1611 ///
1612 /// `use block;` is emitted by default.
1613 pub fn block_extern_crate(mut self, doit: bool) -> Self {
1614 self.options.block_extern_crate = doit;
1615 self
1616 }
1617 },
1618 as_args: "--block-extern-crate",
1619 },
1620 /// Whether to use the clang-provided name mangling.
1621 enable_mangling: bool {
1622 default: true,
1623 methods: {
1624 /// Set whether to use the clang-provided name mangling. This is probably needed for
1625 /// C++ features.
1626 ///
1627 /// The mangling provided by clang is used by default.
1628 ///
1629 /// We allow disabling this option because some old `libclang` versions seem to return
1630 /// incorrect results in some cases for non-mangled functions, check [#528] for more
1631 /// information.
1632 ///
1633 /// [#528]: https://github.com/rust-lang/rust-bindgen/issues/528
1634 pub fn trust_clang_mangling(mut self, doit: bool) -> Self {
1635 self.options.enable_mangling = doit;
1636 self
1637 }
1638
1639 },
1640 as_args: |value, args| (!value).as_args(args, "--distrust-clang-mangling"),
1641 },
1642 /// Whether to detect include paths using `clang_sys`.
1643 detect_include_paths: bool {
1644 default: true,
1645 methods: {
1646 /// Set whether to detect include paths using `clang_sys`.
1647 ///
1648 /// `clang_sys` is used to detect include paths by default.
1649 pub fn detect_include_paths(mut self, doit: bool) -> Self {
1650 self.options.detect_include_paths = doit;
1651 self
1652 }
1653 },
1654 as_args: |value, args| (!value).as_args(args, "--no-include-path-detection"),
1655 },
1656 /// Whether we should try to fit macro constants into types smaller than `u32` and `i32`.
1657 fit_macro_constants: bool {
1658 methods: {
1659 /// Set whether `bindgen` should try to fit macro constants into types smaller than `u32`
1660 /// and `i32`.
1661 ///
1662 /// This option is disabled by default.
1663 pub fn fit_macro_constants(mut self, doit: bool) -> Self {
1664 self.options.fit_macro_constants = doit;
1665 self
1666 }
1667 },
1668 as_args: "--fit-macro-constant-types",
1669 },
1670 /// Whether to prepend the `enum` name to constant or newtype variants.
1671 prepend_enum_name: bool {
1672 default: true,
1673 methods: {
1674 /// Set whether to prepend the `enum` name to constant or newtype variants.
1675 ///
1676 /// The `enum` name is prepended by default.
1677 pub fn prepend_enum_name(mut self, doit: bool) -> Self {
1678 self.options.prepend_enum_name = doit;
1679 self
1680 }
1681 },
1682 as_args: |value, args| (!value).as_args(args, "--no-prepend-enum-name"),
1683 },
1684 /// Version of the Rust compiler to target.
1685 rust_target: RustTarget {
1686 methods: {
1687 /// Specify the Rust target version.
1688 ///
1689 /// The default target is the latest stable Rust version.
1690 pub fn rust_target(mut self, rust_target: RustTarget) -> Self {
1691 self.options.set_rust_target(rust_target);
1692 self
1693 }
1694 },
1695 as_args: |rust_target, args| {
1696 args.push("--rust-target".to_owned());
1697 args.push(rust_target.to_string());
1698 },
1699 },
1700 /// The Rust edition to use for code generation.
1701 rust_edition: Option<RustEdition> {
1702 methods: {
1703 /// Specify the Rust target edition.
1704 ///
1705 /// The default edition is the latest edition supported by the chosen Rust target.
1706 pub fn rust_edition(mut self, rust_edition: RustEdition) -> Self {
1707 self.options.rust_edition = Some(rust_edition);
1708 self
1709 }
1710 }
1711 as_args: |edition, args| {
1712 if let Some(edition) = edition {
1713 args.push("--rust-edition".to_owned());
1714 args.push(edition.to_string());
1715 }
1716 },
1717 },
1718 /// Features to be enabled. They are derived from `rust_target`.
1719 rust_features: RustFeatures {
1720 methods: {},
1721 // This field cannot be set from the CLI,
1722 as_args: ignore,
1723 },
1724 /// Enable support for native Rust unions if they are supported.
1725 untagged_union: bool {
1726 default: true,
1727 methods: {
1728 /// Disable support for native Rust unions, if supported.
1729 ///
1730 /// The default value of this option is set based on the value passed to
1731 /// [`Builder::rust_target`].
1732 pub fn disable_untagged_union(mut self) -> Self {
1733 self.options.untagged_union = false;
1734 self
1735 }
1736 }
1737 as_args: |value, args| (!value).as_args(args, "--disable-untagged-union"),
1738 },
1739 /// Whether we should record which items in the regex sets did match any C items.
1740 record_matches: bool {
1741 default: true,
1742 methods: {
1743 /// Set whether we should record which items in our regex sets did match any C items.
1744 ///
1745 /// Matches are recorded by default.
1746 pub fn record_matches(mut self, doit: bool) -> Self {
1747 self.options.record_matches = doit;
1748 self
1749 }
1750
1751 },
1752 as_args: |value, args| (!value).as_args(args, "--no-record-matches"),
1753 },
1754 /// Whether `size_t` should be translated to `usize` automatically.
1755 size_t_is_usize: bool {
1756 default: true,
1757 methods: {
1758 /// Set whether `size_t` should be translated to `usize`.
1759 ///
1760 /// If `size_t` is translated to `usize`, type definitions for `size_t` will not be
1761 /// emitted.
1762 ///
1763 /// `size_t` is translated to `usize` by default.
1764 pub fn size_t_is_usize(mut self, is: bool) -> Self {
1765 self.options.size_t_is_usize = is;
1766 self
1767 }
1768 },
1769 as_args: |value, args| (!value).as_args(args, "--no-size_t-is-usize"),
1770 },
1771 /// The tool that should be used to format the generated bindings.
1772 formatter: Formatter {
1773 methods: {
1774 /// Set whether `rustfmt` should be used to format the generated bindings.
1775 ///
1776 /// `rustfmt` is used by default.
1777 ///
1778 /// This method overlaps in functionality with the more general [`Builder::formatter`].
1779 /// Thus, the latter should be preferred.
1780 #[deprecated]
1781 pub fn rustfmt_bindings(mut self, doit: bool) -> Self {
1782 self.options.formatter = if doit {
1783 Formatter::Rustfmt
1784 } else {
1785 Formatter::None
1786 };
1787 self
1788 }
1789
1790 /// Set which tool should be used to format the generated bindings.
1791 ///
1792 /// The default formatter is [`Formatter::Rustfmt`].
1793 ///
1794 /// To be able to use `prettyplease` as a formatter, the `"prettyplease"` feature for
1795 /// `bindgen` must be enabled in the Cargo manifest.
1796 pub fn formatter(mut self, formatter: Formatter) -> Self {
1797 self.options.formatter = formatter;
1798 self
1799 }
1800 },
1801 as_args: |formatter, args| {
1802 if *formatter != Default::default() {
1803 args.push("--formatter".to_owned());
1804 args.push(formatter.to_string());
1805 }
1806 },
1807 },
1808 /// The absolute path to the `rustfmt` configuration file.
1809 rustfmt_configuration_file: Option<PathBuf> {
1810 methods: {
1811 /// Set the absolute path to the `rustfmt` configuration file.
1812 ///
1813 /// The default `rustfmt` options are used if `None` is passed to this method or if
1814 /// this method is not called at all.
1815 ///
1816 /// Calling this method will set the [`Builder::rustfmt_bindings`] option to `true`
1817 /// and the [`Builder::formatter`] option to [`Formatter::Rustfmt`].
1818 pub fn rustfmt_configuration_file(mut self, path: Option<PathBuf>) -> Self {
1819 self = self.formatter(Formatter::Rustfmt);
1820 self.options.rustfmt_configuration_file = path;
1821 self
1822 }
1823 },
1824 as_args: "--rustfmt-configuration-file",
1825 },
1826 /// Types that should not derive `PartialEq`.
1827 no_partialeq_types: RegexSet {
1828 methods: {
1829 regex_option! {
1830 /// Do not derive `PartialEq` for a given type.
1831 pub fn no_partialeq<T: Into<String>>(mut self, arg: T) -> Builder {
1832 self.options.no_partialeq_types.insert(arg.into());
1833 self
1834 }
1835 }
1836 },
1837 as_args: "--no-partialeq",
1838 },
1839 /// Types that should not derive `Copy`.
1840 no_copy_types: RegexSet {
1841 methods: {
1842 regex_option! {
1843 /// Do not derive `Copy` and `Clone` for a given type.
1844 pub fn no_copy<T: Into<String>>(mut self, arg: T) -> Self {
1845 self.options.no_copy_types.insert(arg.into());
1846 self
1847 }
1848 }
1849 },
1850 as_args: "--no-copy",
1851 },
1852 /// Types that should not derive `Debug`.
1853 no_debug_types: RegexSet {
1854 methods: {
1855 regex_option! {
1856 /// Do not derive `Debug` for a given type.
1857 pub fn no_debug<T: Into<String>>(mut self, arg: T) -> Self {
1858 self.options.no_debug_types.insert(arg.into());
1859 self
1860 }
1861 }
1862 },
1863 as_args: "--no-debug",
1864 },
1865 /// Types that should not derive or implement `Default`.
1866 no_default_types: RegexSet {
1867 methods: {
1868 regex_option! {
1869 /// Do not derive or implement `Default` for a given type.
1870 pub fn no_default<T: Into<String>>(mut self, arg: T) -> Self {
1871 self.options.no_default_types.insert(arg.into());
1872 self
1873 }
1874 }
1875 },
1876 as_args: "--no-default",
1877 },
1878 /// Types that should not derive `Hash`.
1879 no_hash_types: RegexSet {
1880 methods: {
1881 regex_option! {
1882 /// Do not derive `Hash` for a given type.
1883 pub fn no_hash<T: Into<String>>(mut self, arg: T) -> Builder {
1884 self.options.no_hash_types.insert(arg.into());
1885 self
1886 }
1887 }
1888 },
1889 as_args: "--no-hash",
1890 },
1891 /// Types that should be annotated with `#[must_use]`.
1892 must_use_types: RegexSet {
1893 methods: {
1894 regex_option! {
1895 /// Annotate the given type with the `#[must_use]` attribute.
1896 pub fn must_use_type<T: Into<String>>(mut self, arg: T) -> Builder {
1897 self.options.must_use_types.insert(arg.into());
1898 self
1899 }
1900 }
1901 },
1902 as_args: "--must-use-type",
1903 },
1904 /// Whether C arrays should be regular pointers in rust or array pointers
1905 array_pointers_in_arguments: bool {
1906 methods: {
1907 /// Translate arrays `T arr[size]` into array pointers `*mut [T; size]` instead of
1908 /// translating them as `*mut T` which is the default.
1909 ///
1910 /// The same is done for `*const` pointers.
1911 pub fn array_pointers_in_arguments(mut self, doit: bool) -> Self {
1912 self.options.array_pointers_in_arguments = doit;
1913 self
1914 }
1915
1916 },
1917 as_args: "--use-array-pointers-in-arguments",
1918 },
1919 /// Attributes to add to all `extern` blocks.
1920 extern_fn_block_attrs: Vec<String> {
1921 methods: {
1922 /// Add an attribute to all the `extern` blocks generated by `bindgen`.
1923 ///
1924 /// This can be used to add attributes such as `#[link(...)]` to all
1925 /// the `extern` blocks.
1926 pub fn extern_fn_block_attrs<T: Into<String>>(mut self, attr: T) -> Self {
1927 self.options.extern_fn_block_attrs.push(attr.into());
1928 self
1929 }
1930 },
1931 as_args: |attrs, args| {
1932 for attr in attrs {
1933 args.push("--extern-fn-block-attrs".to_owned());
1934 args.push(attr.clone());
1935 }
1936 },
1937 },
1938 /// The name of the `wasm_import_module`.
1939 wasm_import_module_name: Option<String> {
1940 methods: {
1941 /// Adds the `#[link(wasm_import_module = import_name)]` attribute to all the `extern`
1942 /// blocks generated by `bindgen`.
1943 ///
1944 /// This attribute is not added by default.
1945 pub fn wasm_import_module_name<T: Into<String>>(
1946 mut self,
1947 import_name: T,
1948 ) -> Self {
1949 self.options.extern_fn_block_attrs.push(format!(
1950 "#[link(wasm_import_module = \"{}\")]", import_name.into()
1951 ));
1952 self
1953 }
1954 },
1955 as_args: "--wasm-import-module-name",
1956 },
1957 /// The name of the dynamic library (if we are generating bindings for a shared library).
1958 dynamic_library_name: Option<String> {
1959 methods: {
1960 /// Generate bindings for a shared library with the given name.
1961 ///
1962 /// This option is disabled by default.
1963 pub fn dynamic_library_name<T: Into<String>>(
1964 mut self,
1965 dynamic_library_name: T,
1966 ) -> Self {
1967 self.options.dynamic_library_name = Some(dynamic_library_name.into());
1968 self
1969 }
1970 },
1971 as_args: "--dynamic-loading",
1972 },
1973 /// Whether to require successful linkage for all routines in a shared library.
1974 dynamic_link_require_all: bool {
1975 methods: {
1976 /// Set whether to require successful linkage for all routines in a shared library.
1977 /// This allows us to optimize function calls by being able to safely assume function
1978 /// pointers are valid.
1979 ///
1980 /// This option only comes into effect if the [`Builder::dynamic_library_name`] option
1981 /// is set.
1982 ///
1983 /// This option is disabled by default.
1984 pub fn dynamic_link_require_all(mut self, req: bool) -> Self {
1985 self.options.dynamic_link_require_all = req;
1986 self
1987 }
1988 },
1989 as_args: "--dynamic-link-require-all",
1990 },
1991 /// Whether to only make generated bindings `pub` if the items would be publicly accessible by
1992 /// C++.
1993 respect_cxx_access_specs: bool {
1994 methods: {
1995 /// Set whether to respect the C++ access specifications.
1996 ///
1997 /// Passing `true` to this method will set the visibility of the generated Rust items
1998 /// as `pub` only if the corresponding C++ items are publicly accessible instead of
1999 /// marking all the items as public, which is the default.
2000 pub fn respect_cxx_access_specs(mut self, doit: bool) -> Self {
2001 self.options.respect_cxx_access_specs = doit;
2002 self
2003 }
2004
2005 },
2006 as_args: "--respect-cxx-access-specs",
2007 },
2008 /// Whether to translate `enum` integer types to native Rust integer types.
2009 translate_enum_integer_types: bool {
2010 methods: {
2011 /// Set whether to always translate `enum` integer types to native Rust integer types.
2012 ///
2013 /// Passing `true` to this method will result in `enum`s having types such as `u32` and
2014 /// `i16` instead of `c_uint` and `c_short` which is the default. The `#[repr]` types
2015 /// of Rust `enum`s are always translated to Rust integer types.
2016 pub fn translate_enum_integer_types(mut self, doit: bool) -> Self {
2017 self.options.translate_enum_integer_types = doit;
2018 self
2019 }
2020 },
2021 as_args: "--translate-enum-integer-types",
2022 },
2023 /// Whether to generate types with C style naming.
2024 c_naming: bool {
2025 methods: {
2026 /// Set whether to generate types with C style naming.
2027 ///
2028 /// Passing `true` to this method will add prefixes to the generated type names. For
2029 /// example, instead of a `struct` with name `A` we will generate a `struct` with
2030 /// `struct_A`. Currently applies to `struct`s, `union`s, and `enum`s.
2031 pub fn c_naming(mut self, doit: bool) -> Self {
2032 self.options.c_naming = doit;
2033 self
2034 }
2035 },
2036 as_args: "--c-naming",
2037 },
2038 /// Whether to always emit explicit padding fields.
2039 force_explicit_padding: bool {
2040 methods: {
2041 /// Set whether to always emit explicit padding fields.
2042 ///
2043 /// This option should be enabled if a `struct` needs to be serialized in its native
2044 /// format (padding bytes and all). This could be required if such `struct` will be
2045 /// written to a file or sent over the network, as anything reading the padding bytes
2046 /// of a struct may cause undefined behavior.
2047 ///
2048 /// Padding fields are not emitted by default.
2049 pub fn explicit_padding(mut self, doit: bool) -> Self {
2050 self.options.force_explicit_padding = doit;
2051 self
2052 }
2053 },
2054 as_args: "--explicit-padding",
2055 },
2056 /// Whether to emit vtable functions.
2057 vtable_generation: bool {
2058 methods: {
2059 /// Set whether to enable experimental support to generate virtual table functions.
2060 ///
2061 /// This option should mostly work, though some edge cases are likely to be broken.
2062 ///
2063 /// Virtual table generation is disabled by default.
2064 pub fn vtable_generation(mut self, doit: bool) -> Self {
2065 self.options.vtable_generation = doit;
2066 self
2067 }
2068 },
2069 as_args: "--vtable-generation",
2070 },
2071 /// Whether to sort the generated Rust items.
2072 sort_semantically: bool {
2073 methods: {
2074 /// Set whether to sort the generated Rust items in a predefined manner.
2075 ///
2076 /// Items are not ordered by default.
2077 pub fn sort_semantically(mut self, doit: bool) -> Self {
2078 self.options.sort_semantically = doit;
2079 self
2080 }
2081 },
2082 as_args: "--sort-semantically",
2083 },
2084 /// Whether to deduplicate `extern` blocks.
2085 merge_extern_blocks: bool {
2086 methods: {
2087 /// Merge all extern blocks under the same module into a single one.
2088 ///
2089 /// Extern blocks are not merged by default.
2090 pub fn merge_extern_blocks(mut self, doit: bool) -> Self {
2091 self.options.merge_extern_blocks = doit;
2092 self
2093 }
2094 },
2095 as_args: "--merge-extern-blocks",
2096 },
2097 /// Whether to wrap unsafe operations in unsafe blocks.
2098 wrap_unsafe_ops: bool {
2099 methods: {
2100 /// Wrap all unsafe operations in unsafe blocks.
2101 ///
2102 /// Unsafe operations are not wrapped by default.
2103 pub fn wrap_unsafe_ops(mut self, doit: bool) -> Self {
2104 self.options.wrap_unsafe_ops = doit;
2105 self
2106 }
2107 },
2108 as_args: "--wrap-unsafe-ops",
2109 },
2110 /// Use DSTs to represent structures with flexible array members.
2111 flexarray_dst: bool {
2112 methods: {
2113 /// Use DSTs to represent structures with flexible array members.
2114 ///
2115 /// This option is disabled by default.
2116 pub fn flexarray_dst(mut self, doit: bool) -> Self {
2117 self.options.flexarray_dst = doit;
2118 self
2119 }
2120 },
2121 as_args: "--flexarray-dst",
2122 },
2123 /// Patterns for functions whose ABI should be overridden.
2124 abi_overrides: HashMap<Abi, RegexSet> {
2125 methods: {
2126 regex_option! {
2127 /// Override the ABI of a given function.
2128 pub fn override_abi<T: Into<String>>(mut self, abi: Abi, arg: T) -> Self {
2129 self.options
2130 .abi_overrides
2131 .entry(abi)
2132 .or_default()
2133 .insert(arg.into());
2134 self
2135 }
2136 }
2137 },
2138 as_args: |overrides, args| {
2139 for (abi, set) in overrides {
2140 for item in set.get_items() {
2141 args.push("--override-abi".to_owned());
2142 args.push(format!("{item}={abi}"));
2143 }
2144 }
2145 },
2146 },
2147 /// Whether to generate wrappers for `static` functions.
2148 wrap_static_fns: bool {
2149 methods: {
2150 /// Set whether to generate wrappers for `static` functions.
2151 ///
2152 /// Passing `true` to this method will generate a C source file with non-`static`
2153 /// functions that call the `static` functions found in the input headers and can be
2154 /// called from Rust once the source file is compiled.
2155 ///
2156 /// The path of this source file can be set using the [`Builder::wrap_static_fns_path`]
2157 /// method.
2158 pub fn wrap_static_fns(mut self, doit: bool) -> Self {
2159 self.options.wrap_static_fns = doit;
2160 self
2161 }
2162 },
2163 as_args: "--wrap-static-fns",
2164 },
2165 /// The suffix to be added to the function wrappers for `static` functions.
2166 wrap_static_fns_suffix: Option<String> {
2167 methods: {
2168 /// Set the suffix added to the wrappers for `static` functions.
2169 ///
2170 /// This option only comes into effect if `true` is passed to the
2171 /// [`Builder::wrap_static_fns`] method.
2172 ///
2173 /// The default suffix is `__extern`.
2174 pub fn wrap_static_fns_suffix<T: AsRef<str>>(mut self, suffix: T) -> Self {
2175 self.options.wrap_static_fns_suffix = Some(suffix.as_ref().to_owned());
2176 self
2177 }
2178 },
2179 as_args: "--wrap-static-fns-suffix",
2180 },
2181 /// The path of the file where the wrappers for `static` functions will be emitted.
2182 wrap_static_fns_path: Option<PathBuf> {
2183 methods: {
2184 /// Set the path for the source code file that would be created if any wrapper
2185 /// functions must be generated due to the presence of `static` functions.
2186 ///
2187 /// `bindgen` will automatically add the right extension to the header and source code
2188 /// files.
2189 ///
2190 /// This option only comes into effect if `true` is passed to the
2191 /// [`Builder::wrap_static_fns`] method.
2192 ///
2193 /// The default path is `temp_dir/bindgen/extern`, where `temp_dir` is the path
2194 /// returned by [`std::env::temp_dir`] .
2195 pub fn wrap_static_fns_path<T: AsRef<Path>>(mut self, path: T) -> Self {
2196 self.options.wrap_static_fns_path = Some(path.as_ref().to_owned());
2197 self
2198 }
2199 },
2200 as_args: "--wrap-static-fns-path",
2201 },
2202 /// Default visibility of fields.
2203 default_visibility: FieldVisibilityKind {
2204 methods: {
2205 /// Set the default visibility of fields, including bitfields and accessor methods for
2206 /// bitfields.
2207 ///
2208 /// This option only comes into effect if the [`Builder::respect_cxx_access_specs`]
2209 /// option is disabled.
2210 pub fn default_visibility(
2211 mut self,
2212 visibility: FieldVisibilityKind,
2213 ) -> Self {
2214 self.options.default_visibility = visibility;
2215 self
2216 }
2217 },
2218 as_args: |visibility, args| {
2219 if *visibility != Default::default() {
2220 args.push("--default-visibility".to_owned());
2221 args.push(visibility.to_string());
2222 }
2223 },
2224 },
2225 /// Whether to emit diagnostics or not.
2226 emit_diagnostics: bool {
2227 methods: {
2228 #[cfg(feature = "experimental")]
2229 /// Emit diagnostics.
2230 ///
2231 /// These diagnostics are emitted to `stderr` if you are using `bindgen-cli` or printed
2232 /// using `cargo:warning=` if you are using `bindgen` as a `build-dependency`.
2233 ///
2234 /// Diagnostics are not emitted by default.
2235 ///
2236 /// The layout and contents of these diagnostic messages are not covered by versioning
2237 /// and can change without notice.
2238 pub fn emit_diagnostics(mut self) -> Self {
2239 self.options.emit_diagnostics = true;
2240 self
2241 }
2242 },
2243 as_args: "--emit-diagnostics",
2244 },
2245 /// Whether to use Clang evaluation on temporary files as a fallback for macros that fail to
2246 /// parse.
2247 clang_macro_fallback: bool {
2248 methods: {
2249 /// Use Clang as a fallback for macros that fail to parse using `CExpr`.
2250 ///
2251 /// This uses a workaround to evaluate each macro in a temporary file. Because this
2252 /// results in slower compilation, this option is opt-in.
2253 pub fn clang_macro_fallback(mut self) -> Self {
2254 self.options.clang_macro_fallback = true;
2255 self
2256 }
2257 },
2258 as_args: "--clang-macro-fallback",
2259 }
2260 /// Path to use for temporary files created by clang macro fallback code like precompiled
2261 /// headers.
2262 clang_macro_fallback_build_dir: Option<PathBuf> {
2263 methods: {
2264 /// Set a path to a directory to which `.c` and `.h.pch` files should be written for the
2265 /// purpose of using clang to evaluate macros that can't be easily parsed.
2266 ///
2267 /// The default location for `.h.pch` files is the directory that the corresponding
2268 /// `.h` file is located in. The default for the temporary `.c` file used for clang
2269 /// parsing is the current working directory. Both of these defaults are overridden
2270 /// by this option.
2271 pub fn clang_macro_fallback_build_dir<P: AsRef<Path>>(mut self, path: P) -> Self {
2272 self.options.clang_macro_fallback_build_dir = Some(path.as_ref().to_owned());
2273 self
2274 }
2275 },
2276 as_args: "--clang-macro-fallback-build-dir",
2277 }
2278 /// Whether to always report C++ "deleted" functions.
2279 generate_deleted_functions: bool {
2280 methods: {
2281 /// Set whether to generate C++ functions even marked "=deleted"
2282 ///
2283 /// Although not useful to call these functions, downstream code
2284 /// generators may need to know whether they've been deleted in
2285 /// order to determine the relocatability of a C++ type
2286 /// (specifically by virtue of which constructors exist.)
2287 pub fn generate_deleted_functions(mut self, doit: bool) -> Self {
2288 self.options.generate_deleted_functions = doit;
2289 self
2290 }
2291
2292 },
2293 as_args: "--generate-deleted-functions",
2294 },
2295 /// Whether to always report C++ "pure virtual" functions.
2296 generate_pure_virtual_functions: bool {
2297 methods: {
2298 /// Set whether to generate C++ functions that are pure virtual.
2299 ///
2300 /// These functions can't be called, so the only reason
2301 /// to generate them is if downstream postprocessors
2302 /// need to know of their existence. This is necessary,
2303 /// for instance, to determine whether a type itself is
2304 /// pure virtual and thus can't be allocated.
2305 /// Downstream code generators may choose to make code to
2306 /// allow types to be allocated but need to avoid doing so
2307 /// if the type contains pure virtual functions.
2308 pub fn generate_pure_virtual_functions(mut self, doit: bool) -> Self {
2309 self.options.generate_pure_virtual_functions = doit;
2310 self
2311 }
2312
2313 },
2314 as_args: "--generate-pure-virtual-functions",
2315 },
2316 /// Whether to always report C++ "private" functions.
2317 generate_private_functions: bool {
2318 methods: {
2319 /// Set whether to generate C++ functions that are private.
2320 ///
2321 /// These functions can't be called, so the only reason
2322 /// to generate them is if downstream postprocessors
2323 /// need to know of their existence.
2324 pub fn generate_private_functions(mut self, doit: bool) -> Self {
2325 self.options.generate_private_functions = doit;
2326 self
2327 }
2328
2329 },
2330 as_args: "--generate-private-functions",
2331 },
2332 /// Field attribute patterns for adding custom attributes to struct/union fields.
2333 field_attr_patterns: Vec<(Box<str>, Box<str>, Box<str>)> {
2334 methods: {
2335 /// Add a custom attribute to a specific field.
2336 ///
2337 /// # Arguments
2338 ///
2339 /// * `type_name` - The name of the struct or union containing the field
2340 /// * `field_name` - The name of the field (use "0" for newtype tuple fields)
2341 /// * `attribute` - The attribute to add (e.g., "serde(skip)")
2342 ///
2343 /// # Example
2344 ///
2345 /// ```ignore
2346 /// bindgen::Builder::default()
2347 /// .header("input.h")
2348 /// .field_attribute("MyStruct", "data", r#"serde(rename = "myData")"#)
2349 /// .field_attribute("MyStruct", "secret", "serde(skip)")
2350 /// .generate()
2351 /// .unwrap();
2352 /// ```
2353 pub fn field_attribute<T, F, A>(
2354 mut self,
2355 type_name: T,
2356 field_name: F,
2357 attribute: A,
2358 ) -> Self
2359 where
2360 T: Into<String>,
2361 F: Into<String>,
2362 A: Into<String>,
2363 {
2364 self.options.field_attr_patterns.push((
2365 type_name.into().into_boxed_str(),
2366 field_name.into().into_boxed_str(),
2367 attribute.into().into_boxed_str(),
2368 ));
2369 self
2370 }
2371 },
2372 as_args: |patterns, args| {
2373 for (type_pat, field_pat, attr) in patterns {
2374 args.push("--field-attr".to_owned());
2375 args.push(format!("{type_pat}::{field_pat}={attr}"));
2376 }
2377 },
2378 },
2379}