Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add BindgenError and Change generate to return the error #2125

Merged
merged 10 commits into from
Dec 29, 2021
68 changes: 51 additions & 17 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1444,7 +1444,7 @@ impl Builder {
}

/// Generate the Rust bindings using the options built up thus far.
pub fn generate(mut self) -> Result<Bindings, ()> {
pub fn generate(mut self) -> Result<Bindings, BindgenError> {
// Add any extra arguments from the environment to the clang command line.
if let Some(extra_clang_args) =
get_target_dependent_env_var("BINDGEN_EXTRA_CLANG_ARGS")
Expand Down Expand Up @@ -2146,6 +2146,39 @@ fn ensure_libclang_is_loaded() {
#[cfg(not(feature = "runtime"))]
fn ensure_libclang_is_loaded() {}

/// Error type for rust-bindgen.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum BindgenError {
MikuroXina marked this conversation as resolved.
Show resolved Hide resolved
/// The header was a folder.
FolderAsHeader(String),
/// Permissions to read the header is insufficient.
InsufficientPermissions(String),
/// The header does not exist.
NotExist(String),
MikuroXina marked this conversation as resolved.
Show resolved Hide resolved
/// Clang diagnosed an error.
ClangDiagnostic(String),
}

impl std::fmt::Display for BindgenError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
BindgenError::FolderAsHeader(h) => write!(f, "'{}' is a folder", h),
BindgenError::InsufficientPermissions(h) => {
write!(f, "insufficient permissions to read '{}'", h)
}
BindgenError::NotExist(h) => {
write!(f, "header '{}' does not exist.", h)
}
BindgenError::ClangDiagnostic(message) => {
write!(f, "clang diagnosed error: {}", message)
}
}
}
}

impl std::error::Error for BindgenError {}

/// Generated Rust bindings.
#[derive(Debug)]
pub struct Bindings {
Expand Down Expand Up @@ -2198,7 +2231,7 @@ impl Bindings {
/// Generate bindings for the given options.
pub(crate) fn generate(
mut options: BindgenOptions,
) -> Result<Bindings, ()> {
) -> Result<Bindings, BindgenError> {
ensure_libclang_is_loaded();

#[cfg(feature = "runtime")]
Expand Down Expand Up @@ -2318,20 +2351,16 @@ impl Bindings {
if let Some(h) = options.input_header.as_ref() {
if let Ok(md) = std::fs::metadata(h) {
if md.is_dir() {
eprintln!("error: '{}' is a folder", h);
return Err(());
return Err(BindgenError::FolderAsHeader(h.into()));
}
if !can_read(&md.permissions()) {
eprintln!(
"error: insufficient permissions to read '{}'",
h
);
return Err(());
return Err(BindgenError::InsufficientPermissions(
h.into(),
));
}
options.clang_args.push(h.clone())
} else {
eprintln!("error: header '{}' does not exist.", h);
return Err(());
return Err(BindgenError::NotExist(h.into()));
}
}

Expand Down Expand Up @@ -2552,19 +2581,24 @@ fn parse_one(
}

/// Parse the Clang AST into our `Item` internal representation.
fn parse(context: &mut BindgenContext) -> Result<(), ()> {
fn parse(context: &mut BindgenContext) -> Result<(), BindgenError> {
use clang_sys::*;

let mut any_error = false;
let mut error = None;
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 is_err {
let error = error.get_or_insert_with(String::new);
error.push_str(&msg);
error.push('\n');
} else {
eprintln!("clang diag: {}", msg);
}
}

if any_error {
return Err(());
if let Some(message) = error {
return Err(BindgenError::ClangDiagnostic(message));
}

let cursor = context.translation_unit().cursor();
Expand Down
2 changes: 1 addition & 1 deletion tests/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ fn compare_generated_header(
let actual = bindings.to_string();
rustfmt(actual)
}
Err(()) => ("<error generating bindings>".to_string(), "".to_string()),
Err(_) => ("<error generating bindings>".to_string(), "".to_string()),
};
println!("{}", rustfmt_stderr);

Expand Down