Skip to content

Commit cbc0304

Browse files
author
bors-servo
authored
Auto merge of #357 - emilio:auto, r=fitzgen
Multiple cleanups and fix for #355 Fixes #355 Also improves the output of #354. r? @fitzgen
2 parents 4472e0a + 1ad2821 commit cbc0304

File tree

14 files changed

+127
-69
lines changed

14 files changed

+127
-69
lines changed

bindgen-integration/src/lib.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,7 @@ use std::ffi::CStr;
77
#[test]
88
fn test_static_method() {
99
let c_str = unsafe { bindings::Test::name() };
10-
let name = unsafe {
11-
CStr::from_ptr(c_str).to_string_lossy().into_owned()
12-
};
10+
let name = unsafe { CStr::from_ptr(c_str).to_string_lossy().into_owned() };
1311
assert_eq!(name, "Test", "Calling a static C++ method works!");
1412
}
1513

bindgen/src/options.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use clap::{App, Arg};
2-
use libbindgen::{Builder, builder, CodegenConfig};
2+
use libbindgen::{Builder, CodegenConfig, builder};
33
use std::fs::File;
44
use std::io::{self, Error, ErrorKind};
55

@@ -200,8 +200,8 @@ pub fn builder_from_flags<I>(args: I)
200200
"vars" => config.vars = true,
201201
"methods" => config.methods = true,
202202
_ => {
203-
return Err(
204-
Error::new(ErrorKind::Other, "Unknown generate item"));
203+
return Err(Error::new(ErrorKind::Other,
204+
"Unknown generate item"));
205205
}
206206
}
207207
}

libbindgen/src/clang.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -832,8 +832,8 @@ impl SourceLocation {
832832
&mut col,
833833
&mut off);
834834
(File {
835-
x: file,
836-
},
835+
x: file,
836+
},
837837
line as usize,
838838
col as usize,
839839
off as usize)

