#![deny(missing_docs)]
#![deny(warnings)]
#![deny(unused_extern_crates)]
#![allow(non_upper_case_globals)]
#![recursion_limit="128"]
extern crate cexpr;
#[macro_use]
#[allow(unused_extern_crates)]
extern crate cfg_if;
extern crate clang_sys;
#[macro_use]
extern crate lazy_static;
extern crate peeking_take_while;
#[macro_use]
extern crate quote;
extern crate regex;
extern crate which;
#[cfg(feature = "logging")]
#[macro_use]
extern crate log;
#[cfg(not(feature = "logging"))]
#[macro_use]
mod log_stubs;
#[macro_use]
mod extra_assertions;
macro_rules! doc_mod {
($m:ident, $doc_mod_name:ident) => {
cfg_if! {
if #[cfg(feature = "testing_only_docs")] {
pub mod $doc_mod_name {
pub use super::$m::*;
}
} else {
}
}
};
}
mod clang;
mod codegen;
mod features;
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);
pub use features::{LATEST_STABLE_RUST, RUST_TARGET_STRINGS, RustTarget};
use features::RustFeatures;
use ir::context::{BindgenContext, ItemId};
use ir::item::Item;
use parse::{ClangItemParser, ParseError};
use regex_set::RegexSet;
use std::borrow::Cow;
use std::fs::{File, OpenOptions};
use std::io::{self, Write};
use std::iter;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::Arc;
#[derive(Debug, Clone)]
pub struct CodegenConfig {
pub functions: bool,
pub types: bool,
pub vars: bool,
pub methods: bool,
pub constructors: bool,
pub destructors: bool,
}
impl CodegenConfig {
pub fn all() -> Self {
CodegenConfig {
functions: true,
types: true,
vars: true,
methods: true,
constructors: true,
destructors: true,
}
}
pub fn nothing() -> Self {
CodegenConfig {
functions: false,
types: false,
vars: false,
methods: false,
constructors: false,
destructors: false,
}
}
}
impl Default for CodegenConfig {
fn default() -> Self {
CodegenConfig::all()
}
}
#[derive(Debug, Default)]
pub struct Builder {
options: BindgenOptions,
input_headers: Vec<String>,
input_header_contents: Vec<(String, String)>,
}
pub fn builder() -> Builder {
Default::default()
}
impl Builder {
pub fn command_line_flags(&self) -> Vec<String> {
let mut output_vector: Vec<String> = Vec::new();
if let Some(header) = self.input_headers.last().cloned() {
output_vector.push(header);
}
output_vector.push(self.options.rust_target.into());
self.options
.bitfield_enums
.get_items()
.iter()
.map(|item| {
output_vector.push("--bitfield-enum".into());
output_vector.push(
item.trim_left_matches("^")
.trim_right_matches("$")
.into(),
);
})
.count();
self.options
.rustified_enums
.get_items()
.iter()
.map(|item| {
output_vector.push("--rustified-enum".into());
output_vector.push(
item.trim_left_matches("^")
.trim_right_matches("$")
.into(),
);
})
.count();
self.options
.constified_enum_modules
.get_items()
.iter()
.map(|item| {
output_vector.push("--constified-enum-module".into());
output_vector.push(
item.trim_left_matches("^")
.trim_right_matches("$")
.into(),
);
})
.count();
self.options
.blacklisted_types
.get_items()
.iter()
.map(|item| {
output_vector.push("--blacklist-type".into());
output_vector.push(
item.trim_left_matches("^")
.trim_right_matches("$")
.into(),
);
})
.count();
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.whitelist_recursively {
output_vector.push("--no-recursive-whitelist".into());
}
if self.options.objc_extern_crate {
output_vector.push("--objc-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.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.disable_name_namespacing {
output_vector.push("--disable-name-namespacing".into());
}
self.options
.links
.iter()
.map(|&(ref item, _)| {
output_vector.push("--framework".into());
output_vector.push(
item.trim_left_matches("^")
.trim_right_matches("$")
.into(),
);
})
.count();
if !self.options.codegen_config.functions {
output_vector.push("--ignore-functions".into());
}
output_vector.push("--generate".into());
let mut options: Vec<String> = Vec::new();
if self.options.codegen_config.functions {
options.push("function".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());
}
self.options
.links
.iter()
.map(|&(ref item, _)| {
output_vector.push("--clang-args".into());
output_vector.push(
item.trim_left_matches("^")
.trim_right_matches("$")
.into(),
);
})
.count();
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());
}
self.options
.opaque_types
.get_items()
.iter()
.map(|item| {
output_vector.push("--opaque-type".into());
output_vector.push(
item.trim_left_matches("^")
.trim_right_matches("$")
.into(),
);
})
.count();
self.options
.raw_lines
.iter()
.map(|item| {
output_vector.push("--raw-line".into());
output_vector.push(
item.trim_left_matches("^")
.trim_right_matches("$")
.into(),
);
})
.count();
self.options
.links
.iter()
.map(|&(ref item, _)| {
output_vector.push("--static".into());
output_vector.push(
item.trim_left_matches("^")
.trim_right_matches("$")
.into(),
);
})
.count();
if self.options.use_core {
output_vector.push("--use-core".into());
}
if self.options.conservative_inline_namespaces {
output_vector.push("--conservative-inline-namespaces".into());
}
self.options
.whitelisted_functions
.get_items()
.iter()
.map(|item| {
output_vector.push("--whitelist-function".into());
output_vector.push(
item.trim_left_matches("^")
.trim_right_matches("$")
.into(),
);
})
.count();
self.options
.whitelisted_types
.get_items()
.iter()
.map(|item| {
output_vector.push("--whitelist-type".into());
output_vector.push(
item.trim_left_matches("^")
.trim_right_matches("$")
.into(),
);
})
.count();
self.options
.whitelisted_vars
.get_items()
.iter()
.map(|item| {
output_vector.push("--whitelist-var".into());
output_vector.push(
item.trim_left_matches("^")
.trim_right_matches("$")
.into(),
);
})
.count();
output_vector.push("--".into());
if !self.options.clang_args.is_empty() {
output_vector.extend(self.options.clang_args.iter().cloned());
}
if self.input_headers.len() > 1 {
output_vector.extend(
self.input_headers[..self.input_headers.len() - 1]
.iter()
.cloned(),
);
}
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());
}
self.options
.no_partialeq_types
.get_items()
.iter()
.map(|item| {
output_vector.push("--no-partialeq".into());
output_vector.push(
item.trim_left_matches("^")
.trim_right_matches("$")
.into(),
);
})
.count();
self.options
.no_copy_types
.get_items()
.iter()
.map(|item| {
output_vector.push("--no-copy".into());
output_vector.push(
item.trim_left_matches("^")
.trim_right_matches("$")
.into(),
);
})
.count();
self.options
.no_hash_types
.get_items()
.iter()
.map(|item| {
output_vector.push("--no-hash".into());
output_vector.push(
item.trim_left_matches("^")
.trim_right_matches("$")
.into(),
);
})
.count();
output_vector
}
pub fn header<T: Into<String>>(mut self, header: T) -> Builder {
self.input_headers.push(header.into());
self
}
pub fn header_contents(mut self, name: &str, contents: &str) -> Builder {
self.input_header_contents.push(
(name.into(), contents.into()),
);
self
}
pub fn rust_target(mut self, rust_target: RustTarget) -> Self {
self.options.set_rust_target(rust_target);
self
}
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
}
pub fn generate_comments(mut self, doit: bool) -> Self {
self.options.generate_comments = doit;
self
}
pub fn whitelist_recursively(mut self, doit: bool) -> Self {
self.options.whitelist_recursively = doit;
self
}
pub fn objc_extern_crate(mut self, doit: bool) -> Self {
self.options.objc_extern_crate = doit;
self
}
pub fn trust_clang_mangling(mut self, doit: bool) -> Self {
self.options.enable_mangling = doit;
self
}
#[deprecated = "Use blacklist_type instead"]
pub fn hide_type<T: AsRef<str>>(self, arg: T) -> Builder {
self.blacklist_type(arg)
}
pub fn blacklist_type<T: AsRef<str>>(mut self, arg: T) -> Builder {
self.options.blacklisted_types.insert(arg);
self
}
pub fn opaque_type<T: AsRef<str>>(mut self, arg: T) -> Builder {
self.options.opaque_types.insert(arg);
self
}
#[deprecated = "use whitelist_type instead"]
pub fn whitelisted_type<T: AsRef<str>>(self, arg: T) -> Builder {
self.whitelist_type(arg)
}
pub fn whitelist_type<T: AsRef<str>>(mut self, arg: T) -> Builder {
self.options.whitelisted_types.insert(arg);
self
}
pub fn whitelist_function<T: AsRef<str>>(mut self, arg: T) -> Builder {
self.options.whitelisted_functions.insert(arg);
self
}
#[deprecated = "use whitelist_function instead"]
pub fn whitelisted_function<T: AsRef<str>>(self, arg: T) -> Builder {
self.whitelist_function(arg)
}
pub fn whitelist_var<T: AsRef<str>>(mut self, arg: T) -> Builder {
self.options.whitelisted_vars.insert(arg);
self
}
#[deprecated = "use whitelist_var instead"]
pub fn whitelisted_var<T: AsRef<str>>(self, arg: T) -> Builder {
self.whitelist_var(arg)
}
pub fn bitfield_enum<T: AsRef<str>>(mut self, arg: T) -> Builder {
self.options.bitfield_enums.insert(arg);
self
}
pub fn rustified_enum<T: AsRef<str>>(mut self, arg: T) -> Builder {
self.options.rustified_enums.insert(arg);
self
}
pub fn constified_enum_module<T: AsRef<str>>(mut self, arg: T) -> Builder {
self.options.constified_enum_modules.insert(arg);
self
}
pub fn raw_line<T: Into<String>>(mut self, arg: T) -> Builder {
self.options.raw_lines.push(arg.into());
self
}
pub fn clang_arg<T: Into<String>>(mut self, arg: T) -> Builder {
self.options.clang_args.push(arg.into());
self
}
pub fn clang_args<I>(mut self, iter: I) -> Builder
where
I: IntoIterator,
I::Item: AsRef<str>,
{
for arg in iter {
self = self.clang_arg(arg.as_ref())
}
self
}
pub fn link<T: Into<String>>(mut self, library: T) -> Builder {
self.options.links.push((library.into(), LinkType::Default));
self
}
pub fn link_static<T: Into<String>>(mut self, library: T) -> Builder {
self.options.links.push((library.into(), LinkType::Static));
self
}
pub fn link_framework<T: Into<String>>(mut self, library: T) -> Builder {
self.options.links.push(
(library.into(), LinkType::Framework),
);
self
}
pub fn emit_builtins(mut self) -> Builder {
self.options.builtins = true;
self
}
pub fn no_convert_floats(mut self) -> Self {
self.options.convert_floats = false;
self
}
pub fn layout_tests(mut self, doit: bool) -> Self {
self.options.layout_tests = doit;
self
}
pub fn impl_debug(mut self, doit: bool) -> Self {
self.options.impl_debug = doit;
self
}
pub fn impl_partialeq(mut self, doit: bool) -> Self {
self.options.impl_partialeq = doit;
self
}
pub fn derive_copy(mut self, doit: bool) -> Self {
self.options.derive_copy = doit;
self
}
pub fn derive_debug(mut self, doit: bool) -> Self {
self.options.derive_debug = doit;
self
}
pub fn derive_default(mut self, doit: bool) -> Self {
self.options.derive_default = doit;
self
}
pub fn derive_hash(mut self, doit: bool) -> Self {
self.options.derive_hash = doit;
self
}
pub fn derive_partialord(mut self, doit: bool) -> Self {
self.options.derive_partialord = doit;
if !doit {
self.options.derive_ord = false;
}
self
}
pub fn derive_ord(mut self, doit: bool) -> Self {
self.options.derive_ord = doit;
self.options.derive_partialord = doit;
self
}
pub fn derive_partialeq(mut self, doit: bool) -> Self {
self.options.derive_partialeq = doit;
if !doit {
self.options.derive_eq = false;
}
self
}
pub fn derive_eq(mut self, doit: bool) -> Self {
self.options.derive_eq = doit;
if doit {
self.options.derive_partialeq = doit;
}
self
}
pub fn time_phases(mut self, doit: bool) -> Self {
self.options.time_phases = doit;
self
}
pub fn emit_clang_ast(mut self) -> Builder {
self.options.emit_ast = true;
self
}
pub fn emit_ir(mut self) -> Builder {
self.options.emit_ir = true;
self
}
pub fn enable_cxx_namespaces(mut self) -> Builder {
self.options.enable_cxx_namespaces = true;
self
}
pub fn disable_name_namespacing(mut self) -> Builder {
self.options.disable_name_namespacing = true;
self
}
pub fn conservative_inline_namespaces(mut self) -> Builder {
self.options.conservative_inline_namespaces = true;
self
}
pub fn generate_inline_functions(mut self, doit: bool) -> Self {
self.options.generate_inline_functions = doit;
self
}
pub fn ignore_functions(mut self) -> Builder {
self.options.codegen_config.functions = false;
self
}
pub fn ignore_methods(mut self) -> Builder {
self.options.codegen_config.methods = false;
self
}
#[deprecated(note = "please use `rust_target` instead")]
pub fn unstable_rust(self, doit: bool) -> Self {
let rust_target = if doit {
RustTarget::Nightly
} else {
LATEST_STABLE_RUST
};
self.rust_target(rust_target)
}
pub fn use_core(mut self) -> Builder {
self.options.use_core = true;
self
}
pub fn ctypes_prefix<T: Into<String>>(mut self, prefix: T) -> Builder {
self.options.ctypes_prefix = Some(prefix.into());
self
}
pub fn parse_callbacks(
mut self,
cb: Box<callbacks::ParseCallbacks>,
) -> Self {
self.options.parse_callbacks = Some(cb);
self
}
pub fn with_codegen_config(mut self, config: CodegenConfig) -> Self {
self.options.codegen_config = config;
self
}
pub fn prepend_enum_name(mut self, doit: bool) -> Self {
self.options.prepend_enum_name = doit;
self
}
pub fn rustfmt_bindings(mut self, doit: bool) -> Self {
self.options.rustfmt_bindings = doit;
self
}
pub fn rustfmt_configuration_file(mut self, path: Option<PathBuf>) -> Self {
self = self.rustfmt_bindings(true);
self.options.rustfmt_configuration_file = path;
self
}
pub fn generate(mut self) -> Result<Bindings, ()> {
self.options.input_header = self.input_headers.pop();
self.options.clang_args.extend(
self.input_headers
.drain(..)
.flat_map(|header| {
iter::once("-include".into()).chain(iter::once(header))
}),
);
self.options.input_unsaved_files.extend(
self.input_header_contents.drain(..).map(|(name, contents)| {
clang::UnsavedFile::new(&name, &contents)
}),
);
Bindings::generate(self.options)
}
pub fn dump_preprocessed_input(&self) -> io::Result<()> {
let clang = clang_sys::support::Clang::find(None, &[]).ok_or_else(|| {
io::Error::new(io::ErrorKind::Other, "Cannot find clang executable")
})?;
let mut wrapper_contents = String::new();
let mut is_cpp = false;
for header in &self.input_headers {
is_cpp |= header.ends_with(".hpp");
wrapper_contents.push_str("#include \"");
wrapper_contents.push_str(header);
wrapper_contents.push_str("\"\n");
}
for &(ref name, ref contents) in &self.input_header_contents {
is_cpp |= name.ends_with(".hpp");
wrapper_contents.push_str("#line 0 \"");
wrapper_contents.push_str(name);
wrapper_contents.push_str("\"\n");
wrapper_contents.push_str(contents);
}
is_cpp |= self.options.clang_args.windows(2).any(|w| {
w[0] == "-x=c++" || w[1] == "-x=c++" || w == &["-x", "c++"]
});
let wrapper_path = PathBuf::from(if is_cpp {
"__bindgen.cpp"
} else {
"__bindgen.c"
});
{
let mut wrapper_file = File::create(&wrapper_path)?;
wrapper_file.write(wrapper_contents.as_bytes())?;
}
let mut cmd = Command::new(&clang.path);
cmd.arg("-save-temps")
.arg("-E")
.arg("-C")
.arg("-c")
.arg(&wrapper_path)
.stdout(Stdio::piped());
for a in &self.options.clang_args {
cmd.arg(a);
}
let mut child = cmd.spawn()?;
let mut preprocessed = child.stdout.take().unwrap();
let mut file = File::create(if is_cpp {
"__bindgen.ii"
} else {
"__bindgen.i"
})?;
io::copy(&mut preprocessed, &mut file)?;
if child.wait()?.success() {
Ok(())
} else {
Err(io::Error::new(
io::ErrorKind::Other,
"clang exited with non-zero status",
))
}
}
pub fn no_partialeq(mut self, arg: String) -> Builder {
self.options.no_partialeq_types.insert(arg);
self
}
pub fn no_copy(mut self, arg: String) -> Self {
self.options.no_copy_types.insert(arg);
self
}
pub fn no_hash(mut self, arg: String) -> Builder {
self.options.no_hash_types.insert(arg);
self
}
}
#[derive(Debug)]
struct BindgenOptions {
blacklisted_types: RegexSet,
opaque_types: RegexSet,
whitelisted_types: RegexSet,
whitelisted_functions: RegexSet,
whitelisted_vars: RegexSet,
bitfield_enums: RegexSet,
rustified_enums: RegexSet,
constified_enum_modules: RegexSet,
builtins: bool,
links: Vec<(String, LinkType)>,
emit_ast: bool,
emit_ir: bool,
emit_ir_graphviz: Option<String>,
enable_cxx_namespaces: bool,
disable_name_namespacing: bool,
layout_tests: bool,
impl_debug: bool,
impl_partialeq: bool,
derive_copy: bool,
derive_debug: bool,
derive_default: bool,
derive_hash: bool,
derive_partialord: bool,
derive_ord: bool,
derive_partialeq: bool,
derive_eq: bool,
use_core: bool,
ctypes_prefix: Option<String>,
time_phases: bool,
namespaced_constants: bool,
msvc_mangling: bool,
convert_floats: bool,
raw_lines: Vec<String>,
clang_args: Vec<String>,
input_header: Option<String>,
input_unsaved_files: Vec<clang::UnsavedFile>,
parse_callbacks: Option<Box<callbacks::ParseCallbacks>>,
codegen_config: CodegenConfig,
conservative_inline_namespaces: bool,
generate_comments: bool,
generate_inline_functions: bool,
whitelist_recursively: bool,
objc_extern_crate: bool,
enable_mangling: bool,
prepend_enum_name: bool,
rust_target: RustTarget,
rust_features: RustFeatures,
rustfmt_bindings: bool,
rustfmt_configuration_file: Option<PathBuf>,
no_partialeq_types: RegexSet,
no_copy_types: RegexSet,
no_hash_types: RegexSet,
}
impl ::std::panic::UnwindSafe for BindgenOptions {}
impl BindgenOptions {
fn build(&mut self) {
self.whitelisted_vars.build();
self.whitelisted_types.build();
self.whitelisted_functions.build();
self.blacklisted_types.build();
self.opaque_types.build();
self.bitfield_enums.build();
self.constified_enum_modules.build();
self.rustified_enums.build();
self.no_partialeq_types.build();
self.no_copy_types.build();
self.no_hash_types.build();
}
pub fn set_rust_target(&mut self, rust_target: RustTarget) {
self.rust_target = rust_target;
self.rust_features = rust_target.into();
}
pub fn rust_features(&self) -> RustFeatures {
self.rust_features
}
}
impl Default for BindgenOptions {
fn default() -> BindgenOptions {
let rust_target = RustTarget::default();
BindgenOptions {
rust_target: rust_target,
rust_features: rust_target.into(),
blacklisted_types: Default::default(),
opaque_types: Default::default(),
whitelisted_types: Default::default(),
whitelisted_functions: Default::default(),
whitelisted_vars: Default::default(),
bitfield_enums: Default::default(),
rustified_enums: Default::default(),
constified_enum_modules: Default::default(),
builtins: false,
links: vec![],
emit_ast: false,
emit_ir: false,
emit_ir_graphviz: None,
layout_tests: true,
impl_debug: false,
impl_partialeq: false,
derive_copy: true,
derive_debug: true,
derive_default: false,
derive_hash: false,
derive_partialord: false,
derive_ord: false,
derive_partialeq: false,
derive_eq: false,
enable_cxx_namespaces: false,
disable_name_namespacing: false,
use_core: false,
ctypes_prefix: None,
namespaced_constants: true,
msvc_mangling: false,
convert_floats: true,
raw_lines: vec![],
clang_args: vec![],
input_header: None,
input_unsaved_files: vec![],
parse_callbacks: None,
codegen_config: CodegenConfig::all(),
conservative_inline_namespaces: false,
generate_comments: true,
generate_inline_functions: false,
whitelist_recursively: true,
objc_extern_crate: false,
enable_mangling: true,
prepend_enum_name: true,
time_phases: false,
rustfmt_bindings: true,
rustfmt_configuration_file: None,
no_partialeq_types: Default::default(),
no_copy_types: Default::default(),
no_hash_types: Default::default(),
}
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum LinkType {
Default,
Static,
Framework,
}
fn ensure_libclang_is_loaded() {
if clang_sys::is_loaded() {
return;
}
lazy_static! {
static ref LIBCLANG: Arc<clang_sys::SharedLibrary> = {
clang_sys::load().expect("Unable to find libclang");
clang_sys::get_library()
.expect("We just loaded libclang and it had better still be \
here!")
};
}
clang_sys::set_library(Some(LIBCLANG.clone()));
}
#[derive(Debug)]
pub struct Bindings {
options: BindgenOptions,
module: quote::Tokens,
}
impl Bindings {
pub(crate) fn generate(
mut options: BindgenOptions,
) -> Result<Bindings, ()> {
ensure_libclang_is_loaded();
options.build();
let clang_args_for_clang_sys = {
let mut last_was_include_prefix = false;
options.clang_args.iter().filter(|arg| {
if last_was_include_prefix {
last_was_include_prefix = false;
return false;
}
let arg = &**arg;
if arg == "-I" || arg == "--include-directory" {
last_was_include_prefix = true;
return false;
}
if arg.starts_with("-I") || arg.starts_with("--include-directory=") {
return false;
}
true
}).cloned().collect::<Vec<_>>()
};
if let Some(clang) = clang_sys::support::Clang::find(
None,
&clang_args_for_clang_sys,
)
{
let has_target_arg = options
.clang_args
.iter()
.rposition(|arg| arg.starts_with("--target"))
.is_some();
if !has_target_arg {
if let Some(cpp_search_paths) = clang.cpp_search_paths {
for path in cpp_search_paths.into_iter() {
if let Ok(path) = path.into_os_string().into_string() {
options.clang_args.push("-isystem".to_owned());
options.clang_args.push(path);
}
}
}
}
}
#[cfg(unix)]
fn can_read(perms: &std::fs::Permissions) -> bool {
use std::os::unix::fs::PermissionsExt;
perms.mode() & 0o444 > 0
}
#[cfg(not(unix))]
fn can_read(_: &std::fs::Permissions) -> bool {
true
}
if let Some(h) = options.input_header.as_ref() {
let md = std::fs::metadata(h).ok().unwrap();
if !md.is_file() {
eprintln!("error: '{}' is a folder", h);
return Err(());
}
if !can_read(&md.permissions()) {
eprintln!("error: insufficient permissions to read '{}'", h);
return Err(());
}
options.clang_args.push(h.clone())
}
for f in options.input_unsaved_files.iter() {
options.clang_args.push(f.name.to_str().unwrap().to_owned())
}
let time_phases = options.time_phases;
let mut context = BindgenContext::new(options);
{
let _t = time::Timer::new("parse")
.with_output(time_phases);
try!(parse(&mut context));
}
let (items, options) = codegen::codegen(context);
Ok(Bindings {
options: options,
module: quote! {
#( #items )*
}
})
}
pub fn to_string(&self) -> String {
let mut bytes = vec![];
self.write(Box::new(&mut bytes) as Box<Write>)
.expect("writing to a vec cannot fail");
String::from_utf8(bytes)
.expect("we should only write bindings that are valid utf-8")
}
pub fn write_to_file<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
let file = OpenOptions::new()
.write(true)
.truncate(true)
.create(true)
.open(path.as_ref())?;
self.write(Box::new(file))?;
Ok(())
}
pub fn write<'a>(&self, mut writer: Box<Write + 'a>) -> io::Result<()> {
writer.write(
"/* automatically generated by rust-bindgen */\n\n".as_bytes(),
)?;
for line in self.options.raw_lines.iter() {
writer.write(line.as_bytes())?;
writer.write("\n".as_bytes())?;
}
if !self.options.raw_lines.is_empty() {
writer.write("\n".as_bytes())?;
}
let bindings = self.module.as_str().to_string();
match self.rustfmt_generated_string(&bindings) {
Ok(rustfmt_bindings) => {
writer.write(rustfmt_bindings.as_bytes())?;
},
Err(err) => {
eprintln!("{:?}", err);
writer.write(bindings.as_str().as_bytes())?;
},
}
Ok(())
}
fn rustfmt_generated_string<'a>(
&self,
source: &'a str,
) -> io::Result<Cow<'a, str>> {
let _t = time::Timer::new("rustfmt_generated_string")
.with_output(self.options.time_phases);
if !self.options.rustfmt_bindings {
return Ok(Cow::Borrowed(source));
}
let rustfmt = which::which("rustfmt")
.map_err(|e| io::Error::new(io::ErrorKind::Other, e.to_owned()))?;
let mut cmd = if let Ok(rustup) = which::which("rustup") {
let mut cmd = Command::new(rustup);
cmd.args(&["run", "nightly", "rustfmt", "--"]);
cmd
} else {
Command::new(rustfmt)
};
cmd
.args(&["--write-mode=display"])
.stdin(Stdio::piped())
.stdout(Stdio::piped());
if let Some(path) = self.options
.rustfmt_configuration_file
.as_ref()
.and_then(|f| f.to_str())
{
cmd.args(&["--config-path", path]);
}
let mut child = cmd.spawn()?;
let mut child_stdin = child.stdin.take().unwrap();
let mut child_stdout = child.stdout.take().unwrap();
let source = source.to_owned();
let stdin_handle = ::std::thread::spawn(move || {
let _ = child_stdin.write_all(source.as_bytes());
source
});
let mut output = vec![];
io::copy(&mut child_stdout, &mut output)?;
let status = child.wait()?;
let source = stdin_handle.join()
.expect("The thread writing to rustfmt's stdin doesn't do \
anything that could panic");
match String::from_utf8(output) {
Ok(bindings) => {
match status.code() {
Some(0) => Ok(Cow::Owned(bindings)),
Some(2) => Err(io::Error::new(
io::ErrorKind::Other,
"Rustfmt parsing errors.".to_string(),
)),
Some(3) => {
warn!("Rustfmt could not format some lines.");
Ok(Cow::Owned(bindings))
}
_ => Err(io::Error::new(
io::ErrorKind::Other,
"Internal rustfmt error".to_string(),
)),
}
},
_ => Ok(Cow::Owned(source))
}
}
}
fn filter_builtins(ctx: &BindgenContext, cursor: &clang::Cursor) -> bool {
ctx.options().builtins || !cursor.is_builtin()
}
fn parse_one(
ctx: &mut BindgenContext,
cursor: clang::Cursor,
parent: Option<ItemId>,
) -> clang_sys::CXChildVisitResult {
if !filter_builtins(ctx, &cursor) {
return CXChildVisit_Continue;
}
use clang_sys::CXChildVisit_Continue;
match Item::parse(cursor, parent, ctx) {
Ok(..) => {}
Err(ParseError::Continue) => {}
Err(ParseError::Recurse) => {
cursor.visit(|child| parse_one(ctx, child, parent));
}
}
CXChildVisit_Continue
}
fn parse(context: &mut BindgenContext) -> Result<(), ()> {
use clang_sys::*;
let mut any_error = false;
for d in context.translation_unit().diags().iter() {
let msg = d.format();
let is_err = d.severity() >= CXDiagnostic_Error;
eprintln!("{}, err: {}", msg, is_err);
any_error |= is_err;
}
if any_error {
return Err(());
}
let cursor = context.translation_unit().cursor();
if context.options().emit_ast {
fn dump_if_not_builtin(cur: &clang::Cursor) -> CXChildVisitResult {
if !cur.is_builtin() {
clang::ast_dump(&cur, 0)
} else {
CXChildVisit_Continue
}
}
cursor.visit(|cur| dump_if_not_builtin(&cur));
}
let root = context.root_module();
context.with_module(root, |context| {
cursor.visit(|cursor| parse_one(context, cursor, None))
});
assert!(
context.current_module() == context.root_module(),
"How did this happen?"
);
Ok(())
}
#[derive(Debug)]
pub struct ClangVersion {
pub parsed: Option<(u32, u32)>,
pub full: String,
}
pub fn clang_version() -> ClangVersion {
if !clang_sys::is_loaded() {
clang_sys::load().expect("Unable to find libclang");
}
let raw_v: String = clang::extract_clang_version();
let split_v: Option<Vec<&str>> = raw_v.split_whitespace().nth(2).map(|v| {
v.split('.').collect()
});
match split_v {
Some(v) => {
if v.len() >= 2 {
let maybe_major = v[0].parse::<u32>();
let maybe_minor = v[1].parse::<u32>();
match (maybe_major, maybe_minor) {
(Ok(major), Ok(minor)) => {
return ClangVersion {
parsed: Some((major, minor)),
full: raw_v.clone(),
}
}
_ => {}
}
}
}
None => {}
};
ClangVersion {
parsed: None,
full: raw_v.clone(),
}
}
#[test]
fn commandline_flag_unit_test_function() {
let bindings = ::builder();
let command_line_flags = bindings.command_line_flags();
let test_cases = vec![
"--no-derive-default",
"--generate",
"function,types,vars,methods,constructors,destructors",
].iter()
.map(|&x| x.into())
.collect::<Vec<String>>();
assert!(test_cases.iter().all(
|ref x| command_line_flags.contains(x),
));
let bindings = ::builder()
.header("input_header")
.whitelist_type("Distinct_Type")
.whitelist_function("safe_function");
let command_line_flags = bindings.command_line_flags();
let test_cases = vec![
"input_header",
"--no-derive-default",
"--generate",
"function,types,vars,methods,constructors,destructors",
"--whitelist-type",
"Distinct_Type",
"--whitelist-function",
"safe_function",
].iter()
.map(|&x| x.into())
.collect::<Vec<String>>();
println!("{:?}", command_line_flags);
assert!(test_cases.iter().all(
|ref x| command_line_flags.contains(x),
));
}