-
Notifications
You must be signed in to change notification settings - Fork 707
/
lib.rs
3034 lines (2623 loc) · 100 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Generate Rust bindings for C and C++ libraries.
//!
//! Provide a C/C++ header file, receive Rust FFI code to call into C/C++
//! functions and use types defined in the header.
//!
//! See the [`Builder`](./struct.Builder.html) struct for usage.
//!
//! See the [Users Guide](https://rust-lang.github.io/rust-bindgen/) for
//! additional documentation.
#![deny(missing_docs)]
#![deny(unused_extern_crates)]
// To avoid rather annoying warnings when matching with CXCursor_xxx as a
// constant.
#![allow(non_upper_case_globals)]
// `quote!` nests quite deeply.
#![recursion_limit = "128"]
#[macro_use]
extern crate bitflags;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate quote;
#[cfg(feature = "logging")]
#[macro_use]
extern crate log;
#[cfg(not(feature = "logging"))]
#[macro_use]
mod log_stubs;
#[macro_use]
mod extra_assertions;
// A macro to declare an internal module for which we *must* provide
// documentation for. If we are building with the "testing_only_docs" feature,
// then the module is declared public, and our `#![deny(missing_docs)]` pragma
// applies to it. This feature is used in CI, so we won't let anything slip by
// undocumented. Normal builds, however, will leave the module private, so that
// we don't expose internals to library consumers.
macro_rules! doc_mod {
($m:ident, $doc_mod_name:ident) => {
#[cfg(feature = "testing_only_docs")]
pub mod $doc_mod_name {
//! Autogenerated documentation module.
pub use super::$m::*;
}
};
}
macro_rules! fn_with_regex_arg {
($(#[$attrs:meta])* pub fn $($tokens:tt)*) => {
$(#[$attrs])*
/// Check the [regular expression arguments] section and the [regex] crate
/// documentation for further information.
///
/// [regular expression arguments]: ./struct.Builder.html#regular-expression-arguments
/// [regex]: <https://docs.rs/regex>
pub fn $($tokens)*
};
}
mod clang;
mod codegen;
mod deps;
mod features;
pub mod ir;
mod parse;
mod regex_set;
mod time;
pub mod callbacks;
doc_mod!(clang, clang_docs);
doc_mod!(features, features_docs);
doc_mod!(ir, ir_docs);
doc_mod!(parse, parse_docs);
doc_mod!(regex_set, regex_set_docs);
use ir::comment;
pub use crate::codegen::{
AliasVariation, EnumVariation, MacroTypeVariation, NonCopyUnionStyle,
};
use crate::features::RustFeatures;
pub use crate::features::{
RustTarget, LATEST_STABLE_RUST, RUST_TARGET_STRINGS,
};
use crate::ir::context::{BindgenContext, ItemId};
pub use crate::ir::function::Abi;
use crate::ir::item::Item;
use crate::parse::ParseError;
pub use crate::regex_set::RegexSet;
use std::borrow::Cow;
use std::env;
use std::fs::{File, OpenOptions};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::rc::Rc;
// Some convenient typedefs for a fast hash map and hash set.
type HashMap<K, V> = ::rustc_hash::FxHashMap<K, V>;
type HashSet<K> = ::rustc_hash::FxHashSet<K>;
pub(crate) use std::collections::hash_map::Entry;
/// Default prefix for the anon fields.
pub const DEFAULT_ANON_FIELDS_PREFIX: &str = "__bindgen_anon_";
fn file_is_cpp(name_file: &str) -> bool {
name_file.ends_with(".hpp") ||
name_file.ends_with(".hxx") ||
name_file.ends_with(".hh") ||
name_file.ends_with(".h++")
}
fn args_are_cpp(clang_args: &[String]) -> bool {
for w in clang_args.windows(2) {
if w[0] == "-xc++" || w[1] == "-xc++" {
return true;
}
if w[0] == "-x" && w[1] == "c++" {
return true;
}
if w[0] == "-include" && file_is_cpp(&w[1]) {
return true;
}
}
false
}
bitflags! {
/// A type used to indicate which kind of items we have to generate.
pub struct CodegenConfig: u32 {
/// Whether to generate functions.
const FUNCTIONS = 1 << 0;
/// Whether to generate types.
const TYPES = 1 << 1;
/// Whether to generate constants.
const VARS = 1 << 2;
/// Whether to generate methods.
const METHODS = 1 << 3;
/// Whether to generate constructors
const CONSTRUCTORS = 1 << 4;
/// Whether to generate destructors.
const DESTRUCTORS = 1 << 5;
}
}
impl CodegenConfig {
/// Returns true if functions should be generated.
pub fn functions(self) -> bool {
self.contains(CodegenConfig::FUNCTIONS)
}
/// Returns true if types should be generated.
pub fn types(self) -> bool {
self.contains(CodegenConfig::TYPES)
}
/// Returns true if constants should be generated.
pub fn vars(self) -> bool {
self.contains(CodegenConfig::VARS)
}
/// Returns true if methds should be generated.
pub fn methods(self) -> bool {
self.contains(CodegenConfig::METHODS)
}
/// Returns true if constructors should be generated.
pub fn constructors(self) -> bool {
self.contains(CodegenConfig::CONSTRUCTORS)
}
/// Returns true if destructors should be generated.
pub fn destructors(self) -> bool {
self.contains(CodegenConfig::DESTRUCTORS)
}
}
impl Default for CodegenConfig {
fn default() -> Self {
CodegenConfig::all()
}
}
/// Configure and generate Rust bindings for a C/C++ header.
///
/// This is the main entry point to the library.
///
/// ```ignore
/// use bindgen::builder;
///
/// // Configure and generate bindings.
/// let bindings = builder().header("path/to/input/header")
/// .allowlist_type("SomeCoolClass")
/// .allowlist_function("do_some_cool_thing")
/// .generate()?;
///
/// // Write the generated bindings to an output file.
/// bindings.write_to_file("path/to/output.rs")?;
/// ```
///
/// # Enums
///
/// Bindgen can map C/C++ enums into Rust in different ways. The way bindgen maps enums depends on
/// the pattern passed to several methods:
///
/// 1. [`constified_enum_module()`](#method.constified_enum_module)
/// 2. [`bitfield_enum()`](#method.bitfield_enum)
/// 3. [`newtype_enum()`](#method.newtype_enum)
/// 4. [`rustified_enum()`](#method.rustified_enum)
///
/// For each C enum, bindgen tries to match the pattern in the following order:
///
/// 1. Constified enum module
/// 2. Bitfield enum
/// 3. Newtype enum
/// 4. Rustified enum
///
/// If none of the above patterns match, then bindgen will generate a set of Rust constants.
///
/// # Clang arguments
///
/// Extra arguments can be passed to with clang:
/// 1. [`clang_arg()`](#method.clang_arg): takes a single argument
/// 2. [`clang_args()`](#method.clang_args): takes an iterator of arguments
/// 3. `BINDGEN_EXTRA_CLANG_ARGS` environment variable: whitespace separate
/// environment variable of arguments
///
/// Clang arguments specific to your crate should be added via the
/// `clang_arg()`/`clang_args()` methods.
///
/// End-users of the crate may need to set the `BINDGEN_EXTRA_CLANG_ARGS` environment variable to
/// add additional arguments. For example, to build against a different sysroot a user could set
/// `BINDGEN_EXTRA_CLANG_ARGS` to `--sysroot=/path/to/sysroot`.
///
/// # Regular expression arguments
///
/// Some [`Builder`] methods like the `allowlist_*` and `blocklist_*` family of methods allow
/// regular expressions as arguments. These regular expressions will be parenthesized and wrapped
/// in `^` and `$`. So if `<regex>` is passed as argument, the regular expression to be stored will
/// be `^(<regex>)$`.
///
/// Releases of `bindgen` with a version lesser or equal to `0.62.0` used to accept the wildcard
/// pattern `*` as a valid regular expression. This behavior has been deprecated and the `.*`
/// pattern must be used instead.
#[derive(Debug, Default, Clone)]
pub struct Builder {
options: BindgenOptions,
}
/// Construct a new [`Builder`](./struct.Builder.html).
pub fn builder() -> Builder {
Default::default()
}
fn get_extra_clang_args() -> Vec<String> {
// Add any extra arguments from the environment to the clang command line.
let extra_clang_args =
match get_target_dependent_env_var("BINDGEN_EXTRA_CLANG_ARGS") {
None => return vec![],
Some(s) => s,
};
// Try to parse it with shell quoting. If we fail, make it one single big argument.
if let Some(strings) = shlex::split(&extra_clang_args) {
return strings;
}
vec![extra_clang_args]
}
impl Builder {
/// Generates the command line flags use for creating `Builder`.
pub fn command_line_flags(&self) -> Vec<String> {
let mut output_vector: Vec<String> = Vec::new();
if let Some(header) = self.options.input_headers.last().cloned() {
// Positional argument 'header'
output_vector.push(header);
}
output_vector.push("--rust-target".into());
output_vector.push(self.options.rust_target.into());
// FIXME(emilio): This is a bit hacky, maybe we should stop re-using the
// RustFeatures to store the "disable_untagged_union" call, and make it
// a different flag that we check elsewhere / in generate().
if !self.options.rust_features.untagged_union &&
RustFeatures::from(self.options.rust_target).untagged_union
{
output_vector.push("--disable-untagged-union".into());
}
if self.options.default_enum_style != Default::default() {
output_vector.push("--default-enum-style".into());
output_vector.push(
match self.options.default_enum_style {
codegen::EnumVariation::Rust {
non_exhaustive: false,
} => "rust",
codegen::EnumVariation::Rust {
non_exhaustive: true,
} => "rust_non_exhaustive",
codegen::EnumVariation::NewType {
is_bitfield: true,
..
} => "bitfield",
codegen::EnumVariation::NewType {
is_bitfield: false,
is_global,
} => {
if is_global {
"newtype_global"
} else {
"newtype"
}
}
codegen::EnumVariation::Consts => "consts",
codegen::EnumVariation::ModuleConsts => "moduleconsts",
}
.into(),
)
}
if self.options.default_macro_constant_type != Default::default() {
output_vector.push("--default-macro-constant-type".into());
output_vector
.push(self.options.default_macro_constant_type.as_str().into());
}
if self.options.default_alias_style != Default::default() {
output_vector.push("--default-alias-style".into());
output_vector
.push(self.options.default_alias_style.as_str().into());
}
if self.options.default_non_copy_union_style != Default::default() {
output_vector.push("--default-non-copy-union-style".into());
output_vector.push(
self.options.default_non_copy_union_style.as_str().into(),
);
}
let regex_sets = &[
(&self.options.bitfield_enums, "--bitfield-enum"),
(&self.options.newtype_enums, "--newtype-enum"),
(&self.options.newtype_global_enums, "--newtype-global-enum"),
(&self.options.rustified_enums, "--rustified-enum"),
(
&self.options.rustified_non_exhaustive_enums,
"--rustified-enum-non-exhaustive",
),
(
&self.options.constified_enum_modules,
"--constified-enum-module",
),
(&self.options.constified_enums, "--constified-enum"),
(&self.options.type_alias, "--type-alias"),
(&self.options.new_type_alias, "--new-type-alias"),
(&self.options.new_type_alias_deref, "--new-type-alias-deref"),
(
&self.options.bindgen_wrapper_union,
"--bindgen-wrapper-union",
),
(&self.options.manually_drop_union, "--manually-drop-union"),
(&self.options.blocklisted_types, "--blocklist-type"),
(&self.options.blocklisted_functions, "--blocklist-function"),
(&self.options.blocklisted_items, "--blocklist-item"),
(&self.options.blocklisted_files, "--blocklist-file"),
(&self.options.opaque_types, "--opaque-type"),
(&self.options.allowlisted_functions, "--allowlist-function"),
(&self.options.allowlisted_types, "--allowlist-type"),
(&self.options.allowlisted_vars, "--allowlist-var"),
(&self.options.allowlisted_files, "--allowlist-file"),
(&self.options.no_partialeq_types, "--no-partialeq"),
(&self.options.no_copy_types, "--no-copy"),
(&self.options.no_debug_types, "--no-debug"),
(&self.options.no_default_types, "--no-default"),
(&self.options.no_hash_types, "--no-hash"),
(&self.options.must_use_types, "--must-use-type"),
];
for (set, flag) in regex_sets {
for item in set.get_items() {
output_vector.push((*flag).to_owned());
output_vector.push(item.to_owned());
}
}
for (abi, set) in &self.options.abi_overrides {
for item in set.get_items() {
output_vector.push("--override-abi".to_owned());
output_vector.push(format!("{}={}", item, abi));
}
}
if !self.options.layout_tests {
output_vector.push("--no-layout-tests".into());
}
if self.options.impl_debug {
output_vector.push("--impl-debug".into());
}
if self.options.impl_partialeq {
output_vector.push("--impl-partialeq".into());
}
if !self.options.derive_copy {
output_vector.push("--no-derive-copy".into());
}
if !self.options.derive_debug {
output_vector.push("--no-derive-debug".into());
}
if !self.options.derive_default {
output_vector.push("--no-derive-default".into());
} else {
output_vector.push("--with-derive-default".into());
}
if self.options.derive_hash {
output_vector.push("--with-derive-hash".into());
}
if self.options.derive_partialord {
output_vector.push("--with-derive-partialord".into());
}
if self.options.derive_ord {
output_vector.push("--with-derive-ord".into());
}
if self.options.derive_partialeq {
output_vector.push("--with-derive-partialeq".into());
}
if self.options.derive_eq {
output_vector.push("--with-derive-eq".into());
}
if self.options.time_phases {
output_vector.push("--time-phases".into());
}
if !self.options.generate_comments {
output_vector.push("--no-doc-comments".into());
}
if !self.options.allowlist_recursively {
output_vector.push("--no-recursive-allowlist".into());
}
if self.options.objc_extern_crate {
output_vector.push("--objc-extern-crate".into());
}
if self.options.generate_block {
output_vector.push("--generate-block".into());
}
if self.options.block_extern_crate {
output_vector.push("--block-extern-crate".into());
}
if self.options.builtins {
output_vector.push("--builtins".into());
}
if let Some(ref prefix) = self.options.ctypes_prefix {
output_vector.push("--ctypes-prefix".into());
output_vector.push(prefix.clone());
}
if self.options.anon_fields_prefix != DEFAULT_ANON_FIELDS_PREFIX {
output_vector.push("--anon-fields-prefix".into());
output_vector.push(self.options.anon_fields_prefix.clone());
}
if self.options.emit_ast {
output_vector.push("--emit-clang-ast".into());
}
if self.options.emit_ir {
output_vector.push("--emit-ir".into());
}
if let Some(ref graph) = self.options.emit_ir_graphviz {
output_vector.push("--emit-ir-graphviz".into());
output_vector.push(graph.clone())
}
if self.options.enable_cxx_namespaces {
output_vector.push("--enable-cxx-namespaces".into());
}
if self.options.enable_function_attribute_detection {
output_vector.push("--enable-function-attribute-detection".into());
}
if self.options.disable_name_namespacing {
output_vector.push("--disable-name-namespacing".into());
}
if self.options.disable_nested_struct_naming {
output_vector.push("--disable-nested-struct-naming".into());
}
if self.options.disable_header_comment {
output_vector.push("--disable-header-comment".into());
}
if !self.options.codegen_config.functions() {
output_vector.push("--ignore-functions".into());
}
output_vector.push("--generate".into());
//Temporary placeholder for below 4 options
let mut options: Vec<String> = Vec::new();
if self.options.codegen_config.functions() {
options.push("functions".into());
}
if self.options.codegen_config.types() {
options.push("types".into());
}
if self.options.codegen_config.vars() {
options.push("vars".into());
}
if self.options.codegen_config.methods() {
options.push("methods".into());
}
if self.options.codegen_config.constructors() {
options.push("constructors".into());
}
if self.options.codegen_config.destructors() {
options.push("destructors".into());
}
output_vector.push(options.join(","));
if !self.options.codegen_config.methods() {
output_vector.push("--ignore-methods".into());
}
if !self.options.convert_floats {
output_vector.push("--no-convert-floats".into());
}
if !self.options.prepend_enum_name {
output_vector.push("--no-prepend-enum-name".into());
}
if self.options.fit_macro_constants {
output_vector.push("--fit-macro-constant-types".into());
}
if self.options.array_pointers_in_arguments {
output_vector.push("--use-array-pointers-in-arguments".into());
}
if let Some(ref wasm_import_module_name) =
self.options.wasm_import_module_name
{
output_vector.push("--wasm-import-module-name".into());
output_vector.push(wasm_import_module_name.clone());
}
for line in &self.options.raw_lines {
output_vector.push("--raw-line".into());
output_vector.push(line.clone());
}
for (module, lines) in &self.options.module_lines {
for line in lines.iter() {
output_vector.push("--module-raw-line".into());
output_vector.push(module.clone());
output_vector.push(line.clone());
}
}
if self.options.use_core {
output_vector.push("--use-core".into());
}
if self.options.conservative_inline_namespaces {
output_vector.push("--conservative-inline-namespaces".into());
}
if self.options.generate_inline_functions {
output_vector.push("--generate-inline-functions".into());
}
if !self.options.record_matches {
output_vector.push("--no-record-matches".into());
}
if !self.options.size_t_is_usize {
output_vector.push("--no-size_t-is-usize".into());
}
if !self.options.rustfmt_bindings {
output_vector.push("--no-rustfmt-bindings".into());
}
if let Some(path) = self
.options
.rustfmt_configuration_file
.as_ref()
.and_then(|f| f.to_str())
{
output_vector.push("--rustfmt-configuration-file".into());
output_vector.push(path.into());
}
if let Some(ref name) = self.options.dynamic_library_name {
output_vector.push("--dynamic-loading".into());
output_vector.push(name.clone());
}
if self.options.dynamic_link_require_all {
output_vector.push("--dynamic-link-require-all".into());
}
if self.options.respect_cxx_access_specs {
output_vector.push("--respect-cxx-access-specs".into());
}
if self.options.translate_enum_integer_types {
output_vector.push("--translate-enum-integer-types".into());
}
if self.options.c_naming {
output_vector.push("--c-naming".into());
}
if self.options.force_explicit_padding {
output_vector.push("--explicit-padding".into());
}
if self.options.vtable_generation {
output_vector.push("--vtable-generation".into());
}
if self.options.sort_semantically {
output_vector.push("--sort-semantically".into());
}
if self.options.merge_extern_blocks {
output_vector.push("--merge-extern-blocks".into());
}
if self.options.wrap_unsafe_ops {
output_vector.push("--wrap-unsafe-ops".into());
}
#[cfg(feature = "cli")]
for callbacks in &self.options.parse_callbacks {
output_vector.extend(callbacks.cli_args());
}
// Add clang arguments
output_vector.push("--".into());
if !self.options.clang_args.is_empty() {
output_vector.extend(self.options.clang_args.iter().cloned());
}
// To pass more than one header, we need to pass all but the last
// header via the `-include` clang arg
for header in &self.options.input_headers
[..self.options.input_headers.len().saturating_sub(1)]
{
output_vector.push("-include".to_string());
output_vector.push(header.clone());
}
output_vector
}
/// Add an input C/C++ header to generate bindings for.
///
/// This can be used to generate bindings to a single header:
///
/// ```ignore
/// let bindings = bindgen::Builder::default()
/// .header("input.h")
/// .generate()
/// .unwrap();
/// ```
///
/// Or you can invoke it multiple times to generate bindings to multiple
/// headers:
///
/// ```ignore
/// let bindings = bindgen::Builder::default()
/// .header("first.h")
/// .header("second.h")
/// .header("third.h")
/// .generate()
/// .unwrap();
/// ```
pub fn header<T: Into<String>>(mut self, header: T) -> Builder {
self.options.input_headers.push(header.into());
self
}
/// Add a depfile output which will be written alongside the generated bindings.
pub fn depfile<H: Into<String>, D: Into<PathBuf>>(
mut self,
output_module: H,
depfile: D,
) -> Builder {
self.options.depfile = Some(deps::DepfileSpec {
output_module: output_module.into(),
depfile_path: depfile.into(),
});
self
}
/// Add `contents` as an input C/C++ header named `name`.
///
/// The file `name` will be added to the clang arguments.
pub fn header_contents(mut self, name: &str, contents: &str) -> Builder {
// Apparently clang relies on having virtual FS correspondent to
// the real one, so we need absolute paths here
let absolute_path = env::current_dir()
.expect("Cannot retrieve current directory")
.join(name)
.to_str()
.expect("Cannot convert current directory name to string")
.to_owned();
self.options
.input_header_contents
.push((absolute_path, contents.into()));
self
}
/// Specify the rust target
///
/// The default is the latest stable Rust version
pub fn rust_target(mut self, rust_target: RustTarget) -> Self {
#[allow(deprecated)]
if rust_target <= RustTarget::Stable_1_30 {
warn!(
"The {} rust target is deprecated. If you have a good reason to use this target please report it at https://github.com/rust-lang/rust-bindgen/issues",
String::from(rust_target)
);
}
self.options.set_rust_target(rust_target);
self
}
/// Disable support for native Rust unions, if supported.
pub fn disable_untagged_union(mut self) -> Self {
self.options.rust_features.untagged_union = false;
self
}
/// Disable insertion of bindgen's version identifier into generated
/// bindings.
pub fn disable_header_comment(mut self) -> Self {
self.options.disable_header_comment = true;
self
}
/// Set the output graphviz file.
pub fn emit_ir_graphviz<T: Into<String>>(mut self, path: T) -> Builder {
let path = path.into();
self.options.emit_ir_graphviz = Some(path);
self
}
/// Whether the generated bindings should contain documentation comments
/// (docstrings) or not. This is set to true by default.
///
/// Note that clang by default excludes comments from system headers, pass
/// `-fretain-comments-from-system-headers` as
/// [`clang_arg`][Builder::clang_arg] to include them. It can also be told
/// to process all comments (not just documentation ones) using the
/// `-fparse-all-comments` flag. See [slides on clang comment parsing](
/// https://llvm.org/devmtg/2012-11/Gribenko_CommentParsing.pdf) for
/// background and examples.
pub fn generate_comments(mut self, doit: bool) -> Self {
self.options.generate_comments = doit;
self
}
/// Whether to allowlist recursively or not. Defaults to true.
///
/// Given that we have explicitly allowlisted the "initiate_dance_party"
/// function in this C header:
///
/// ```c
/// typedef struct MoonBoots {
/// int bouncy_level;
/// } MoonBoots;
///
/// void initiate_dance_party(MoonBoots* boots);
/// ```
///
/// We would normally generate bindings to both the `initiate_dance_party`
/// function and the `MoonBoots` struct that it transitively references. By
/// configuring with `allowlist_recursively(false)`, `bindgen` will not emit
/// bindings for anything except the explicitly allowlisted items, and there
/// would be no emitted struct definition for `MoonBoots`. However, the
/// `initiate_dance_party` function would still reference `MoonBoots`!
///
/// **Disabling this feature will almost certainly cause `bindgen` to emit
/// bindings that will not compile!** If you disable this feature, then it
/// is *your* responsibility to provide definitions for every type that is
/// referenced from an explicitly allowlisted item. One way to provide the
/// definitions is by using the [`Builder::raw_line`](#method.raw_line)
/// method, another would be to define them in Rust and then `include!(...)`
/// the bindings immediately afterwards.
pub fn allowlist_recursively(mut self, doit: bool) -> Self {
self.options.allowlist_recursively = doit;
self
}
/// Generate `#[macro_use] extern crate objc;` instead of `use objc;`
/// in the prologue of the files generated from objective-c files
pub fn objc_extern_crate(mut self, doit: bool) -> Self {
self.options.objc_extern_crate = doit;
self
}
/// Generate proper block signatures instead of void pointers.
pub fn generate_block(mut self, doit: bool) -> Self {
self.options.generate_block = doit;
self
}
/// Generate `#[macro_use] extern crate block;` instead of `use block;`
/// in the prologue of the files generated from apple block files
pub fn block_extern_crate(mut self, doit: bool) -> Self {
self.options.block_extern_crate = doit;
self
}
/// Whether to use the clang-provided name mangling. This is true by default
/// and probably needed for C++ features.
///
/// However, some old libclang versions seem to return incorrect results in
/// some cases for non-mangled functions, see [1], so we allow disabling it.
///
/// [1]: https://github.com/rust-lang/rust-bindgen/issues/528
pub fn trust_clang_mangling(mut self, doit: bool) -> Self {
self.options.enable_mangling = doit;
self
}
fn_with_regex_arg! {
/// Hide the given type from the generated bindings. Regular expressions are
/// supported.
///
/// To blocklist types prefixed with "mylib" use `"mylib_.*"`.
pub fn blocklist_type<T: AsRef<str>>(mut self, arg: T) -> Builder {
self.options.blocklisted_types.insert(arg);
self
}
}
fn_with_regex_arg! {
/// Hide the given function from the generated bindings. Regular expressions
/// are supported.
///
/// Methods can be blocklisted by prefixing the name of the type implementing
/// them followed by an underscore. So if `Foo` has a method `bar`, it can
/// be blocklisted as `Foo_bar`.
///
/// To blocklist functions prefixed with "mylib" use `"mylib_.*"`.
pub fn blocklist_function<T: AsRef<str>>(mut self, arg: T) -> Builder {
self.options.blocklisted_functions.insert(arg);
self
}
}
fn_with_regex_arg! {
/// Hide the given item from the generated bindings, regardless of
/// whether it's a type, function, module, etc. Regular
/// expressions are supported.
///
/// To blocklist items prefixed with "mylib" use `"mylib_.*"`.
pub fn blocklist_item<T: AsRef<str>>(mut self, arg: T) -> Builder {
self.options.blocklisted_items.insert(arg);
self
}
}
fn_with_regex_arg! {
/// Hide any contents of the given file from the generated bindings,
/// regardless of whether it's a type, function, module etc.
pub fn blocklist_file<T: AsRef<str>>(mut self, arg: T) -> Builder {
self.options.blocklisted_files.insert(arg);
self
}
}
fn_with_regex_arg! {
/// Treat the given type as opaque in the generated bindings. Regular
/// expressions are supported.
///
/// To change types prefixed with "mylib" into opaque, use `"mylib_.*"`.
pub fn opaque_type<T: AsRef<str>>(mut self, arg: T) -> Builder {
self.options.opaque_types.insert(arg);
self
}
}
fn_with_regex_arg! {
/// Allowlist the given type so that it (and all types that it transitively
/// refers to) appears in the generated bindings. Regular expressions are
/// supported.
///
/// To allowlist types prefixed with "mylib" use `"mylib_.*"`.
pub fn allowlist_type<T: AsRef<str>>(mut self, arg: T) -> Builder {
self.options.allowlisted_types.insert(arg);
self
}
}
fn_with_regex_arg! {
/// Allowlist the given function so that it (and all types that it
/// transitively refers to) appears in the generated bindings. Regular
/// expressions are supported.
///
/// Methods can be allowlisted by prefixing the name of the type
/// implementing them followed by an underscore. So if `Foo` has a method
/// `bar`, it can be allowlisted as `Foo_bar`.
///
/// To allowlist functions prefixed with "mylib" use `"mylib_.*"`.
pub fn allowlist_function<T: AsRef<str>>(mut self, arg: T) -> Builder {
self.options.allowlisted_functions.insert(arg);
self
}
}
fn_with_regex_arg! {
/// Allowlist the given variable so that it (and all types that it
/// transitively refers to) appears in the generated bindings. Regular
/// expressions are supported.
///
/// To allowlist variables prefixed with "mylib" use `"mylib_.*"`.
pub fn allowlist_var<T: AsRef<str>>(mut self, arg: T) -> Builder {
self.options.allowlisted_vars.insert(arg);
self
}
}
fn_with_regex_arg! {
/// Allowlist the given file so that its contents appear in the generated bindings.
pub fn allowlist_file<T: AsRef<str>>(mut self, arg: T) -> Builder {
self.options.allowlisted_files.insert(arg);
self
}
}
/// Set the default style of code to generate for enums
pub fn default_enum_style(
mut self,
arg: codegen::EnumVariation,
) -> Builder {
self.options.default_enum_style = arg;
self
}
fn_with_regex_arg! {
/// Mark the given enum (or set of enums, if using a pattern) as being
/// bitfield-like. Regular expressions are supported.
///
/// This makes bindgen generate a type that isn't a rust `enum`. Regular
/// expressions are supported.
///
/// This is similar to the newtype enum style, but with the bitwise
/// operators implemented.
pub fn bitfield_enum<T: AsRef<str>>(mut self, arg: T) -> Builder {
self.options.bitfield_enums.insert(arg);
self
}
}
fn_with_regex_arg! {
/// Mark the given enum (or set of enums, if using a pattern) as a newtype.
/// Regular expressions are supported.
///
/// This makes bindgen generate a type that isn't a Rust `enum`. Regular
/// expressions are supported.
pub fn newtype_enum<T: AsRef<str>>(mut self, arg: T) -> Builder {
self.options.newtype_enums.insert(arg);
self
}
}
fn_with_regex_arg! {
/// Mark the given enum (or set of enums, if using a pattern) as a newtype
/// whose variants are exposed as global constants.
///
/// Regular expressions are supported.
///