• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //! Generate Rust bindings for C and C++ libraries.
2 //!
3 //! Provide a C/C++ header file, receive Rust FFI code to call into C/C++
4 //! functions and use types defined in the header.
5 //!
6 //! See the [`Builder`](./struct.Builder.html) struct for usage.
7 //!
8 //! See the [Users Guide](https://rust-lang.github.io/rust-bindgen/) for
9 //! additional documentation.
10 #![deny(missing_docs)]
11 #![deny(unused_extern_crates)]
12 #![deny(clippy::disallowed_methods)]
13 // To avoid rather annoying warnings when matching with CXCursor_xxx as a
14 // constant.
15 #![allow(non_upper_case_globals)]
16 // `quote!` nests quite deeply.
17 #![recursion_limit = "128"]
18 
19 #[macro_use]
20 extern crate bitflags;
21 #[macro_use]
22 extern crate lazy_static;
23 #[macro_use]
24 extern crate quote;
25 
26 #[cfg(feature = "logging")]
27 #[macro_use]
28 extern crate log;
29 
30 #[cfg(not(feature = "logging"))]
31 #[macro_use]
32 mod log_stubs;
33 
34 #[macro_use]
35 mod extra_assertions;
36 
37 mod codegen;
38 mod deps;
39 mod options;
40 mod time;
41 
42 pub mod callbacks;
43 
44 mod clang;
45 #[cfg(feature = "experimental")]
46 mod diagnostics;
47 mod features;
48 mod ir;
49 mod parse;
50 mod regex_set;
51 
52 pub use codegen::{
53     AliasVariation, EnumVariation, MacroTypeVariation, NonCopyUnionStyle,
54 };
55 #[cfg(feature = "__cli")]
56 pub use features::RUST_TARGET_STRINGS;
57 pub use features::{RustTarget, LATEST_STABLE_RUST};
58 pub use ir::annotations::FieldVisibilityKind;
59 pub use ir::function::Abi;
60 pub use regex_set::RegexSet;
61 
62 use codegen::CodegenError;
63 use features::RustFeatures;
64 use ir::comment;
65 use ir::context::{BindgenContext, ItemId};
66 use ir::item::Item;
67 use options::BindgenOptions;
68 use parse::ParseError;
69 
70 use std::borrow::Cow;
71 use std::collections::hash_map::Entry;
72 use std::env;
73 use std::ffi::OsStr;
74 use std::fs::{File, OpenOptions};
75 use std::io::{self, Write};
76 use std::path::{Path, PathBuf};
77 use std::process::{Command, Stdio};
78 use std::rc::Rc;
79 use std::str::FromStr;
80 
81 // Some convenient typedefs for a fast hash map and hash set.
82 type HashMap<K, V> = rustc_hash::FxHashMap<K, V>;
83 type HashSet<K> = rustc_hash::FxHashSet<K>;
84 
85 /// Default prefix for the anon fields.
86 pub const DEFAULT_ANON_FIELDS_PREFIX: &str = "__bindgen_anon_";
87 
88 const DEFAULT_NON_EXTERN_FNS_SUFFIX: &str = "__extern";
89 
file_is_cpp(name_file: &str) -> bool90 fn file_is_cpp(name_file: &str) -> bool {
91     name_file.ends_with(".hpp") ||
92         name_file.ends_with(".hxx") ||
93         name_file.ends_with(".hh") ||
94         name_file.ends_with(".h++")
95 }
96 
args_are_cpp(clang_args: &[Box<str>]) -> bool97 fn args_are_cpp(clang_args: &[Box<str>]) -> bool {
98     for w in clang_args.windows(2) {
99         if w[0].as_ref() == "-xc++" || w[1].as_ref() == "-xc++" {
100             return true;
101         }
102         if w[0].as_ref() == "-x" && w[1].as_ref() == "c++" {
103             return true;
104         }
105         if w[0].as_ref() == "-include" && file_is_cpp(w[1].as_ref()) {
106             return true;
107         }
108     }
109     false
110 }
111 
112 bitflags! {
113     /// A type used to indicate which kind of items we have to generate.
114     #[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
115     pub struct CodegenConfig: u32 {
116         /// Whether to generate functions.
117         const FUNCTIONS = 1 << 0;
118         /// Whether to generate types.
119         const TYPES = 1 << 1;
120         /// Whether to generate constants.
121         const VARS = 1 << 2;
122         /// Whether to generate methods.
123         const METHODS = 1 << 3;
124         /// Whether to generate constructors
125         const CONSTRUCTORS = 1 << 4;
126         /// Whether to generate destructors.
127         const DESTRUCTORS = 1 << 5;
128     }
129 }
130 
131 impl CodegenConfig {
132     /// Returns true if functions should be generated.
functions(self) -> bool133     pub fn functions(self) -> bool {
134         self.contains(CodegenConfig::FUNCTIONS)
135     }
136 
137     /// Returns true if types should be generated.
types(self) -> bool138     pub fn types(self) -> bool {
139         self.contains(CodegenConfig::TYPES)
140     }
141 
142     /// Returns true if constants should be generated.
vars(self) -> bool143     pub fn vars(self) -> bool {
144         self.contains(CodegenConfig::VARS)
145     }
146 
147     /// Returns true if methds should be generated.
methods(self) -> bool148     pub fn methods(self) -> bool {
149         self.contains(CodegenConfig::METHODS)
150     }
151 
152     /// Returns true if constructors should be generated.
constructors(self) -> bool153     pub fn constructors(self) -> bool {
154         self.contains(CodegenConfig::CONSTRUCTORS)
155     }
156 
157     /// Returns true if destructors should be generated.
destructors(self) -> bool158     pub fn destructors(self) -> bool {
159         self.contains(CodegenConfig::DESTRUCTORS)
160     }
161 }
162 
163 impl Default for CodegenConfig {
default() -> Self164     fn default() -> Self {
165         CodegenConfig::all()
166     }
167 }
168 
169 /// Formatting tools that can be used to format the bindings
170 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
171 #[non_exhaustive]
172 pub enum Formatter {
173     /// Do not format the bindings.
174     None,
175     /// Use `rustfmt` to format the bindings.
176     Rustfmt,
177     #[cfg(feature = "prettyplease")]
178     /// Use `prettyplease` to format the bindings.
179     Prettyplease,
180 }
181 
182 impl Default for Formatter {
default() -> Self183     fn default() -> Self {
184         Self::Rustfmt
185     }
186 }
187 
188 impl FromStr for Formatter {
189     type Err = String;
190 
from_str(s: &str) -> Result<Self, Self::Err>191     fn from_str(s: &str) -> Result<Self, Self::Err> {
192         match s {
193             "none" => Ok(Self::None),
194             "rustfmt" => Ok(Self::Rustfmt),
195             #[cfg(feature = "prettyplease")]
196             "prettyplease" => Ok(Self::Prettyplease),
197             _ => Err(format!("`{}` is not a valid formatter", s)),
198         }
199     }
200 }
201 
202 impl std::fmt::Display for Formatter {
fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result203     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
204         let s = match self {
205             Self::None => "none",
206             Self::Rustfmt => "rustfmt",
207             #[cfg(feature = "prettyplease")]
208             Self::Prettyplease => "prettyplease",
209         };
210 
211         s.fmt(f)
212     }
213 }
214 
215 /// Configure and generate Rust bindings for a C/C++ header.
216 ///
217 /// This is the main entry point to the library.
218 ///
219 /// ```ignore
220 /// use bindgen::builder;
221 ///
222 /// // Configure and generate bindings.
223 /// let bindings = builder().header("path/to/input/header")
224 ///     .allowlist_type("SomeCoolClass")
225 ///     .allowlist_function("do_some_cool_thing")
226 ///     .generate()?;
227 ///
228 /// // Write the generated bindings to an output file.
229 /// bindings.write_to_file("path/to/output.rs")?;
230 /// ```
231 ///
232 /// # Enums
233 ///
234 /// Bindgen can map C/C++ enums into Rust in different ways. The way bindgen maps enums depends on
235 /// the pattern passed to several methods:
236 ///
237 /// 1. [`constified_enum_module()`](#method.constified_enum_module)
238 /// 2. [`bitfield_enum()`](#method.bitfield_enum)
239 /// 3. [`newtype_enum()`](#method.newtype_enum)
240 /// 4. [`rustified_enum()`](#method.rustified_enum)
241 ///
242 /// For each C enum, bindgen tries to match the pattern in the following order:
243 ///
244 /// 1. Constified enum module
245 /// 2. Bitfield enum
246 /// 3. Newtype enum
247 /// 4. Rustified enum
248 ///
249 /// If none of the above patterns match, then bindgen will generate a set of Rust constants.
250 ///
251 /// # Clang arguments
252 ///
253 /// Extra arguments can be passed to with clang:
254 /// 1. [`clang_arg()`](#method.clang_arg): takes a single argument
255 /// 2. [`clang_args()`](#method.clang_args): takes an iterator of arguments
256 /// 3. `BINDGEN_EXTRA_CLANG_ARGS` environment variable: whitespace separate
257 ///    environment variable of arguments
258 ///
259 /// Clang arguments specific to your crate should be added via the
260 /// `clang_arg()`/`clang_args()` methods.
261 ///
262 /// End-users of the crate may need to set the `BINDGEN_EXTRA_CLANG_ARGS` environment variable to
263 /// add additional arguments. For example, to build against a different sysroot a user could set
264 /// `BINDGEN_EXTRA_CLANG_ARGS` to `--sysroot=/path/to/sysroot`.
265 ///
266 /// # Regular expression arguments
267 ///
268 /// Some [`Builder`] methods, such as `allowlist_*` and `blocklist_*`, allow regular
269 /// expressions as arguments. These regular expressions will be enclosed in parentheses and
270 /// anchored with `^` and `$`. So, if the argument passed is `<regex>`, the regular expression to be
271 /// stored will be `^(<regex>)$`.
272 ///
273 /// As a consequence, regular expressions passed to `bindgen` will try to match the whole name of
274 /// an item instead of a section of it, which means that to match any items with the prefix
275 /// `prefix`, the `prefix.*` regular expression must be used.
276 ///
277 /// Certain methods, like [`Builder::allowlist_function`], use regular expressions over function
278 /// names. To match C++ methods, prefix the name of the type where they belong, followed by an
279 /// underscore. So, if the type `Foo` has a method `bar`, it can be matched with the `Foo_bar`
280 /// regular expression.
281 ///
282 /// Additionally, Objective-C interfaces can be matched by prefixing the regular expression with
283 /// `I`. For example, the `IFoo` regular expression matches the `Foo` interface, and the `IFoo_foo`
284 /// regular expression matches the `foo` method of the `Foo` interface.
285 ///
286 /// Releases of `bindgen` with a version lesser or equal to `0.62.0` used to accept the wildcard
287 /// pattern `*` as a valid regular expression. This behavior has been deprecated, and the `.*`
288 /// regular expression must be used instead.
289 #[derive(Debug, Default, Clone)]
290 pub struct Builder {
291     options: BindgenOptions,
292 }
293 
294 /// Construct a new [`Builder`](./struct.Builder.html).
builder() -> Builder295 pub fn builder() -> Builder {
296     Default::default()
297 }
298 
get_extra_clang_args( parse_callbacks: &[Rc<dyn callbacks::ParseCallbacks>], ) -> Vec<String>299 fn get_extra_clang_args(
300     parse_callbacks: &[Rc<dyn callbacks::ParseCallbacks>],
301 ) -> Vec<String> {
302     // Add any extra arguments from the environment to the clang command line.
303     let extra_clang_args = match get_target_dependent_env_var(
304         parse_callbacks,
305         "BINDGEN_EXTRA_CLANG_ARGS",
306     ) {
307         None => return vec![],
308         Some(s) => s,
309     };
310 
311     // Try to parse it with shell quoting. If we fail, make it one single big argument.
312     if let Some(strings) = shlex::split(&extra_clang_args) {
313         return strings;
314     }
315     vec![extra_clang_args]
316 }
317 
318 impl Builder {
319     /// Generate the Rust bindings using the options built up thus far.
generate(mut self) -> Result<Bindings, BindgenError>320     pub fn generate(mut self) -> Result<Bindings, BindgenError> {
321         // Add any extra arguments from the environment to the clang command line.
322         self.options.clang_args.extend(
323             get_extra_clang_args(&self.options.parse_callbacks)
324                 .into_iter()
325                 .map(String::into_boxed_str),
326         );
327 
328         for header in &self.options.input_headers {
329             self.options
330                 .for_each_callback(|cb| cb.header_file(header.as_ref()));
331         }
332 
333         // Transform input headers to arguments on the clang command line.
334         self.options.clang_args.extend(
335             self.options.input_headers
336                 [..self.options.input_headers.len().saturating_sub(1)]
337                 .iter()
338                 .flat_map(|header| ["-include".into(), header.clone()]),
339         );
340 
341         let input_unsaved_files =
342             std::mem::take(&mut self.options.input_header_contents)
343                 .into_iter()
344                 .map(|(name, contents)| {
345                     clang::UnsavedFile::new(name.as_ref(), contents.as_ref())
346                 })
347                 .collect::<Vec<_>>();
348 
349         Bindings::generate(self.options, input_unsaved_files)
350     }
351 
352     /// Preprocess and dump the input header files to disk.
353     ///
354     /// This is useful when debugging bindgen, using C-Reduce, or when filing
355     /// issues. The resulting file will be named something like `__bindgen.i` or
356     /// `__bindgen.ii`
dump_preprocessed_input(&self) -> io::Result<()>357     pub fn dump_preprocessed_input(&self) -> io::Result<()> {
358         let clang =
359             clang_sys::support::Clang::find(None, &[]).ok_or_else(|| {
360                 io::Error::new(
361                     io::ErrorKind::Other,
362                     "Cannot find clang executable",
363                 )
364             })?;
365 
366         // The contents of a wrapper file that includes all the input header
367         // files.
368         let mut wrapper_contents = String::new();
369 
370         // Whether we are working with C or C++ inputs.
371         let mut is_cpp = args_are_cpp(&self.options.clang_args);
372 
373         // For each input header, add `#include "$header"`.
374         for header in &self.options.input_headers {
375             is_cpp |= file_is_cpp(header);
376 
377             wrapper_contents.push_str("#include \"");
378             wrapper_contents.push_str(header);
379             wrapper_contents.push_str("\"\n");
380         }
381 
382         // For each input header content, add a prefix line of `#line 0 "$name"`
383         // followed by the contents.
384         for (name, contents) in &self.options.input_header_contents {
385             is_cpp |= file_is_cpp(name);
386 
387             wrapper_contents.push_str("#line 0 \"");
388             wrapper_contents.push_str(name);
389             wrapper_contents.push_str("\"\n");
390             wrapper_contents.push_str(contents);
391         }
392 
393         let wrapper_path = PathBuf::from(if is_cpp {
394             "__bindgen.cpp"
395         } else {
396             "__bindgen.c"
397         });
398 
399         {
400             let mut wrapper_file = File::create(&wrapper_path)?;
401             wrapper_file.write_all(wrapper_contents.as_bytes())?;
402         }
403 
404         let mut cmd = Command::new(clang.path);
405         cmd.arg("-save-temps")
406             .arg("-E")
407             .arg("-C")
408             .arg("-c")
409             .arg(&wrapper_path)
410             .stdout(Stdio::piped());
411 
412         for a in &self.options.clang_args {
413             cmd.arg(a.as_ref());
414         }
415 
416         for a in get_extra_clang_args(&self.options.parse_callbacks) {
417             cmd.arg(a);
418         }
419 
420         let mut child = cmd.spawn()?;
421 
422         let mut preprocessed = child.stdout.take().unwrap();
423         let mut file = File::create(if is_cpp {
424             "__bindgen.ii"
425         } else {
426             "__bindgen.i"
427         })?;
428         io::copy(&mut preprocessed, &mut file)?;
429 
430         if child.wait()?.success() {
431             Ok(())
432         } else {
433             Err(io::Error::new(
434                 io::ErrorKind::Other,
435                 "clang exited with non-zero status",
436             ))
437         }
438     }
439 }
440 
441 impl BindgenOptions {
build(&mut self)442     fn build(&mut self) {
443         const REGEX_SETS_LEN: usize = 28;
444 
445         let regex_sets: [_; REGEX_SETS_LEN] = [
446             &mut self.blocklisted_types,
447             &mut self.blocklisted_functions,
448             &mut self.blocklisted_items,
449             &mut self.blocklisted_files,
450             &mut self.opaque_types,
451             &mut self.allowlisted_vars,
452             &mut self.allowlisted_types,
453             &mut self.allowlisted_functions,
454             &mut self.allowlisted_files,
455             &mut self.allowlisted_items,
456             &mut self.bitfield_enums,
457             &mut self.constified_enums,
458             &mut self.constified_enum_modules,
459             &mut self.newtype_enums,
460             &mut self.newtype_global_enums,
461             &mut self.rustified_enums,
462             &mut self.rustified_non_exhaustive_enums,
463             &mut self.type_alias,
464             &mut self.new_type_alias,
465             &mut self.new_type_alias_deref,
466             &mut self.bindgen_wrapper_union,
467             &mut self.manually_drop_union,
468             &mut self.no_partialeq_types,
469             &mut self.no_copy_types,
470             &mut self.no_debug_types,
471             &mut self.no_default_types,
472             &mut self.no_hash_types,
473             &mut self.must_use_types,
474         ];
475 
476         let record_matches = self.record_matches;
477         #[cfg(feature = "experimental")]
478         {
479             let sets_len = REGEX_SETS_LEN + self.abi_overrides.len();
480             let names = if self.emit_diagnostics {
481                 <[&str; REGEX_SETS_LEN]>::into_iter([
482                     "--blocklist-type",
483                     "--blocklist-function",
484                     "--blocklist-item",
485                     "--blocklist-file",
486                     "--opaque-type",
487                     "--allowlist-type",
488                     "--allowlist-function",
489                     "--allowlist-var",
490                     "--allowlist-file",
491                     "--allowlist-item",
492                     "--bitfield-enum",
493                     "--newtype-enum",
494                     "--newtype-global-enum",
495                     "--rustified-enum",
496                     "--rustified-enum-non-exhaustive",
497                     "--constified-enum-module",
498                     "--constified-enum",
499                     "--type-alias",
500                     "--new-type-alias",
501                     "--new-type-alias-deref",
502                     "--bindgen-wrapper-union",
503                     "--manually-drop-union",
504                     "--no-partialeq",
505                     "--no-copy",
506                     "--no-debug",
507                     "--no-default",
508                     "--no-hash",
509                     "--must-use",
510                 ])
511                 .chain((0..self.abi_overrides.len()).map(|_| "--override-abi"))
512                 .map(Some)
513                 .collect()
514             } else {
515                 vec![None; sets_len]
516             };
517 
518             for (regex_set, name) in
519                 self.abi_overrides.values_mut().chain(regex_sets).zip(names)
520             {
521                 regex_set.build_with_diagnostics(record_matches, name);
522             }
523         }
524         #[cfg(not(feature = "experimental"))]
525         for regex_set in self.abi_overrides.values_mut().chain(regex_sets) {
526             regex_set.build(record_matches);
527         }
528 
529         let rust_target = self.rust_target;
530         #[allow(deprecated)]
531         if rust_target <= RustTarget::Stable_1_30 {
532             deprecated_target_diagnostic(rust_target, self);
533         }
534 
535         // Disable `untagged_union` if the target does not support it.
536         if !self.rust_features.untagged_union {
537             self.untagged_union = false;
538         }
539     }
540 
541     /// Update rust target version
set_rust_target(&mut self, rust_target: RustTarget)542     pub fn set_rust_target(&mut self, rust_target: RustTarget) {
543         self.rust_target = rust_target;
544 
545         // Keep rust_features synced with rust_target
546         self.rust_features = rust_target.into();
547     }
548 
549     /// Get features supported by target Rust version
rust_features(&self) -> RustFeatures550     pub fn rust_features(&self) -> RustFeatures {
551         self.rust_features
552     }
553 
last_callback<T>( &self, f: impl Fn(&dyn callbacks::ParseCallbacks) -> Option<T>, ) -> Option<T>554     fn last_callback<T>(
555         &self,
556         f: impl Fn(&dyn callbacks::ParseCallbacks) -> Option<T>,
557     ) -> Option<T> {
558         self.parse_callbacks
559             .iter()
560             .filter_map(|cb| f(cb.as_ref()))
561             .last()
562     }
563 
all_callbacks<T>( &self, f: impl Fn(&dyn callbacks::ParseCallbacks) -> Vec<T>, ) -> Vec<T>564     fn all_callbacks<T>(
565         &self,
566         f: impl Fn(&dyn callbacks::ParseCallbacks) -> Vec<T>,
567     ) -> Vec<T> {
568         self.parse_callbacks
569             .iter()
570             .flat_map(|cb| f(cb.as_ref()))
571             .collect()
572     }
573 
for_each_callback(&self, f: impl Fn(&dyn callbacks::ParseCallbacks))574     fn for_each_callback(&self, f: impl Fn(&dyn callbacks::ParseCallbacks)) {
575         self.parse_callbacks.iter().for_each(|cb| f(cb.as_ref()));
576     }
577 
process_comment(&self, comment: &str) -> String578     fn process_comment(&self, comment: &str) -> String {
579         let comment = comment::preprocess(comment);
580         self.parse_callbacks
581             .last()
582             .and_then(|cb| cb.process_comment(&comment))
583             .unwrap_or(comment)
584     }
585 }
586 
deprecated_target_diagnostic(target: RustTarget, _options: &BindgenOptions)587 fn deprecated_target_diagnostic(target: RustTarget, _options: &BindgenOptions) {
588     warn!("The {} Rust target is deprecated. If you have a need to use this target please report it at https://github.com/rust-lang/rust-bindgen/issues", target);
589 
590     #[cfg(feature = "experimental")]
591     if _options.emit_diagnostics {
592         use crate::diagnostics::{Diagnostic, Level};
593 
594         let mut diagnostic = Diagnostic::default();
595         diagnostic.with_title(
596             format!("The {} Rust target is deprecated.", target),
597             Level::Warn,
598         );
599         diagnostic.add_annotation(
600             "This Rust target was passed to `--rust-target`",
601             Level::Info,
602         );
603         diagnostic.add_annotation("If you have a good reason to use this target please report it at https://github.com/rust-lang/rust-bindgen/issues", Level::Help);
604         diagnostic.display();
605     }
606 }
607 
608 #[cfg(feature = "runtime")]
ensure_libclang_is_loaded()609 fn ensure_libclang_is_loaded() {
610     if clang_sys::is_loaded() {
611         return;
612     }
613 
614     // XXX (issue #350): Ensure that our dynamically loaded `libclang`
615     // doesn't get dropped prematurely, nor is loaded multiple times
616     // across different threads.
617 
618     lazy_static! {
619         static ref LIBCLANG: std::sync::Arc<clang_sys::SharedLibrary> = {
620             clang_sys::load().expect("Unable to find libclang");
621             clang_sys::get_library().expect(
622                 "We just loaded libclang and it had better still be \
623                  here!",
624             )
625         };
626     }
627 
628     clang_sys::set_library(Some(LIBCLANG.clone()));
629 }
630 
631 #[cfg(not(feature = "runtime"))]
ensure_libclang_is_loaded()632 fn ensure_libclang_is_loaded() {}
633 
634 /// Error type for rust-bindgen.
635 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
636 #[non_exhaustive]
637 pub enum BindgenError {
638     /// The header was a folder.
639     FolderAsHeader(PathBuf),
640     /// Permissions to read the header is insufficient.
641     InsufficientPermissions(PathBuf),
642     /// The header does not exist.
643     NotExist(PathBuf),
644     /// Clang diagnosed an error.
645     ClangDiagnostic(String),
646     /// Code generation reported an error.
647     Codegen(CodegenError),
648 }
649 
650 impl std::fmt::Display for BindgenError {
fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result651     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
652         match self {
653             BindgenError::FolderAsHeader(h) => {
654                 write!(f, "'{}' is a folder", h.display())
655             }
656             BindgenError::InsufficientPermissions(h) => {
657                 write!(f, "insufficient permissions to read '{}'", h.display())
658             }
659             BindgenError::NotExist(h) => {
660                 write!(f, "header '{}' does not exist.", h.display())
661             }
662             BindgenError::ClangDiagnostic(message) => {
663                 write!(f, "clang diagnosed error: {}", message)
664             }
665             BindgenError::Codegen(err) => {
666                 write!(f, "codegen error: {}", err)
667             }
668         }
669     }
670 }
671 
672 impl std::error::Error for BindgenError {}
673 
674 /// Generated Rust bindings.
675 #[derive(Debug)]
676 pub struct Bindings {
677     options: BindgenOptions,
678     module: proc_macro2::TokenStream,
679 }
680 
681 pub(crate) const HOST_TARGET: &str =
682     include_str!(concat!(env!("OUT_DIR"), "/host-target.txt"));
683 
684 // Some architecture triplets are different between rust and libclang, see #1211
685 // and duplicates.
rust_to_clang_target(rust_target: &str) -> Box<str>686 fn rust_to_clang_target(rust_target: &str) -> Box<str> {
687     if rust_target.starts_with("aarch64-apple-") {
688         let mut clang_target = "arm64-apple-".to_owned();
689         clang_target
690             .push_str(rust_target.strip_prefix("aarch64-apple-").unwrap());
691         return clang_target.into();
692     } else if rust_target.starts_with("riscv64gc-") {
693         let mut clang_target = "riscv64-".to_owned();
694         clang_target.push_str(rust_target.strip_prefix("riscv64gc-").unwrap());
695         return clang_target.into();
696     } else if rust_target.ends_with("-espidf") {
697         let mut clang_target =
698             rust_target.strip_suffix("-espidf").unwrap().to_owned();
699         clang_target.push_str("-elf");
700         if clang_target.starts_with("riscv32imc-") {
701             clang_target = "riscv32-".to_owned() +
702                 clang_target.strip_prefix("riscv32imc-").unwrap();
703         }
704         return clang_target.into();
705     } else if rust_target.starts_with("riscv32imc-") {
706         let mut clang_target = "riscv32-".to_owned();
707         clang_target.push_str(rust_target.strip_prefix("riscv32imc-").unwrap());
708         return clang_target.into();
709     } else if rust_target.starts_with("riscv32imac-") {
710         let mut clang_target = "riscv32-".to_owned();
711         clang_target
712             .push_str(rust_target.strip_prefix("riscv32imac-").unwrap());
713         return clang_target.into();
714     }
715     rust_target.into()
716 }
717 
718 /// Returns the effective target, and whether it was explicitly specified on the
719 /// clang flags.
find_effective_target(clang_args: &[Box<str>]) -> (Box<str>, bool)720 fn find_effective_target(clang_args: &[Box<str>]) -> (Box<str>, bool) {
721     let mut args = clang_args.iter();
722     while let Some(opt) = args.next() {
723         if opt.starts_with("--target=") {
724             let mut split = opt.split('=');
725             split.next();
726             return (split.next().unwrap().into(), true);
727         }
728 
729         if opt.as_ref() == "-target" {
730             if let Some(target) = args.next() {
731                 return (target.clone(), true);
732             }
733         }
734     }
735 
736     // If we're running from a build script, try to find the cargo target.
737     if let Ok(t) = env::var("TARGET") {
738         return (rust_to_clang_target(&t), false);
739     }
740 
741     (rust_to_clang_target(HOST_TARGET), false)
742 }
743 
744 impl Bindings {
745     /// Generate bindings for the given options.
generate( mut options: BindgenOptions, input_unsaved_files: Vec<clang::UnsavedFile>, ) -> Result<Bindings, BindgenError>746     pub(crate) fn generate(
747         mut options: BindgenOptions,
748         input_unsaved_files: Vec<clang::UnsavedFile>,
749     ) -> Result<Bindings, BindgenError> {
750         ensure_libclang_is_loaded();
751 
752         #[cfg(feature = "runtime")]
753         debug!(
754             "Generating bindings, libclang at {}",
755             clang_sys::get_library().unwrap().path().display()
756         );
757         #[cfg(not(feature = "runtime"))]
758         debug!("Generating bindings, libclang linked");
759 
760         options.build();
761 
762         let (effective_target, explicit_target) =
763             find_effective_target(&options.clang_args);
764 
765         let is_host_build =
766             rust_to_clang_target(HOST_TARGET) == effective_target;
767 
768         // NOTE: The is_host_build check wouldn't be sound normally in some
769         // cases if we were to call a binary (if you have a 32-bit clang and are
770         // building on a 64-bit system for example).  But since we rely on
771         // opening libclang.so, it has to be the same architecture and thus the
772         // check is fine.
773         if !explicit_target && !is_host_build {
774             options.clang_args.insert(
775                 0,
776                 format!("--target={}", effective_target).into_boxed_str(),
777             );
778         };
779 
780         fn detect_include_paths(options: &mut BindgenOptions) {
781             if !options.detect_include_paths {
782                 return;
783             }
784 
785             // Filter out include paths and similar stuff, so we don't incorrectly
786             // promote them to `-isystem`.
787             let clang_args_for_clang_sys = {
788                 let mut last_was_include_prefix = false;
789                 options
790                     .clang_args
791                     .iter()
792                     .filter(|arg| {
793                         if last_was_include_prefix {
794                             last_was_include_prefix = false;
795                             return false;
796                         }
797 
798                         let arg = arg.as_ref();
799 
800                         // https://clang.llvm.org/docs/ClangCommandLineReference.html
801                         // -isystem and -isystem-after are harmless.
802                         if arg == "-I" || arg == "--include-directory" {
803                             last_was_include_prefix = true;
804                             return false;
805                         }
806 
807                         if arg.starts_with("-I") ||
808                             arg.starts_with("--include-directory=")
809                         {
810                             return false;
811                         }
812 
813                         true
814                     })
815                     .map(|arg| arg.clone().into())
816                     .collect::<Vec<_>>()
817             };
818 
819             debug!(
820                 "Trying to find clang with flags: {:?}",
821                 clang_args_for_clang_sys
822             );
823 
824             let clang = match clang_sys::support::Clang::find(
825                 None,
826                 &clang_args_for_clang_sys,
827             ) {
828                 None => return,
829                 Some(clang) => clang,
830             };
831 
832             debug!("Found clang: {:?}", clang);
833 
834             // Whether we are working with C or C++ inputs.
835             let is_cpp = args_are_cpp(&options.clang_args) ||
836                 options.input_headers.iter().any(|h| file_is_cpp(h));
837 
838             let search_paths = if is_cpp {
839                 clang.cpp_search_paths
840             } else {
841                 clang.c_search_paths
842             };
843 
844             if let Some(search_paths) = search_paths {
845                 for path in search_paths.into_iter() {
846                     if let Ok(path) = path.into_os_string().into_string() {
847                         options.clang_args.push("-isystem".into());
848                         options.clang_args.push(path.into_boxed_str());
849                     }
850                 }
851             }
852         }
853 
854         detect_include_paths(&mut options);
855 
856         #[cfg(unix)]
857         fn can_read(perms: &std::fs::Permissions) -> bool {
858             use std::os::unix::fs::PermissionsExt;
859             perms.mode() & 0o444 > 0
860         }
861 
862         #[cfg(not(unix))]
863         fn can_read(_: &std::fs::Permissions) -> bool {
864             true
865         }
866 
867         if let Some(h) = options.input_headers.last() {
868             let path = Path::new(h.as_ref());
869             if let Ok(md) = std::fs::metadata(path) {
870                 if md.is_dir() {
871                     return Err(BindgenError::FolderAsHeader(path.into()));
872                 }
873                 if !can_read(&md.permissions()) {
874                     return Err(BindgenError::InsufficientPermissions(
875                         path.into(),
876                     ));
877                 }
878                 options.clang_args.push(h.clone());
879             } else {
880                 return Err(BindgenError::NotExist(path.into()));
881             }
882         }
883 
884         for (idx, f) in input_unsaved_files.iter().enumerate() {
885             if idx != 0 || !options.input_headers.is_empty() {
886                 options.clang_args.push("-include".into());
887             }
888             options.clang_args.push(f.name.to_str().unwrap().into())
889         }
890 
891         debug!("Fixed-up options: {:?}", options);
892 
893         let time_phases = options.time_phases;
894         let mut context = BindgenContext::new(options, &input_unsaved_files);
895 
896         if is_host_build {
897             debug_assert_eq!(
898                 context.target_pointer_size(),
899                 std::mem::size_of::<*mut ()>(),
900                 "{:?} {:?}",
901                 effective_target,
902                 HOST_TARGET
903             );
904         }
905 
906         {
907             let _t = time::Timer::new("parse").with_output(time_phases);
908             parse(&mut context)?;
909         }
910 
911         let (module, options) =
912             codegen::codegen(context).map_err(BindgenError::Codegen)?;
913 
914         Ok(Bindings { options, module })
915     }
916 
917     /// Write these bindings as source text to a file.
write_to_file<P: AsRef<Path>>(&self, path: P) -> io::Result<()>918     pub fn write_to_file<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
919         let file = OpenOptions::new()
920             .write(true)
921             .truncate(true)
922             .create(true)
923             .open(path.as_ref())?;
924         self.write(Box::new(file))?;
925         Ok(())
926     }
927 
928     /// Write these bindings as source text to the given `Write`able.
write<'a>(&self, mut writer: Box<dyn Write + 'a>) -> io::Result<()>929     pub fn write<'a>(&self, mut writer: Box<dyn Write + 'a>) -> io::Result<()> {
930         if !self.options.disable_header_comment {
931             let version =
932                 Some("0.69.1").unwrap_or("(unknown version)");
933             let header = format!(
934                 "/* automatically generated by rust-bindgen {version} */\n\n",
935             );
936             writer.write_all(header.as_bytes())?;
937         }
938 
939         for line in self.options.raw_lines.iter() {
940             writer.write_all(line.as_bytes())?;
941             writer.write_all("\n".as_bytes())?;
942         }
943 
944         if !self.options.raw_lines.is_empty() {
945             writer.write_all("\n".as_bytes())?;
946         }
947 
948         match self.format_tokens(&self.module) {
949             Ok(formatted_bindings) => {
950                 writer.write_all(formatted_bindings.as_bytes())?;
951             }
952             Err(err) => {
953                 eprintln!(
954                     "Failed to run rustfmt: {} (non-fatal, continuing)",
955                     err
956                 );
957                 writer.write_all(self.module.to_string().as_bytes())?;
958             }
959         }
960         Ok(())
961     }
962 
963     /// Gets the rustfmt path to rustfmt the generated bindings.
rustfmt_path(&self) -> io::Result<Cow<PathBuf>>964     fn rustfmt_path(&self) -> io::Result<Cow<PathBuf>> {
965         debug_assert!(matches!(self.options.formatter, Formatter::Rustfmt));
966         if let Some(ref p) = self.options.rustfmt_path {
967             return Ok(Cow::Borrowed(p));
968         }
969         if let Ok(rustfmt) = env::var("RUSTFMT") {
970             return Ok(Cow::Owned(rustfmt.into()));
971         }
972         #[cfg(feature = "which-rustfmt")]
973         match which::which("rustfmt") {
974             Ok(p) => Ok(Cow::Owned(p)),
975             Err(e) => {
976                 Err(io::Error::new(io::ErrorKind::Other, format!("{}", e)))
977             }
978         }
979         #[cfg(not(feature = "which-rustfmt"))]
980         // No rustfmt binary was specified, so assume that the binary is called
981         // "rustfmt" and that it is in the user's PATH.
982         Ok(Cow::Owned("rustfmt".into()))
983     }
984 
985     /// Formats a token stream with the formatter set up in `BindgenOptions`.
format_tokens( &self, tokens: &proc_macro2::TokenStream, ) -> io::Result<String>986     fn format_tokens(
987         &self,
988         tokens: &proc_macro2::TokenStream,
989     ) -> io::Result<String> {
990         let _t = time::Timer::new("rustfmt_generated_string")
991             .with_output(self.options.time_phases);
992 
993         match self.options.formatter {
994             Formatter::None => return Ok(tokens.to_string()),
995             #[cfg(feature = "prettyplease")]
996             Formatter::Prettyplease => {
997                 return Ok(prettyplease::unparse(&syn::parse_quote!(#tokens)));
998             }
999             Formatter::Rustfmt => (),
1000         }
1001 
1002         let rustfmt = self.rustfmt_path()?;
1003         let mut cmd = Command::new(&*rustfmt);
1004 
1005         cmd.stdin(Stdio::piped()).stdout(Stdio::piped());
1006 
1007         if let Some(path) = self
1008             .options
1009             .rustfmt_configuration_file
1010             .as_ref()
1011             .and_then(|f| f.to_str())
1012         {
1013             cmd.args(["--config-path", path]);
1014         }
1015 
1016         let mut child = cmd.spawn()?;
1017         let mut child_stdin = child.stdin.take().unwrap();
1018         let mut child_stdout = child.stdout.take().unwrap();
1019 
1020         let source = tokens.to_string();
1021 
1022         // Write to stdin in a new thread, so that we can read from stdout on this
1023         // thread. This keeps the child from blocking on writing to its stdout which
1024         // might block us from writing to its stdin.
1025         let stdin_handle = ::std::thread::spawn(move || {
1026             let _ = child_stdin.write_all(source.as_bytes());
1027             source
1028         });
1029 
1030         let mut output = vec![];
1031         io::copy(&mut child_stdout, &mut output)?;
1032 
1033         let status = child.wait()?;
1034         let source = stdin_handle.join().expect(
1035             "The thread writing to rustfmt's stdin doesn't do \
1036              anything that could panic",
1037         );
1038 
1039         match String::from_utf8(output) {
1040             Ok(bindings) => match status.code() {
1041                 Some(0) => Ok(bindings),
1042                 Some(2) => Err(io::Error::new(
1043                     io::ErrorKind::Other,
1044                     "Rustfmt parsing errors.".to_string(),
1045                 )),
1046                 Some(3) => {
1047                     rustfmt_non_fatal_error_diagnostic(
1048                         "Rustfmt could not format some lines",
1049                         &self.options,
1050                     );
1051                     Ok(bindings)
1052                 }
1053                 _ => Err(io::Error::new(
1054                     io::ErrorKind::Other,
1055                     "Internal rustfmt error".to_string(),
1056                 )),
1057             },
1058             _ => Ok(source),
1059         }
1060     }
1061 }
1062 
rustfmt_non_fatal_error_diagnostic(msg: &str, _options: &BindgenOptions)1063 fn rustfmt_non_fatal_error_diagnostic(msg: &str, _options: &BindgenOptions) {
1064     warn!("{}", msg);
1065 
1066     #[cfg(feature = "experimental")]
1067     if _options.emit_diagnostics {
1068         use crate::diagnostics::{Diagnostic, Level};
1069 
1070         Diagnostic::default()
1071             .with_title(msg, Level::Warn)
1072             .add_annotation(
1073                 "The bindings will be generated but not formatted.",
1074                 Level::Note,
1075             )
1076             .display();
1077     }
1078 }
1079 
1080 impl std::fmt::Display for Bindings {
fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result1081     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1082         let mut bytes = vec![];
1083         self.write(Box::new(&mut bytes) as Box<dyn Write>)
1084             .expect("writing to a vec cannot fail");
1085         f.write_str(
1086             std::str::from_utf8(&bytes)
1087                 .expect("we should only write bindings that are valid utf-8"),
1088         )
1089     }
1090 }
1091 
1092 /// Determines whether the given cursor is in any of the files matched by the
1093 /// options.
filter_builtins(ctx: &BindgenContext, cursor: &clang::Cursor) -> bool1094 fn filter_builtins(ctx: &BindgenContext, cursor: &clang::Cursor) -> bool {
1095     ctx.options().builtins || !cursor.is_builtin()
1096 }
1097 
1098 /// Parse one `Item` from the Clang cursor.
parse_one( ctx: &mut BindgenContext, cursor: clang::Cursor, parent: Option<ItemId>, )1099 fn parse_one(
1100     ctx: &mut BindgenContext,
1101     cursor: clang::Cursor,
1102     parent: Option<ItemId>,
1103 ) {
1104     if !filter_builtins(ctx, &cursor) {
1105         return;
1106     }
1107 
1108     match Item::parse(cursor, parent, ctx) {
1109         Ok(..) => {}
1110         Err(ParseError::Continue) => {}
1111         Err(ParseError::Recurse) => {
1112             cursor
1113                 .visit_sorted(ctx, |ctx, child| parse_one(ctx, child, parent));
1114         }
1115     }
1116 }
1117 
1118 /// Parse the Clang AST into our `Item` internal representation.
parse(context: &mut BindgenContext) -> Result<(), BindgenError>1119 fn parse(context: &mut BindgenContext) -> Result<(), BindgenError> {
1120     use clang_sys::*;
1121 
1122     let mut error = None;
1123     for d in context.translation_unit().diags().iter() {
1124         let msg = d.format();
1125         let is_err = d.severity() >= CXDiagnostic_Error;
1126         if is_err {
1127             let error = error.get_or_insert_with(String::new);
1128             error.push_str(&msg);
1129             error.push('\n');
1130         } else {
1131             eprintln!("clang diag: {}", msg);
1132         }
1133     }
1134 
1135     if let Some(message) = error {
1136         return Err(BindgenError::ClangDiagnostic(message));
1137     }
1138 
1139     let cursor = context.translation_unit().cursor();
1140 
1141     if context.options().emit_ast {
1142         fn dump_if_not_builtin(cur: &clang::Cursor) -> CXChildVisitResult {
1143             if !cur.is_builtin() {
1144                 clang::ast_dump(cur, 0)
1145             } else {
1146                 CXChildVisit_Continue
1147             }
1148         }
1149         cursor.visit(|cur| dump_if_not_builtin(&cur));
1150     }
1151 
1152     let root = context.root_module();
1153     context.with_module(root, |ctx| {
1154         cursor.visit_sorted(ctx, |ctx, child| parse_one(ctx, child, None))
1155     });
1156 
1157     assert!(
1158         context.current_module() == context.root_module(),
1159         "How did this happen?"
1160     );
1161     Ok(())
1162 }
1163 
1164 /// Extracted Clang version data
1165 #[derive(Debug)]
1166 pub struct ClangVersion {
1167     /// Major and minor semver, if parsing was successful
1168     pub parsed: Option<(u32, u32)>,
1169     /// full version string
1170     pub full: String,
1171 }
1172 
1173 /// Get the major and the minor semver numbers of Clang's version
clang_version() -> ClangVersion1174 pub fn clang_version() -> ClangVersion {
1175     ensure_libclang_is_loaded();
1176 
1177     //Debian clang version 11.0.1-2
1178     let raw_v: String = clang::extract_clang_version();
1179     let split_v: Option<Vec<&str>> = raw_v
1180         .split_whitespace()
1181         .find(|t| t.chars().next().map_or(false, |v| v.is_ascii_digit()))
1182         .map(|v| v.split('.').collect());
1183     if let Some(v) = split_v {
1184         if v.len() >= 2 {
1185             let maybe_major = v[0].parse::<u32>();
1186             let maybe_minor = v[1].parse::<u32>();
1187             if let (Ok(major), Ok(minor)) = (maybe_major, maybe_minor) {
1188                 return ClangVersion {
1189                     parsed: Some((major, minor)),
1190                     full: raw_v.clone(),
1191                 };
1192             }
1193         }
1194     };
1195     ClangVersion {
1196         parsed: None,
1197         full: raw_v.clone(),
1198     }
1199 }
1200 
env_var<K: AsRef<str> + AsRef<OsStr>>( parse_callbacks: &[Rc<dyn callbacks::ParseCallbacks>], key: K, ) -> Result<String, std::env::VarError>1201 fn env_var<K: AsRef<str> + AsRef<OsStr>>(
1202     parse_callbacks: &[Rc<dyn callbacks::ParseCallbacks>],
1203     key: K,
1204 ) -> Result<String, std::env::VarError> {
1205     for callback in parse_callbacks {
1206         callback.read_env_var(key.as_ref());
1207     }
1208     std::env::var(key)
1209 }
1210 
1211 /// Looks for the env var `var_${TARGET}`, and falls back to just `var` when it is not found.
get_target_dependent_env_var( parse_callbacks: &[Rc<dyn callbacks::ParseCallbacks>], var: &str, ) -> Option<String>1212 fn get_target_dependent_env_var(
1213     parse_callbacks: &[Rc<dyn callbacks::ParseCallbacks>],
1214     var: &str,
1215 ) -> Option<String> {
1216     if let Ok(target) = env_var(parse_callbacks, "TARGET") {
1217         if let Ok(v) = env_var(parse_callbacks, format!("{}_{}", var, target)) {
1218             return Some(v);
1219         }
1220         if let Ok(v) = env_var(
1221             parse_callbacks,
1222             format!("{}_{}", var, target.replace('-', "_")),
1223         ) {
1224             return Some(v);
1225         }
1226     }
1227 
1228     env_var(parse_callbacks, var).ok()
1229 }
1230 
1231 /// A ParseCallbacks implementation that will act on file includes by echoing a rerun-if-changed
1232 /// line and on env variable usage by echoing a rerun-if-env-changed line
1233 ///
1234 /// When running inside a `build.rs` script, this can be used to make cargo invalidate the
1235 /// generated bindings whenever any of the files included from the header change:
1236 /// ```
1237 /// use bindgen::builder;
1238 /// let bindings = builder()
1239 ///     .header("path/to/input/header")
1240 ///     .parse_callbacks(Box::new(bindgen::CargoCallbacks))
1241 ///     .generate();
1242 /// ```
1243 #[derive(Debug)]
1244 pub struct CargoCallbacks {
1245     rerun_on_header_files: bool,
1246 }
1247 
1248 /// Create a new `CargoCallbacks` value with [`CargoCallbacks::rerun_on_header_files`] disabled.
1249 ///
1250 /// This constructor has been deprecated in favor of [`CargoCallbacks::new`] where
1251 /// [`CargoCallbacks::rerun_on_header_files`] is enabled by default.
1252 #[deprecated = "Use `CargoCallbacks::new()` instead. Please, check the documentation for further information."]
1253 pub const CargoCallbacks: CargoCallbacks = CargoCallbacks {
1254     rerun_on_header_files: false,
1255 };
1256 
1257 impl CargoCallbacks {
1258     /// Create a new `CargoCallbacks` value.
new() -> Self1259     pub fn new() -> Self {
1260         Self {
1261             rerun_on_header_files: true,
1262         }
1263     }
1264 
1265     /// Whether Cargo should re-run the build script if any of the input header files has changed.
1266     ///
1267     /// This option is enabled by default unless the deprecated [`const@CargoCallbacks`]
1268     /// constructor is used.
rerun_on_header_files(mut self, doit: bool) -> Self1269     pub fn rerun_on_header_files(mut self, doit: bool) -> Self {
1270         self.rerun_on_header_files = doit;
1271         self
1272     }
1273 }
1274 
1275 impl Default for CargoCallbacks {
default() -> Self1276     fn default() -> Self {
1277         Self::new()
1278     }
1279 }
1280 
1281 impl callbacks::ParseCallbacks for CargoCallbacks {
header_file(&self, filename: &str)1282     fn header_file(&self, filename: &str) {
1283         if self.rerun_on_header_files {
1284             println!("cargo:rerun-if-changed={}", filename);
1285         }
1286     }
1287 
include_file(&self, filename: &str)1288     fn include_file(&self, filename: &str) {
1289         println!("cargo:rerun-if-changed={}", filename);
1290     }
1291 
read_env_var(&self, key: &str)1292     fn read_env_var(&self, key: &str) {
1293         println!("cargo:rerun-if-env-changed={}", key);
1294     }
1295 }
1296 
1297 /// Test command_line_flag function.
1298 #[test]
commandline_flag_unit_test_function()1299 fn commandline_flag_unit_test_function() {
1300     //Test 1
1301     let bindings = crate::builder();
1302     let command_line_flags = bindings.command_line_flags();
1303 
1304     let test_cases = [
1305         "--rust-target",
1306         "--no-derive-default",
1307         "--generate",
1308         "functions,types,vars,methods,constructors,destructors",
1309     ]
1310     .iter()
1311     .map(|&x| x.into())
1312     .collect::<Vec<String>>();
1313 
1314     assert!(test_cases.iter().all(|x| command_line_flags.contains(x)));
1315 
1316     //Test 2
1317     let bindings = crate::builder()
1318         .header("input_header")
1319         .allowlist_type("Distinct_Type")
1320         .allowlist_function("safe_function");
1321 
1322     let command_line_flags = bindings.command_line_flags();
1323     let test_cases = [
1324         "--rust-target",
1325         "input_header",
1326         "--no-derive-default",
1327         "--generate",
1328         "functions,types,vars,methods,constructors,destructors",
1329         "--allowlist-type",
1330         "Distinct_Type",
1331         "--allowlist-function",
1332         "safe_function",
1333     ]
1334     .iter()
1335     .map(|&x| x.into())
1336     .collect::<Vec<String>>();
1337     println!("{:?}", command_line_flags);
1338 
1339     assert!(test_cases.iter().all(|x| command_line_flags.contains(x)));
1340 }
1341 
1342 #[test]
test_rust_to_clang_target()1343 fn test_rust_to_clang_target() {
1344     assert_eq!(
1345         rust_to_clang_target("aarch64-apple-ios").as_ref(),
1346         "arm64-apple-ios"
1347     );
1348 }
1349 
1350 #[test]
test_rust_to_clang_target_riscv()1351 fn test_rust_to_clang_target_riscv() {
1352     assert_eq!(
1353         rust_to_clang_target("riscv64gc-unknown-linux-gnu").as_ref(),
1354         "riscv64-unknown-linux-gnu"
1355     );
1356     assert_eq!(
1357         rust_to_clang_target("riscv32imc-unknown-none-elf").as_ref(),
1358         "riscv32-unknown-none-elf"
1359     );
1360     assert_eq!(
1361         rust_to_clang_target("riscv32imac-unknown-none-elf").as_ref(),
1362         "riscv32-unknown-none-elf"
1363     );
1364 }
1365 
1366 #[test]
test_rust_to_clang_target_espidf()1367 fn test_rust_to_clang_target_espidf() {
1368     assert_eq!(
1369         rust_to_clang_target("riscv32imc-esp-espidf").as_ref(),
1370         "riscv32-esp-elf"
1371     );
1372     assert_eq!(
1373         rust_to_clang_target("xtensa-esp32-espidf").as_ref(),
1374         "xtensa-esp32-elf"
1375     );
1376 }
1377