libbindgen/src/codegen/mod.rs

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -727,14 +727,15 @@ impl CodeGenerator for CompInfo {
727727
let layout = item.kind().expect_type().layout(ctx);
728728

729729
if let Some(layout) = layout {
730-
let fn_name = format!("__bindgen_test_layout_template_{}", result.next_id());
730+
let fn_name = format!("__bindgen_test_layout_template_{}",
731+
result.next_id());
731732
let fn_name = ctx.rust_ident_raw(&fn_name);
732733
let ident = item.to_rust_ty(ctx);
733734
let prefix = ctx.trait_prefix();
734735
let size_of_expr = quote_expr!(ctx.ext_cx(),
735-
::$prefix::mem::size_of::<$ident>());
736+
::$prefix::mem::size_of::<$ident>());
736737
let align_of_expr = quote_expr!(ctx.ext_cx(),
737-
::$prefix::mem::align_of::<$ident>());
738+
::$prefix::mem::align_of::<$ident>());
738739
let size = layout.size;
739740
let align = layout.align;
740741
let item = quote_item!(ctx.ext_cx(),
@@ -894,7 +895,7 @@ impl CodeGenerator for CompInfo {
894895

895896
// Try to catch a bitfield contination early.
896897
if let (Some(ref mut bitfield_width), Some(width)) =
897-
(current_bitfield_width, field.bitfield()) {
898+
(current_bitfield_width, field.bitfield()) {
898899
let layout = current_bitfield_layout.unwrap();
899900
debug!("Testing bitfield continuation {} {} {:?}",
900901
*bitfield_width, width, layout);
@@ -1562,7 +1563,10 @@ impl CodeGenerator for Enum {
15621563
};
15631564

15641565
let signed = repr.is_signed();
1565-
let size = layout.map(|l| l.size).unwrap_or(0);
1566+
let size = layout.map(|l| l.size)
1567+
.or_else(|| repr.known_size())
1568+
.unwrap_or(0);
1569+
15661570
let repr_name = match (signed, size) {
15671571
(true, 1) => "i8",
15681572
(false, 1) => "u8",
@@ -1617,7 +1621,8 @@ impl CodeGenerator for Enum {
16171621
// Only to avoid recomputing every time.
16181622
enum_canonical_name: &str,
16191623
// May be the same as "variant" if it's because the
1620-
// enum is unnamed and we still haven't seen the value.
1624+
// enum is unnamed and we still haven't seen the
1625+
// value.
16211626
variant_name: &str,
16221627
referenced_name: &str,
16231628
enum_rust_ty: P<ast::Ty>,
@@ -2010,14 +2015,10 @@ impl CodeGenerator for Function {
20102015
}
20112016

20122017
let signature_item = ctx.resolve_item(self.signature());
2013-
let signature = signature_item.kind().expect_type();
2018+
let signature = signature_item.kind().expect_type().canonical_type(ctx);
20142019
let signature = match *signature.kind() {
20152020
TypeKind::Function(ref sig) => sig,
2016-
TypeKind::ResolvedTypeRef(ref item_id) => {
2017-
let item = ctx.resolve_item(*item_id);
2018-
return self.codegen(ctx, result, _whitelisted_items, item);
2019-
},
2020-
_ => panic!("How?")
2021+
_ => panic!("Signature kind is not a Function: {:?}", signature),
20212022
};
20222023

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

2271-
let signature = sig.kind().expect_type();
2272+
let signature = sig.kind().expect_type().canonical_type(ctx);
22722273
let signature = match *signature.kind() {
22732274
TypeKind::Function(ref sig) => sig,
22742275
_ => panic!("How?"),

libbindgen/src/ir/context.rs

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1135,7 +1135,8 @@ impl<'ctx, 'gen> Iterator for WhitelistedItemsIter<'ctx, 'gen>
11351135

11361136
/// An iterator to find any dangling items.
11371137
///
1138-
/// See `BindgenContext::assert_no_dangling_item_traversal` for more information.
1138+
/// See `BindgenContext::assert_no_dangling_item_traversal` for more
1139+
/// information.
11391140
pub struct AssertNoDanglingItemIter<'ctx, 'gen>
11401141
where 'gen: 'ctx,
11411142
{
@@ -1152,8 +1153,8 @@ impl<'ctx, 'gen> Iterator for AssertNoDanglingItemIter<'ctx, 'gen>
11521153
fn next(&mut self) -> Option<Self::Item> {
11531154
let id = match self.to_iterate.pop_front() {
11541155
None => {
1155-
// We've traversed everything reachable from the previous root(s), see if
1156-
// we have any more roots.
1156+
// We've traversed everything reachable from the previous
1157+
// root(s), see if we have any more roots.
11571158
match self.ctx
11581159
.items()
11591160
.filter(|&(id, _)| !self.seen.contains_key(id))
@@ -1177,8 +1178,10 @@ impl<'ctx, 'gen> Iterator for AssertNoDanglingItemIter<'ctx, 'gen>
11771178
let mut path = vec![];
11781179
let mut current = id;
11791180
loop {
1180-
let predecessor = *self.seen.get(&current)
1181-
.expect("We know we found this item id, so it must have a predecessor");
1181+
let predecessor = *self.seen
1182+
.get(&current)
1183+
.expect("We know we found this item id, so it must have a \
1184+
predecessor");
11821185
if predecessor == current {
11831186
break;
11841187
}

libbindgen/src/ir/enum_ty.rs

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -53,22 +53,18 @@ impl Enum {
5353
.and_then(|et| Item::from_ty(&et, None, None, ctx).ok());
5454
let mut variants = vec![];
5555

56-
let is_signed = match repr {
57-
Some(repr) => {
58-
let repr_type = ctx.resolve_type(repr);
59-
match *repr_type.canonical_type(ctx).kind() {
60-
TypeKind::Int(ref int_kind) => int_kind.is_signed(),
61-
ref other => {
62-
panic!("Since when enums can be non-integers? {:?}",
56+
// Assume signedness since the default type by the C standard is an int.
57+
let is_signed =
58+
repr.and_then(|r| ctx.resolve_type(r).safe_canonical_type(ctx))
59+
.map_or(true, |ty| {
60+
match *ty.kind() {
61+
TypeKind::Int(ref int_kind) => int_kind.is_signed(),
62+
ref other => {
63+
panic!("Since when enums can be non-integers? {:?}",
6364
other)
65+
}
6466
}
65-
}
66-
}
67-
// Assume signedness since the default type by the C
68-
// standard is an
69-
// int.
70-
None => true,
71-
};
67+
});
7268

7369
declaration.visit(|cursor| {
7470
if cursor.kind() == CXCursor_EnumConstantDecl {

libbindgen/src/ir/int.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,21 @@ impl IntKind {
9191
}
9292
}
9393

94+
/// If this type has a known size, return it (in bytes). This is to
95+
/// alleviate libclang sometimes not giving us a layout (like in the case
96+
/// when an enum is defined inside a class with template parameters).
97+
pub fn known_size(&self) -> Option<usize> {
98+
use self::IntKind::*;
99+
Some(match *self {
100+
Bool | UChar | Char | U8 | I8 => 1,
101+
U16 | I16 => 2,
102+
U32 | I32 => 4,
103+
U64 | I64 => 8,
104+
I128 | U128 => 16,
105+
_ => return None,
106+
})
107+
}
108+
94109
/// Whether this type's signedness matches the value.
95110
pub fn signedness_matches(&self, val: i64) -> bool {
96111
val >= 0 || self.is_signed()

libbindgen/src/ir/item.rs

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -696,7 +696,9 @@ impl Item {
696696
}
697697
ItemKind::Type(ref ty) => {
698698
let name = match *ty.kind() {
699-
TypeKind::ResolvedTypeRef(..) => panic!("should have resolved this in name_target()"),
699+
TypeKind::ResolvedTypeRef(..) => {
700+
panic!("should have resolved this in name_target()")
701+
}
700702
_ => ty.name(),
701703
};
702704
name.map(ToOwned::to_owned)
@@ -1075,7 +1077,7 @@ impl ClangItemParser for Item {
10751077
}
10761078

10771079
if let Some(ty) =
1078-
ctx.builtin_or_resolved_ty(id, parent_id, ty, location) {
1080+
ctx.builtin_or_resolved_ty(id, parent_id, ty, location) {
10791081
return Ok(ty);
10801082
}
10811083

@@ -1093,9 +1095,10 @@ impl ClangItemParser for Item {
10931095
};
10941096

10951097
if valid_decl {
1096-
if let Some(&(_, item_id)) = ctx.currently_parsed_types
1097-
.iter()
1098-
.find(|&&(d, _)| d == declaration_to_look_for) {
1098+
if let Some(&(_, item_id)) =
1099+
ctx.currently_parsed_types
1100+
.iter()
1101+
.find(|&&(d, _)| d == declaration_to_look_for) {
10991102
debug!("Avoiding recursion parsing type: {:?}", ty);
11001103
return Ok(item_id);
11011104
}

libbindgen/src/ir/ty.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -696,8 +696,8 @@ impl Type {
696696
let inner_type = match inner {
697697
Ok(inner) => inner,
698698
Err(..) => {
699-
error!("Failed to parse template alias {:?}",
700-
location);
699+
error!("Failed to parse template alias \
700+
{:?}", location);
701701
return Err(ParseError::Continue);
702702
}
703703
};

libbindgen/src/lib.rs

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -517,7 +517,8 @@ fn ensure_libclang_is_loaded() {
517517
// TODO(emilio): Return meaningful error (breaking).
518518
clang_sys::load().expect("Unable to find libclang");
519519
*libclang = Some(clang_sys::get_library()
520-
.expect("We just loaded libclang and it had better still be here!"));
520+
.expect("We just loaded libclang and it had \
521+
better still be here!"));
521522
} else {
522523
clang_sys::set_library(libclang.clone());
523524
}
@@ -630,16 +631,16 @@ impl<'ctx> Bindings<'ctx> {
630631
///
631632
/// See the `uses` module for more information.
632633
pub fn write_dummy_uses(&mut self) -> io::Result<()> {
633-
let file =
634-
if let Some(ref dummy_path) = self.context.options().dummy_uses {
635-
Some(try!(OpenOptions::new()
636-
.write(true)
637-
.truncate(true)
638-
.create(true)
639-
.open(dummy_path)))
640-
} else {
641-
None
642-
};
634+
let file = if let Some(ref dummy_path) =
635+
self.context.options().dummy_uses {
636+
Some(try!(OpenOptions::new()
637+
.write(true)
638+
.truncate(true)
639+
.create(true)
640+
.open(dummy_path)))
641+
} else {
642+
None
643+
};
643644

644645
if let Some(file) = file {
645646
try!(uses::generate_dummy_uses(&mut self.context, file));
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
/* automatically generated by rust-bindgen */
2+
3+
4+
#![allow(non_snake_case)]
5+
6+
7+
#[repr(C)]
8+
#[derive(Debug, Copy, Clone)]
9+
pub struct std_fbstring_core<Char> {
10+
pub _address: u8,
11+
pub _phantom_0: ::std::marker::PhantomData<Char>,
12+
}
13+
pub type std_fbstring_core_category_type = u8;
14+
pub const std_fbstring_core_Category_Bar: std_fbstring_core_Category =
15+
std_fbstring_core_Category::Foo;
16+
#[repr(u8)]
17+
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
18+
pub enum std_fbstring_core_Category { Foo = 0, }

libbindgen/tests/expectations/tests/resolved_type_def_function.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,6 @@
55

66

77
pub type FuncType = ::std::option::Option<unsafe extern "C" fn()>;
8+
extern "C" {
9+
pub fn Func();
10+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
// bindgen-flags: -- -std=c++11
2+
3+
namespace std {
4+
template <typename Char> class fbstring_core;
5+
}
6+
7+
typedef unsigned char uint8_t;
8+
namespace std {
9+
template <typename Char> class fbstring_core {
10+
typedef uint8_t category_type;
11+
enum Category : category_type {
12+
Foo = 1,
13+
Bar = 4,
14+
};
15+
};
16+
}

libbindgen/tests/tests.rs

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ fn compare_generated_header(header: &PathBuf,
4343
return Ok(());
4444
}
4545
return Err(Error::new(ErrorKind::Other,
46-
"Something's gone really wrong!"))
46+
"Something's gone really wrong!"));
4747
}
4848

4949
println!("diff expected generated");
@@ -79,10 +79,13 @@ fn create_bindgen_builder(header: &PathBuf)
7979
let line = try!(line);
8080
if line.contains("bindgen-flags: ") {
8181
let extra_flags = line.split("bindgen-flags: ")
82-
.last().and_then(shlex::split).unwrap();
82+
.last()
83+
.and_then(shlex::split)
84+
.unwrap();
8385
flags.extend(extra_flags.into_iter());
84-
} else if line.contains("bindgen-unstable") && cfg!(feature = "llvm_stable") {
85-
return Ok(None)
86+
} else if line.contains("bindgen-unstable") &&
87+
cfg!(feature = "llvm_stable") {
88+
return Ok(None);
8689
}
8790
}
8891

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

97-
let prepend = [
98-
"bindgen",
99-
header_str,
100-
"--raw-line", "",
101-
"--raw-line", "#![allow(non_snake_case)]",
102-
"--raw-line", "",
103-
];
100+
let prepend = ["bindgen",
101+
header_str,
102+
"--raw-line",
103+
"",
104+
"--raw-line",
105+
"#![allow(non_snake_case)]",
106+
"--raw-line",
107+
""];
104108

105109
let args = prepend.into_iter()
106110
.map(ToString::to_string)

0 commit comments

Comments
 (0)