Skip to content

Multiple cleanups and fix for #355 #357

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

Merged
merged 4 commits into from
Dec 23, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 1 addition & 3 deletions bindgen-integration/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@ use std::ffi::CStr;
#[test]
fn test_static_method() {
let c_str = unsafe { bindings::Test::name() };
let name = unsafe {
CStr::from_ptr(c_str).to_string_lossy().into_owned()
};
let name = unsafe { CStr::from_ptr(c_str).to_string_lossy().into_owned() };
assert_eq!(name, "Test", "Calling a static C++ method works!");
}

Expand Down
6 changes: 3 additions & 3 deletions bindgen/src/options.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use clap::{App, Arg};
use libbindgen::{Builder, builder, CodegenConfig};
use libbindgen::{Builder, CodegenConfig, builder};
use std::fs::File;
use std::io::{self, Error, ErrorKind};

Expand Down Expand Up @@ -200,8 +200,8 @@ pub fn builder_from_flags<I>(args: I)
"vars" => config.vars = true,
"methods" => config.methods = true,
_ => {
return Err(
Error::new(ErrorKind::Other, "Unknown generate item"));
return Err(Error::new(ErrorKind::Other,
"Unknown generate item"));
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions libbindgen/src/clang.rs
Original file line number Diff line number Diff line change
Expand Up @@ -832,8 +832,8 @@ impl SourceLocation {
&mut col,
&mut off);
(File {
x: file,
},
x: file,
},
line as usize,
col as usize,
off as usize)
Expand Down
27 changes: 14 additions & 13 deletions libbindgen/src/codegen/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -727,14 +727,15 @@ impl CodeGenerator for CompInfo {
let layout = item.kind().expect_type().layout(ctx);

if let Some(layout) = layout {
let fn_name = format!("__bindgen_test_layout_template_{}", result.next_id());
let fn_name = format!("__bindgen_test_layout_template_{}",
result.next_id());
let fn_name = ctx.rust_ident_raw(&fn_name);
let ident = item.to_rust_ty(ctx);
let prefix = ctx.trait_prefix();
let size_of_expr = quote_expr!(ctx.ext_cx(),
::$prefix::mem::size_of::<$ident>());
::$prefix::mem::size_of::<$ident>());
let align_of_expr = quote_expr!(ctx.ext_cx(),
::$prefix::mem::align_of::<$ident>());
::$prefix::mem::align_of::<$ident>());
let size = layout.size;
let align = layout.align;
let item = quote_item!(ctx.ext_cx(),
Expand Down Expand Up @@ -894,7 +895,7 @@ impl CodeGenerator for CompInfo {

// Try to catch a bitfield contination early.
if let (Some(ref mut bitfield_width), Some(width)) =
(current_bitfield_width, field.bitfield()) {
(current_bitfield_width, field.bitfield()) {
let layout = current_bitfield_layout.unwrap();
debug!("Testing bitfield continuation {} {} {:?}",
*bitfield_width, width, layout);
Expand Down Expand Up @@ -1562,7 +1563,10 @@ impl CodeGenerator for Enum {
};

let signed = repr.is_signed();
let size = layout.map(|l| l.size).unwrap_or(0);
let size = layout.map(|l| l.size)
.or_else(|| repr.known_size())
.unwrap_or(0);

let repr_name = match (signed, size) {
(true, 1) => "i8",
(false, 1) => "u8",
Expand Down Expand Up @@ -1617,7 +1621,8 @@ impl CodeGenerator for Enum {
// Only to avoid recomputing every time.
enum_canonical_name: &str,
// May be the same as "variant" if it's because the
// enum is unnamed and we still haven't seen the value.
// enum is unnamed and we still haven't seen the
// value.
variant_name: &str,
referenced_name: &str,
enum_rust_ty: P<ast::Ty>,
Expand Down Expand Up @@ -2010,14 +2015,10 @@ impl CodeGenerator for Function {
}

let signature_item = ctx.resolve_item(self.signature());
let signature = signature_item.kind().expect_type();
let signature = signature_item.kind().expect_type().canonical_type(ctx);
let signature = match *signature.kind() {
TypeKind::Function(ref sig) => sig,
TypeKind::ResolvedTypeRef(ref item_id) => {
let item = ctx.resolve_item(*item_id);
return self.codegen(ctx, result, _whitelisted_items, item);
},
_ => panic!("How?")
_ => panic!("Signature kind is not a Function: {:?}", signature),
};

let fndecl = utils::rust_fndecl_from_signature(ctx, signature_item);
Expand Down Expand Up @@ -2268,7 +2269,7 @@ mod utils {
-> P<ast::FnDecl> {
use codegen::ToRustTy;

let signature = sig.kind().expect_type();
let signature = sig.kind().expect_type().canonical_type(ctx);
let signature = match *signature.kind() {
TypeKind::Function(ref sig) => sig,
_ => panic!("How?"),
Expand Down
13 changes: 8 additions & 5 deletions libbindgen/src/ir/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1135,7 +1135,8 @@ impl<'ctx, 'gen> Iterator for WhitelistedItemsIter<'ctx, 'gen>

/// An iterator to find any dangling items.
///
/// See `BindgenContext::assert_no_dangling_item_traversal` for more information.
/// See `BindgenContext::assert_no_dangling_item_traversal` for more
/// information.
pub struct AssertNoDanglingItemIter<'ctx, 'gen>
where 'gen: 'ctx,
{
Expand All @@ -1152,8 +1153,8 @@ impl<'ctx, 'gen> Iterator for AssertNoDanglingItemIter<'ctx, 'gen>
fn next(&mut self) -> Option<Self::Item> {
let id = match self.to_iterate.pop_front() {
None => {
// We've traversed everything reachable from the previous root(s), see if
// we have any more roots.
// We've traversed everything reachable from the previous
// root(s), see if we have any more roots.
match self.ctx
.items()
.filter(|&(id, _)| !self.seen.contains_key(id))
Expand All @@ -1177,8 +1178,10 @@ impl<'ctx, 'gen> Iterator for AssertNoDanglingItemIter<'ctx, 'gen>
let mut path = vec![];
let mut current = id;
loop {
let predecessor = *self.seen.get(&current)
.expect("We know we found this item id, so it must have a predecessor");
let predecessor = *self.seen
.get(&current)
.expect("We know we found this item id, so it must have a \
predecessor");
if predecessor == current {
break;
}
Expand Down
24 changes: 10 additions & 14 deletions libbindgen/src/ir/enum_ty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,22 +53,18 @@ impl Enum {
.and_then(|et| Item::from_ty(&et, None, None, ctx).ok());
let mut variants = vec![];

let is_signed = match repr {
Some(repr) => {
let repr_type = ctx.resolve_type(repr);
match *repr_type.canonical_type(ctx).kind() {
TypeKind::Int(ref int_kind) => int_kind.is_signed(),
ref other => {
panic!("Since when enums can be non-integers? {:?}",
// Assume signedness since the default type by the C standard is an int.
let is_signed =
repr.and_then(|r| ctx.resolve_type(r).safe_canonical_type(ctx))
.map_or(true, |ty| {
match *ty.kind() {
TypeKind::Int(ref int_kind) => int_kind.is_signed(),
ref other => {
panic!("Since when enums can be non-integers? {:?}",
other)
}
}
}
}
// Assume signedness since the default type by the C
// standard is an
// int.
None => true,
};
});

declaration.visit(|cursor| {
if cursor.kind() == CXCursor_EnumConstantDecl {
Expand Down
15 changes: 15 additions & 0 deletions libbindgen/src/ir/int.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,21 @@ impl IntKind {
}
}

/// If this type has a known size, return it (in bytes). This is to
/// alleviate libclang sometimes not giving us a layout (like in the case
/// when an enum is defined inside a class with template parameters).
pub fn known_size(&self) -> Option<usize> {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great :)

use self::IntKind::*;
Some(match *self {
Bool | UChar | Char | U8 | I8 => 1,
U16 | I16 => 2,
U32 | I32 => 4,
U64 | I64 => 8,
I128 | U128 => 16,
_ => return None,
})
}

/// Whether this type's signedness matches the value.
pub fn signedness_matches(&self, val: i64) -> bool {
val >= 0 || self.is_signed()
Expand Down
13 changes: 8 additions & 5 deletions libbindgen/src/ir/item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -696,7 +696,9 @@ impl Item {
}
ItemKind::Type(ref ty) => {
let name = match *ty.kind() {
TypeKind::ResolvedTypeRef(..) => panic!("should have resolved this in name_target()"),
TypeKind::ResolvedTypeRef(..) => {
panic!("should have resolved this in name_target()")
}
_ => ty.name(),
};
name.map(ToOwned::to_owned)
Expand Down Expand Up @@ -1075,7 +1077,7 @@ impl ClangItemParser for Item {
}

if let Some(ty) =
ctx.builtin_or_resolved_ty(id, parent_id, ty, location) {
ctx.builtin_or_resolved_ty(id, parent_id, ty, location) {
return Ok(ty);
}

Expand All @@ -1093,9 +1095,10 @@ impl ClangItemParser for Item {
};

if valid_decl {
if let Some(&(_, item_id)) = ctx.currently_parsed_types
.iter()
.find(|&&(d, _)| d == declaration_to_look_for) {
if let Some(&(_, item_id)) =
ctx.currently_parsed_types
.iter()
.find(|&&(d, _)| d == declaration_to_look_for) {
debug!("Avoiding recursion parsing type: {:?}", ty);
return Ok(item_id);
}
Expand Down
4 changes: 2 additions & 2 deletions libbindgen/src/ir/ty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -696,8 +696,8 @@ impl Type {
let inner_type = match inner {
Ok(inner) => inner,
Err(..) => {
error!("Failed to parse template alias {:?}",
location);
error!("Failed to parse template alias \
{:?}", location);
return Err(ParseError::Continue);
}
};
Expand Down
23 changes: 12 additions & 11 deletions libbindgen/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -517,7 +517,8 @@ fn ensure_libclang_is_loaded() {
// TODO(emilio): Return meaningful error (breaking).
clang_sys::load().expect("Unable to find libclang");
*libclang = Some(clang_sys::get_library()
.expect("We just loaded libclang and it had better still be here!"));
.expect("We just loaded libclang and it had \
better still be here!"));
} else {
clang_sys::set_library(libclang.clone());
}
Expand Down Expand Up @@ -630,16 +631,16 @@ impl<'ctx> Bindings<'ctx> {
///
/// See the `uses` module for more information.
pub fn write_dummy_uses(&mut self) -> io::Result<()> {
let file =
if let Some(ref dummy_path) = self.context.options().dummy_uses {
Some(try!(OpenOptions::new()
.write(true)
.truncate(true)
.create(true)
.open(dummy_path)))
} else {
None
};
let file = if let Some(ref dummy_path) =
self.context.options().dummy_uses {
Some(try!(OpenOptions::new()
.write(true)
.truncate(true)
.create(true)
.open(dummy_path)))
} else {
None
};

if let Some(file) = file {
try!(uses::generate_dummy_uses(&mut self.context, file));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/* automatically generated by rust-bindgen */


#![allow(non_snake_case)]


#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct std_fbstring_core<Char> {
pub _address: u8,
pub _phantom_0: ::std::marker::PhantomData<Char>,
}
pub type std_fbstring_core_category_type = u8;
pub const std_fbstring_core_Category_Bar: std_fbstring_core_Category =
std_fbstring_core_Category::Foo;
#[repr(u8)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum std_fbstring_core_Category { Foo = 0, }
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,6 @@


pub type FuncType = ::std::option::Option<unsafe extern "C" fn()>;
extern "C" {
pub fn Func();
}
16 changes: 16 additions & 0 deletions libbindgen/tests/headers/enum_in_template_with_typedef.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// bindgen-flags: -- -std=c++11

namespace std {
template <typename Char> class fbstring_core;
}

typedef unsigned char uint8_t;
namespace std {
template <typename Char> class fbstring_core {
typedef uint8_t category_type;
enum Category : category_type {
Foo = 1,
Bar = 4,
};
};
}
26 changes: 15 additions & 11 deletions libbindgen/tests/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ fn compare_generated_header(header: &PathBuf,
return Ok(());
}
return Err(Error::new(ErrorKind::Other,
"Something's gone really wrong!"))
"Something's gone really wrong!"));
}

println!("diff expected generated");
Expand Down Expand Up @@ -79,10 +79,13 @@ fn create_bindgen_builder(header: &PathBuf)
let line = try!(line);
if line.contains("bindgen-flags: ") {
let extra_flags = line.split("bindgen-flags: ")
.last().and_then(shlex::split).unwrap();
.last()
.and_then(shlex::split)
.unwrap();
flags.extend(extra_flags.into_iter());
} else if line.contains("bindgen-unstable") && cfg!(feature = "llvm_stable") {
return Ok(None)
} else if line.contains("bindgen-unstable") &&
cfg!(feature = "llvm_stable") {
return Ok(None);
}
}

Expand All @@ -94,13 +97,14 @@ fn create_bindgen_builder(header: &PathBuf)
let header_str = try!(header.to_str()
.ok_or(Error::new(ErrorKind::Other, "Invalid header file name")));

let prepend = [
"bindgen",
header_str,
"--raw-line", "",
"--raw-line", "#![allow(non_snake_case)]",
"--raw-line", "",
];
let prepend = ["bindgen",
header_str,
"--raw-line",
"",
"--raw-line",
"#![allow(non_snake_case)]",
"--raw-line",
""];

let args = prepend.into_iter()
.map(ToString::to_string)
Expand Down