summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorEmilio Cobos Álvarez <ecoal95@gmail.com>2016-11-01 12:56:14 +0100
committerEmilio Cobos Álvarez <ecoal95@gmail.com>2016-11-01 17:07:37 +0100
commitf226fef4c8e0c97d674a2426eb8bd7f1ad0141e5 (patch)
treeb3b310871ca50344dbbc2fbb08c8a328b8636e2b
parent163848e82c692db951ed301b0a9e3fee9d45338c (diff)
Run `cargo fmt`.
-rwxr-xr-xsrc/bin/bindgen.rs52
-rwxr-xr-xsrc/clang.rs461
-rwxr-xr-xsrc/codegen/mod.rs506
-rw-r--r--src/ir/annotations.rs23
-rw-r--r--src/ir/comp.rs152
-rw-r--r--src/ir/context.rs190
-rw-r--r--src/ir/enum_ty.rs25
-rw-r--r--src/ir/function.rs61
-rw-r--r--src/ir/int.rs12
-rw-r--r--src/ir/item.rs253
-rw-r--r--src/ir/module.rs14
-rw-r--r--src/ir/ty.rs248
-rw-r--r--src/ir/var.rs76
-rwxr-xr-xsrc/lib.rs38
-rw-r--r--src/parse.rs45
-rw-r--r--src/regex_set.rs10
16 files changed, 1286 insertions, 880 deletions
diff --git a/src/bin/bindgen.rs b/src/bin/bindgen.rs
index 119776bd..2a7995e7 100755
--- a/src/bin/bindgen.rs
+++ b/src/bin/bindgen.rs
@@ -8,13 +8,13 @@ extern crate log;
extern crate clang_sys;
extern crate rustc_serialize;
-use bindgen::{Bindings, BindgenOptions, LinkType};
+use bindgen::{BindgenOptions, Bindings, LinkType};
use std::default::Default;
+use std::env;
+use std::fs;
use std::io;
use std::path;
use std::process;
-use std::env;
-use std::fs;
const USAGE: &'static str = "
Usage:
@@ -119,7 +119,8 @@ fn parse_args_or_exit(args: Vec<String>) -> (BindgenOptions, Box<io::Write>) {
options.links.push((lib, LinkType::Static));
}
"--framework-link" => {
- let lib = iter.next().expect("--framework-link needs an argument");
+ let lib = iter.next()
+ .expect("--framework-link needs an argument");
options.links.push((lib, LinkType::Framework));
}
"--raw-line" => {
@@ -127,23 +128,28 @@ fn parse_args_or_exit(args: Vec<String>) -> (BindgenOptions, Box<io::Write>) {
options.raw_lines.push(line);
}
"--opaque-type" => {
- let ty_canonical_name = iter.next().expect("--opaque-type expects a type");
+ let ty_canonical_name = iter.next()
+ .expect("--opaque-type expects a type");
options.opaque_types.insert(ty_canonical_name);
}
"--blacklist-type" => {
- let ty_canonical_name = iter.next().expect("--blacklist-type expects a type");
+ let ty_canonical_name = iter.next()
+ .expect("--blacklist-type expects a type");
options.hidden_types.insert(ty_canonical_name);
}
"--whitelist-type" => {
- let ty_pat = iter.next().expect("--whitelist-type expects a type pattern");
+ let ty_pat = iter.next()
+ .expect("--whitelist-type expects a type pattern");
options.whitelisted_types.insert(&ty_pat);
}
"--whitelist-function" => {
- let function_pat = iter.next().expect("--whitelist-function expects a pattern");
+ let function_pat = iter.next()
+ .expect("--whitelist-function expects a pattern");
options.whitelisted_functions.insert(&function_pat);
}
"--whitelist-var" => {
- let var_pat = iter.next().expect("--whitelist-var expects a pattern");
+ let var_pat = iter.next()
+ .expect("--whitelist-var expects a pattern");
options.whitelisted_vars.insert(&var_pat);
}
"--" => {
@@ -202,25 +208,31 @@ fn parse_args_or_exit(args: Vec<String>) -> (BindgenOptions, Box<io::Write>) {
pub fn main() {
log::set_logger(|max_log_level| {
- use env_logger::Logger;
- let env_logger = Logger::new();
- max_log_level.set(env_logger.filter());
- Box::new(env_logger)
- }).expect("Failed to set logger.");
+ use env_logger::Logger;
+ let env_logger = Logger::new();
+ max_log_level.set(env_logger.filter());
+ Box::new(env_logger)
+ })
+ .expect("Failed to set logger.");
let mut bind_args: Vec<_> = env::args().collect();
if let Some(clang) = clang_sys::support::Clang::find(None) {
- let has_clang_args = bind_args.iter().rposition(|arg| *arg == "--").is_some();
+ let has_clang_args =
+ bind_args.iter().rposition(|arg| *arg == "--").is_some();
if !has_clang_args {
bind_args.push("--".to_owned());
}
- // If --target is specified, assume caller knows what they're doing and don't mess with
+ // If --target is specified, assume caller knows what they're doing and
+ // don't mess with
// include paths for them
- let has_target_arg = bind_args.iter().rposition(|arg| arg.starts_with("--target")).is_some();
+ let has_target_arg = bind_args.iter()
+ .rposition(|arg| arg.starts_with("--target"))
+ .is_some();
if !has_target_arg {
- // TODO: distinguish C and C++ paths? C++'s should be enough, I guess.
+ // TODO: distinguish C and C++ paths? C++'s should be enough, I
+ // guess.
for path in clang.cpp_search_paths.into_iter() {
if let Ok(path) = path.into_os_string().into_string() {
bind_args.push("-isystem".to_owned());
@@ -233,8 +245,8 @@ pub fn main() {
let (options, out) = parse_args_or_exit(bind_args);
let bindings = Bindings::generate(options, None)
- .expect("Unable to generate bindings");
+ .expect("Unable to generate bindings");
bindings.write(out)
- .expect("Unable to write bindings to file.");
+ .expect("Unable to write bindings to file.");
}
diff --git a/src/clang.rs b/src/clang.rs
index ba6fc7f6..24d9e45e 100755
--- a/src/clang.rs
+++ b/src/clang.rs
@@ -3,27 +3,31 @@
#![allow(non_upper_case_globals, dead_code)]
-use std::os::raw::{c_uint, c_char, c_int, c_ulong, c_longlong};
+
+use clangll::*;
use std::{mem, ptr};
+use std::ffi::{CStr, CString};
use std::fmt;
use std::hash::Hash;
use std::hash::Hasher;
-use std::ffi::{CString, CStr};
-
-use clangll::*;
+use std::os::raw::{c_char, c_int, c_longlong, c_uint, c_ulong};
/// A cursor into the Clang AST, pointing to an AST node.
///
/// We call the AST node pointed to by the cursor the cursor's "referent".
#[derive(Copy, Clone)]
pub struct Cursor {
- x: CXCursor
+ x: CXCursor,
}
impl fmt::Debug for Cursor {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- write!(fmt, "Cursor({} kind: {}, loc: {}, usr: {:?})",
- self.spelling(), kind_to_str(self.kind()), self.location(), self.usr())
+ write!(fmt,
+ "Cursor({} kind: {}, loc: {}, usr: {:?})",
+ self.spelling(),
+ kind_to_str(self.kind()),
+ self.location(),
+ self.usr())
}
}
@@ -32,7 +36,8 @@ impl fmt::Debug for Cursor {
/// The first argument is the AST node currently being visited. The second
/// argument is the parent of the AST node currently being visited. The return
/// value informs how traversal should proceed.
-pub type CursorVisitor<'s> = for<'a, 'b> FnMut(&'a Cursor, &'b Cursor) -> Enum_CXChildVisitResult + 's;
+pub type CursorVisitor<'s> = for<'a, 'b> FnMut(&'a Cursor, &'b Cursor)
+ -> Enum_CXChildVisitResult + 's;
impl Cursor {
/// Get the Unified Symbol Resolution for this cursor's referent, if
@@ -40,12 +45,11 @@ impl Cursor {
///
/// The USR can be used to compare entities across translation units.
pub fn usr(&self) -> Option<String> {
- let s = String_ { x: unsafe { clang_getCursorUSR(self.x) } }.to_string();
- if s.is_empty() {
- None
- } else {
- Some(s)
- }
+ let s = String_ {
+ x: unsafe { clang_getCursorUSR(self.x) },
+ }
+ .to_string();
+ if s.is_empty() { None } else { Some(s) }
}
/// Is this cursor's referent a declaration?
@@ -55,13 +59,18 @@ impl Cursor {
/// Get the null cursor, which has no referent.
pub fn null() -> Self {
- Cursor { x: unsafe { clang_getNullCursor() } }
+ Cursor {
+ x: unsafe { clang_getNullCursor() },
+ }
}
/// Get this cursor's referent's spelling.
pub fn spelling(&self) -> String {
unsafe {
- String_ { x: clang_getCursorSpelling(self.x) }.to_string()
+ String_ {
+ x: clang_getCursorSpelling(self.x),
+ }
+ .to_string()
}
}
@@ -71,14 +80,20 @@ impl Cursor {
/// information, such as parameters for a function, etc.
pub fn display_name(&self) -> String {
unsafe {
- String_ { x: clang_getCursorDisplayName(self.x) }.to_string()
+ String_ {
+ x: clang_getCursorDisplayName(self.x),
+ }
+ .to_string()
}
}
/// Get the mangled name of this cursor's referent.
pub fn mangling(&self) -> String {
unsafe {
- String_ { x: clang_Cursor_getMangling(self.x) }.to_string()
+ String_ {
+ x: clang_Cursor_getMangling(self.x),
+ }
+ .to_string()
}
}
@@ -101,7 +116,9 @@ impl Cursor {
/// ```
pub fn lexical_parent(&self) -> Cursor {
unsafe {
- Cursor { x: clang_getCursorLexicalParent(self.x) }
+ Cursor {
+ x: clang_getCursorLexicalParent(self.x),
+ }
}
}
@@ -123,7 +140,9 @@ impl Cursor {
/// lexical parents.
pub fn semantic_parent(&self) -> Cursor {
unsafe {
- Cursor { x: clang_getCursorSemanticParent(self.x) }
+ Cursor {
+ x: clang_getCursorSemanticParent(self.x),
+ }
}
}
@@ -131,7 +150,7 @@ impl Cursor {
/// if the referent is either a template specialization or
/// declaration. Returns -1 otherwise.
pub fn num_template_args(&self) -> Option<u32> {
- let n : c_int = unsafe { clang_Cursor_getNumTemplateArguments(self.x) };
+ let n: c_int = unsafe { clang_Cursor_getNumTemplateArguments(self.x) };
if n >= 0 {
Some(n as u32)
@@ -165,8 +184,7 @@ impl Cursor {
while semantic_parent.kind() == CXCursor_Namespace ||
semantic_parent.kind() == CXCursor_NamespaceAlias ||
- semantic_parent.kind() == CXCursor_NamespaceRef
- {
+ semantic_parent.kind() == CXCursor_NamespaceRef {
semantic_parent = semantic_parent.semantic_parent();
}
@@ -177,16 +195,12 @@ impl Cursor {
/// Get the kind of referent this cursor is pointing to.
pub fn kind(&self) -> Enum_CXCursorKind {
- unsafe {
- clang_getCursorKind(self.x)
- }
+ unsafe { clang_getCursorKind(self.x) }
}
/// Is the referent an anonymous record definition?
pub fn is_anonymous(&self) -> bool {
- unsafe {
- clang_Cursor_isAnonymous(self.x) != 0
- }
+ unsafe { clang_Cursor_isAnonymous(self.x) != 0 }
}
/// Is the referent a template specialization?
@@ -208,34 +222,35 @@ impl Cursor {
}
let parent = self.semantic_parent();
(parent.is_template() && !parent.is_fully_specialized_template()) ||
- parent.is_in_non_fully_specialized_template()
+ parent.is_in_non_fully_specialized_template()
}
/// Is this cursor pointing a valid referent?
pub fn is_valid(&self) -> bool {
- unsafe {
- clang_isInvalid(self.kind()) == 0
- }
+ unsafe { clang_isInvalid(self.kind()) == 0 }
}
/// Get the source location for the referent.
pub fn location(&self) -> SourceLocation {
unsafe {
- SourceLocation { x: clang_getCursorLocation(self.x) }
+ SourceLocation {
+ x: clang_getCursorLocation(self.x),
+ }
}
}
/// Get the source location range for the referent.
pub fn extent(&self) -> CXSourceRange {
- unsafe {
- clang_getCursorExtent(self.x)
- }
+ unsafe { clang_getCursorExtent(self.x) }
}
/// Get the raw declaration comment for this referent, if one exists.
pub fn raw_comment(&self) -> Option<String> {
let s = unsafe {
- String_ { x: clang_Cursor_getRawCommentText(self.x) }.to_string()
+ String_ {
+ x: clang_Cursor_getRawCommentText(self.x),
+ }
+ .to_string()
};
if s.is_empty() { None } else { Some(s) }
}
@@ -243,14 +258,18 @@ impl Cursor {
/// Get the referent's parsed comment.
pub fn comment(&self) -> Comment {
unsafe {
- Comment { x: clang_Cursor_getParsedComment(self.x) }
+ Comment {
+ x: clang_Cursor_getParsedComment(self.x),
+ }
}
}
/// Get the referent's type.
pub fn cur_type(&self) -> Type {
unsafe {
- Type { x: clang_getCursorType(self.x) }
+ Type {
+ x: clang_getCursorType(self.x),
+ }
}
}
@@ -259,7 +278,9 @@ impl Cursor {
/// the declared thing.
pub fn definition(&self) -> Cursor {
unsafe {
- Cursor { x: clang_getCursorDefinition(self.x) }
+ Cursor {
+ x: clang_getCursorDefinition(self.x),
+ }
}
}
@@ -267,7 +288,9 @@ impl Cursor {
/// pointing to the referenced type.
pub fn referenced(&self) -> Cursor {
unsafe {
- Cursor { x: clang_getCursorReferenced(self.x) }
+ Cursor {
+ x: clang_getCursorReferenced(self.x),
+ }
}
}
@@ -278,7 +301,9 @@ impl Cursor {
/// referent type.
pub fn canonical(&self) -> Cursor {
unsafe {
- Cursor { x: clang_getCanonicalCursor(self.x) }
+ Cursor {
+ x: clang_getCanonicalCursor(self.x),
+ }
}
}
@@ -286,7 +311,9 @@ impl Cursor {
/// pointing to the template definition that is being specialized.
pub fn specialized(&self) -> Cursor {
unsafe {
- Cursor { x: clang_getSpecializedCursorTemplate(self.x) }
+ Cursor {
+ x: clang_getSpecializedCursorTemplate(self.x),
+ }
}
}
@@ -302,10 +329,15 @@ impl Cursor {
/// for details on arguments passed to the function and how its return value
/// is interpreted.
pub fn visit<F>(&self, func: F)
- where F: for<'a, 'b> FnMut(&'a Cursor, &'b Cursor) -> Enum_CXChildVisitResult
+ where F: for<'a, 'b> FnMut(&'a Cursor, &'b Cursor)
+ -> Enum_CXChildVisitResult,
{
let mut data: Box<CursorVisitor> = Box::new(func);
- let opt_visit = Some(visit_children as extern "C" fn(CXCursor, CXCursor, CXClientData) -> Enum_CXChildVisitResult);
+ let opt_visit =
+ Some(visit_children as extern "C" fn(CXCursor,
+ CXCursor,
+ CXClientData)
+ -> Enum_CXChildVisitResult);
unsafe {
clang_visitChildren(self.x, opt_visit, mem::transmute(&mut data));
}
@@ -332,11 +364,7 @@ impl Cursor {
pub fn bit_width(&self) -> Option<u32> {
unsafe {
let w = clang_getFieldDeclBitWidth(self.x);
- if w == -1 {
- None
- } else {
- Some(w as u32)
- }
+ if w == -1 { None } else { Some(w as u32) }
}
}
@@ -344,7 +372,9 @@ impl Cursor {
/// enum type.
pub fn enum_type(&self) -> Type {
unsafe {
- Type { x: clang_getEnumDeclIntegerType(self.x) }
+ Type {
+ x: clang_getEnumDeclIntegerType(self.x),
+ }
}
}
@@ -354,9 +384,7 @@ impl Cursor {
/// which is also a valid enum value, so callers should check the cursor
/// kind before calling this method (see issue #127).
pub fn enum_val_signed(&self) -> i64 {
- unsafe {
- clang_getEnumConstantDeclValue(self.x) as i64
- }
+ unsafe { clang_getEnumConstantDeclValue(self.x) as i64 }
}
/// Get the unsigned constant value for this cursor's enum variant referent.
@@ -365,16 +393,16 @@ impl Cursor {
/// which is also a valid enum value, so callers should check the cursor
/// kind before calling this method (see issue #128).
pub fn enum_val_unsigned(&self) -> u64 {
- unsafe {
- clang_getEnumConstantDeclUnsignedValue(self.x) as u64
- }
+ unsafe { clang_getEnumConstantDeclUnsignedValue(self.x) as u64 }
}
/// Given that this cursor's referent is a `typedef`, get the `Type` that is
/// being aliased.
pub fn typedef_type(&self) -> Type {
unsafe {
- Type { x: clang_getTypedefDeclUnderlyingType(self.x) }
+ Type {
+ x: clang_getTypedefDeclUnderlyingType(self.x),
+ }
}
}
@@ -382,16 +410,12 @@ impl Cursor {
///
/// This only applies to functions and variables.
pub fn linkage(&self) -> Enum_CXLinkageKind {
- unsafe {
- clang_getCursorLinkage(self.x)
- }
+ unsafe { clang_getCursorLinkage(self.x) }
}
/// Get the visibility of this cursor's referent.
pub fn visibility(&self) -> Enum_CXVisibilityKind {
- unsafe {
- clang_getCursorVisibility(self.x)
- }
+ unsafe { clang_getCursorVisibility(self.x) }
}
/// Given that this cursor's referent is a function, return cursors to its
@@ -401,7 +425,9 @@ impl Cursor {
let num = self.num_args().expect("expected value, got none") as u32;
let mut args = vec![];
for i in 0..num {
- args.push(Cursor { x: clang_Cursor_getArgument(self.x, i as c_uint) });
+ args.push(Cursor {
+ x: clang_Cursor_getArgument(self.x, i as c_uint),
+ });
}
args
}
@@ -411,7 +437,9 @@ impl Cursor {
/// declaration, return a cursor to its return type.
pub fn ret_type(&self) -> Type {
unsafe {
- Type { x: clang_getCursorResultType(self.x) }
+ Type {
+ x: clang_getCursorResultType(self.x),
+ }
}
}
@@ -423,55 +451,39 @@ impl Cursor {
pub fn num_args(&self) -> Result<u32, ()> {
unsafe {
let w = clang_Cursor_getNumArguments(self.x);
- if w == -1 {
- Err(())
- } else {
- Ok(w as u32)
- }
+ if w == -1 { Err(()) } else { Ok(w as u32) }
}
}
/// Get the access specifier for this cursor's referent.
pub fn access_specifier(&self) -> Enum_CX_CXXAccessSpecifier {
- unsafe {
- clang_getCXXAccessSpecifier(self.x)
- }
+ unsafe { clang_getCXXAccessSpecifier(self.x) }
}
/// Is this cursor's referent a field declaration that is marked as
/// `mutable`?
pub fn is_mutable_field(&self) -> bool {
- unsafe {
- clang_CXXField_isMutable(self.x) != 0
- }
+ unsafe { clang_CXXField_isMutable(self.x) != 0 }
}
/// Is this cursor's referent a member function that is declared `static`?
pub fn method_is_static(&self) -> bool {
- unsafe {
- clang_CXXMethod_isStatic(self.x) != 0
- }
+ unsafe { clang_CXXMethod_isStatic(self.x) != 0 }
}
/// Is this cursor's referent a member function that is declared `const`?
pub fn method_is_const(&self) -> bool {
- unsafe {
- clang_CXXMethod_isConst(self.x) != 0
- }
+ unsafe { clang_CXXMethod_isConst(self.x) != 0 }
}
/// Is this cursor's referent a member function that is declared `const`?
pub fn method_is_virtual(&self) -> bool {
- unsafe {
- clang_CXXMethod_isVirtual(self.x) != 0
- }
+ unsafe { clang_CXXMethod_isVirtual(self.x) != 0 }
}
/// Is this cursor's referent a struct or class with virtual members?
pub fn is_virtual_base(&self) -> bool {
- unsafe {
- clang_isVirtualBase(self.x) != 0
- }
+ unsafe { clang_isVirtualBase(self.x) != 0 }
}
/// Given that this cursor's referent is a template specialization or
@@ -480,32 +492,33 @@ impl Cursor {
/// If the referent is not a template or `i` is out of bounds, an invalid
/// kind is returned.
pub fn template_arg_kind(&self, i: c_int) -> CXTemplateArgumentKind {
- unsafe {
- clang_Cursor_getTemplateArgumentKind(self.x, i as c_uint)
- }
+ unsafe { clang_Cursor_getTemplateArgumentKind(self.x, i as c_uint) }
}
/// Given that this cursor's referent is a template specialization, and that
/// the `i`th template argument is an integral, get the `i`th template
/// argument value.
pub fn template_arg_value(&self, i: c_int) -> c_longlong {
- unsafe {
- clang_Cursor_getTemplateArgumentValue(self.x, i as c_uint)
- }
+ unsafe { clang_Cursor_getTemplateArgumentValue(self.x, i as c_uint) }
}
}
-extern fn visit_children(cur: CXCursor, parent: CXCursor,
- data: CXClientData) -> Enum_CXChildVisitResult {
+extern "C" fn visit_children(cur: CXCursor,
+ parent: CXCursor,
+ data: CXClientData)
+ -> Enum_CXChildVisitResult {
let func: &mut Box<CursorVisitor> = unsafe { mem::transmute(data) };
- (*func)(&Cursor { x : cur }, &Cursor { x: parent })
+ (*func)(&Cursor {
+ x: cur,
+ },
+ &Cursor {
+ x: parent,
+ })
}
impl PartialEq for Cursor {
fn eq(&self, other: &Cursor) -> bool {
- unsafe {
- clang_equalCursors(self.x, other.x) == 1
- }
+ unsafe { clang_equalCursors(self.x, other.x) == 1 }
}
}
@@ -520,14 +533,12 @@ impl Hash for Cursor {
/// The type of a node in clang's AST.
#[derive(Clone, Hash)]
pub struct Type {
- x: CXType
+ x: CXType,
}
impl PartialEq for Type {
fn eq(&self, other: &Self) -> bool {
- unsafe {
- clang_equalTypes(self.x, other.x) != 0
- }
+ unsafe { clang_equalTypes(self.x, other.x) != 0 }
}
}
@@ -535,8 +546,11 @@ impl Eq for Type {}
impl fmt::Debug for Type {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
- write!(fmt, "Type({}, kind: {}, decl: {:?}, canon: {:?})",
- self.spelling(), type_to_str(self.kind()), self.declaration(),
+ write!(fmt,
+ "Type({}, kind: {}, decl: {:?}, canon: {:?})",
+ self.spelling(),
+ type_to_str(self.kind()),
+ self.declaration(),
self.declaration().canonical())
}
}
@@ -582,22 +596,25 @@ impl Type {
/// Get a cursor pointing to this type's declaration.
pub fn declaration(&self) -> Cursor {
unsafe {
- Cursor { x: clang_getTypeDeclaration(self.x) }
+ Cursor {
+ x: clang_getTypeDeclaration(self.x),
+ }
}
}
/// Get a raw display name for this type.
pub fn spelling(&self) -> String {
unsafe {
- String_ { x: clang_getTypeSpelling(self.x) }.to_string()
+ String_ {
+ x: clang_getTypeSpelling(self.x),
+ }
+ .to_string()
}
}
/// Is this type const qualified?
pub fn is_const(&self) -> bool {
- unsafe {
- clang_isConstQualifiedType(self.x) != 0
- }
+ unsafe { clang_isConstQualifiedType(self.x) != 0 }
}
/// What is the size of this type? Paper over invalid types by returning `0`
@@ -657,7 +674,7 @@ impl Type {
Some(TypeTemplateArgIterator {
x: self.x,
length: n as u32,
- index: 0
+ index: 0,
})
} else {
debug_assert_eq!(n, -1);
@@ -669,14 +686,18 @@ impl Type {
/// to.
pub fn pointee_type(&self) -> Type {
unsafe {
- Type { x: clang_getPointeeType(self.x) }
+ Type {
+ x: clang_getPointeeType(self.x),
+ }
}
}
/// Given that this type is an array, vector, or complex type, return the
/// type of its elements.
pub fn elem_type(&self) -> Option<Type> {
- let current_type = Type { x: unsafe { clang_getElementType(self.x) } };
+ let current_type = Type {
+ x: unsafe { clang_getElementType(self.x) },
+ };
if current_type.kind() != CXType_Invalid {
Some(current_type)
} else {
@@ -699,15 +720,15 @@ impl Type {
/// aliases to get the underlying, canonical type.
pub fn canonical_type(&self) -> Type {
unsafe {
- Type { x: clang_getCanonicalType(self.x) }
+ Type {
+ x: clang_getCanonicalType(self.x),
+ }
}
}
/// Is this type a variadic function type?
pub fn is_variadic(&self) -> bool {
- unsafe {
- clang_isFunctionTypeVariadic(self.x) != 0
- }
+ unsafe { clang_isFunctionTypeVariadic(self.x) != 0 }
}
/// Given that this type is a function type, get the types of its
@@ -715,9 +736,11 @@ impl Type {
pub fn arg_types(&self) -> Vec<Type> {
unsafe {
let num = clang_getNumArgTypes(self.x) as usize;
- let mut args = vec!();
+ let mut args = vec![];
for i in 0..num {
- args.push(Type { x: clang_getArgType(self.x, i as c_uint) });
+ args.push(Type {
+ x: clang_getArgType(self.x, i as c_uint),
+ });
}
args
}
@@ -726,7 +749,9 @@ impl Type {
/// Given that this type is a function type, get the type of its return
/// value.
pub fn ret_type(&self) -> Option<Type> {
- let rt = Type { x: unsafe { clang_getResultType(self.x) } };
+ let rt = Type {
+ x: unsafe { clang_getResultType(self.x) },
+ };
if rt.kind() == CXType_Invalid {
None
} else {
@@ -737,9 +762,7 @@ impl Type {
/// Given that this type is a function type, get its calling convention. If
/// this is not a function type, `CXCallingConv_Invalid` is returned.
pub fn call_conv(&self) -> Enum_CXCallingConv {
- unsafe {
- clang_getFunctionTypeCallingConv(self.x)
- }
+ unsafe { clang_getFunctionTypeCallingConv(self.x) }
}
/// For elaborated types (types which use `class`, `struct`, or `union` to
@@ -747,7 +770,9 @@ impl Type {
#[cfg(not(feature="llvm_stable"))]
pub fn named(&self) -> Type {
unsafe {
- Type { x: clang_Type_getNamedType(self.x) }
+ Type {
+ x: clang_Type_getNamedType(self.x),
+ }
}
}
}
@@ -756,7 +781,7 @@ impl Type {
pub struct TypeTemplateArgIterator {
x: CXType,
length: u32,
- index: u32
+ index: u32,
}
impl Iterator for TypeTemplateArgIterator {
@@ -765,7 +790,9 @@ impl Iterator for TypeTemplateArgIterator {
if self.index < self.length {
let idx = self.index as c_int;
self.index += 1;
- Some(Type { x: unsafe { clang_Type_getTemplateArgumentAsType(self.x, idx) } })
+ Some(Type {
+ x: unsafe { clang_Type_getTemplateArgumentAsType(self.x, idx) },
+ })
} else {
None
}
@@ -782,7 +809,7 @@ impl ExactSizeIterator for TypeTemplateArgIterator {
/// A `SourceLocation` is a file, line, column, and byte offset location for
/// some source text.
pub struct SourceLocation {
- x: CXSourceLocation
+ x: CXSourceLocation,
}
impl SourceLocation {
@@ -794,8 +821,17 @@ impl SourceLocation {
let mut line = 0;
let mut col = 0;
let mut off = 0;
- clang_getSpellingLocation(self.x, &mut file, &mut line, &mut col, &mut off);
- (File { x: file }, line as usize, col as usize, off as usize)
+ clang_getSpellingLocation(self.x,
+ &mut file,
+ &mut line,
+ &mut col,
+ &mut off);
+ (File {
+ x: file,
+ },
+ line as usize,
+ col as usize,
+ off as usize)
}
}
}
@@ -815,15 +851,13 @@ impl fmt::Display for SourceLocation {
///
/// Comments are sort of parsed by Clang, and have a tree structure.
pub struct Comment {
- x: CXComment
+ x: CXComment,
}
impl Comment {
/// What kind of comment is this?
pub fn kind(&self) -> Enum_CXCommentKind {
- unsafe {
- clang_Comment_getKind(self.x)
- }
+ unsafe { clang_Comment_getKind(self.x) }
}
/// Get this comment's children comment
@@ -831,7 +865,7 @@ impl Comment {
CommentChildrenIterator {
parent: self.x,
length: unsafe { clang_Comment_getNumChildren(self.x) },
- index: 0
+ index: 0,
}
}
@@ -839,7 +873,10 @@ impl Comment {
/// name.
pub fn get_tag_name(&self) -> String {
unsafe {
- String_ { x: clang_HTMLTagComment_getTagName(self.x) }.to_string()
+ String_ {
+ x: clang_HTMLTagComment_getTagName(self.x),
+ }
+ .to_string()
}
}
@@ -848,7 +885,7 @@ impl Comment {
CommentAttributesIterator {
x: self.x,
length: unsafe { clang_HTMLStartTag_getNumAttrs(self.x) },
- index: 0
+ index: 0,
}
}
}
@@ -857,7 +894,7 @@ impl Comment {
pub struct CommentChildrenIterator {
parent: CXComment,
length: c_uint,
- index: c_uint
+ index: c_uint,
}
impl Iterator for CommentChildrenIterator {
@@ -866,7 +903,9 @@ impl Iterator for CommentChildrenIterator {
if self.index < self.length {
let idx = self.index;
self.index += 1;
- Some( Comment { x: unsafe { clang_Comment_getChild(self.parent, idx) } } )
+ Some(Comment {
+ x: unsafe { clang_Comment_getChild(self.parent, idx) },
+ })
} else {
None
}
@@ -878,14 +917,14 @@ pub struct CommentAttribute {
/// HTML start tag attribute name
pub name: String,
/// HTML start tag attribute value
- pub value: String
+ pub value: String,
}
/// An iterator for a comment's attributes
pub struct CommentAttributesIterator {
x: CXComment,
length: c_uint,
- index: c_uint
+ index: c_uint,
}
impl Iterator for CommentAttributesIterator {
@@ -894,9 +933,19 @@ impl Iterator for CommentAttributesIterator {
if self.index < self.length {
let idx = self.index;
self.index += 1;
- Some( CommentAttribute {
- name: String_ { x: unsafe { clang_HTMLStartTag_getAttrName(self.x, idx) } }.to_string(),
- value: String_ { x: unsafe { clang_HTMLStartTag_getAttrValue(self.x, idx) } }.to_string()
+ Some(CommentAttribute {
+ name: String_ {
+ x: unsafe {
+ clang_HTMLStartTag_getAttrName(self.x, idx)
+ },
+ }
+ .to_string(),
+ value: String_ {
+ x: unsafe {
+ clang_HTMLStartTag_getAttrValue(self.x, idx)
+ },
+ }
+ .to_string(),
})
} else {
None
@@ -906,7 +955,7 @@ impl Iterator for CommentAttributesIterator {
/// A source file.
pub struct File {
- x: CXFile
+ x: CXFile,
}
impl File {
@@ -916,14 +965,17 @@ impl File {
return None;
}
unsafe {
- Some(String_ { x: clang_getFileName(self.x) }.to_string())
+ Some(String_ {
+ x: clang_getFileName(self.x),
+ }
+ .to_string())
}
}
}
/// A Clang string.
pub struct String_ {
- x: CXString
+ x: CXString,
}
impl fmt::Display for String_ {
@@ -942,7 +994,7 @@ impl fmt::Display for String_ {
/// An `Index` is an environment for a set of translation units that will
/// typically end up linked together in one final binary.
pub struct Index {
- x: CXIndex
+ x: CXIndex,
}
impl Index {
@@ -954,7 +1006,9 @@ impl Index {
/// The `diag` parameter controls whether debugging diagnostics are enabled.
pub fn new(pch: bool, diag: bool) -> Index {
unsafe {
- Index { x: clang_createIndex(pch as c_int, diag as c_int) }
+ Index {
+ x: clang_createIndex(pch as c_int, diag as c_int),
+ }
}
}
}
@@ -984,7 +1038,7 @@ pub struct Token {
/// A translation unit (or "compilation unit").
pub struct TranslationUnit {
- x: CXTranslationUnit
+ x: CXTranslationUnit,
}
impl fmt::Debug for TranslationUnit {
@@ -995,14 +1049,22 @@ impl fmt::Debug for TranslationUnit {
impl TranslationUnit {
/// Parse a source file into a translation unit.
- pub fn parse(ix: &Index, file: &str, cmd_args: &[String],
- unsaved: &[UnsavedFile], opts: ::libc::c_uint) -> Option<TranslationUnit> {
+ pub fn parse(ix: &Index,
+ file: &str,
+ cmd_args: &[String],
+ unsaved: &[UnsavedFile],
+ opts: ::libc::c_uint)
+ -> Option<TranslationUnit> {
let fname = CString::new(file).unwrap();
- let _c_args: Vec<CString> = cmd_args.iter().map(|s| CString::new(s.clone()).unwrap()).collect();
- let c_args: Vec<*const c_char> = _c_args.iter().map(|s| s.as_ptr()).collect();
- let mut c_unsaved: Vec<Struct_CXUnsavedFile> = unsaved.iter().map(|f| f.x).collect();
+ let _c_args: Vec<CString> =
+ cmd_args.iter().map(|s| CString::new(s.clone()).unwrap()).collect();
+ let c_args: Vec<*const c_char> =
+ _c_args.iter().map(|s| s.as_ptr()).collect();
+ let mut c_unsaved: Vec<Struct_CXUnsavedFile> =
+ unsaved.iter().map(|f| f.x).collect();
let tu = unsafe {
- clang_parseTranslationUnit(ix.x, fname.as_ptr(),
+ clang_parseTranslationUnit(ix.x,
+ fname.as_ptr(),
c_args.as_ptr(),
c_args.len() as c_int,
c_unsaved.as_mut_ptr(),
@@ -1012,14 +1074,17 @@ impl TranslationUnit {
if tu.is_null() {
None
} else {
- Some(TranslationUnit { x: tu })
+ Some(TranslationUnit {
+ x: tu,
+ })
}
}
/// Reparse this translation unit, maybe because the file changed on disk or
/// something like that.
pub fn reparse(&self, unsaved: &[UnsavedFile], opts: usize) -> bool {
- let mut c_unsaved: Vec<Struct_CXUnsavedFile> = unsaved.iter().map(|f| f.x).collect();
+ let mut c_unsaved: Vec<Struct_CXUnsavedFile> =
+ unsaved.iter().map(|f| f.x).collect();
unsafe {
clang_reparseTranslationUnit(self.x,
@@ -1034,9 +1099,11 @@ impl TranslationUnit {
pub fn diags(&self) -> Vec<Diagnostic> {
unsafe {
let num = clang_getNumDiagnostics(self.x) as usize;
- let mut diags = vec!();
+ let mut diags = vec![];
for i in 0..num {
- diags.push(Diagnostic { x: clang_getDiagnostic(self.x, i as c_uint) });
+ diags.push(Diagnostic {
+ x: clang_getDiagnostic(self.x, i as c_uint),
+ });
}
diags
}
@@ -1045,7 +1112,9 @@ impl TranslationUnit {
/// Get a cursor pointing to the root of this translation unit's AST.
pub fn cursor(&self) -> Cursor {
unsafe {
- Cursor { x: clang_getTranslationUnitCursor(self.x) }
+ Cursor {
+ x: clang_getTranslationUnitCursor(self.x),
+ }
}
}
@@ -1061,16 +1130,23 @@ impl TranslationUnit {
let mut tokens = vec![];
unsafe {
let mut token_ptr = ::std::ptr::null_mut();
- let mut num_tokens : c_uint = 0;
+ let mut num_tokens: c_uint = 0;
clang_tokenize(self.x, range, &mut token_ptr, &mut num_tokens);
if token_ptr.is_null() {
return None;
}
- let token_array = ::std::slice::from_raw_parts(token_ptr, num_tokens as usize);
+ let token_array = ::std::slice::from_raw_parts(token_ptr,
+ num_tokens as usize);
for &token in token_array.iter() {
let kind = clang_getTokenKind(token);
- let spelling = String_ { x: clang_getTokenSpelling(self.x, token) }.to_string();
- tokens.push(Token { kind: kind, spelling: spelling });
+ let spelling = String_ {
+ x: clang_getTokenSpelling(self.x, token),
+ }
+ .to_string();
+ tokens.push(Token {
+ kind: kind,
+ spelling: spelling,
+ });
}
clang_disposeTokens(self.x, token_ptr, num_tokens);
}
@@ -1089,30 +1165,29 @@ impl Drop for TranslationUnit {
/// A diagnostic message generated while parsing a translation unit.
pub struct Diagnostic {
- x: CXDiagnostic
+ x: CXDiagnostic,
}
impl Diagnostic {
/// Get the default diagnostic display option bit flags.
pub fn default_opts() -> usize {
- unsafe {
- clang_defaultDiagnosticDisplayOptions() as usize
- }
+ unsafe { clang_defaultDiagnosticDisplayOptions() as usize }
}
/// Format this diagnostic message as a string, using the given option bit
/// flags.
pub fn format(&self, opts: usize) -> String {
unsafe {
- String_ { x: clang_formatDiagnostic(self.x, opts as c_uint) }.to_string()
+ String_ {
+ x: clang_formatDiagnostic(self.x, opts as c_uint),
+ }
+ .to_string()
}
}
/// What is the severity of this diagnostic message?
pub fn severity(&self) -> Enum_CXDiagnosticSeverity {
- unsafe {
- clang_getDiagnosticSeverity(self.x)
- }
+ unsafe { clang_getDiagnosticSeverity(self.x) }
}
}
@@ -1129,7 +1204,7 @@ impl Drop for Diagnostic {
pub struct UnsavedFile {
x: Struct_CXUnsavedFile,
name: CString,
- contents: CString
+ contents: CString,
}
impl UnsavedFile {
@@ -1145,7 +1220,7 @@ impl UnsavedFile {
UnsavedFile {
x: x,
name: name,
- contents: contents
+ contents: contents,
}
}
}
@@ -1310,8 +1385,8 @@ pub fn kind_to_str(x: Enum_CXCursorKind) -> &'static str {
CXCursor_MacroExpansion => "MacroExpansion",
// CXCursor_MacroInstantiation => "MacroInstantiation",
CXCursor_InclusionDirective => "InclusionDirective",
- //CXCursor_FirstPreprocessing => "FirstPreprocessing",
- //CXCursor_LastPreprocessing => "LastPreprocessing",
+ // CXCursor_FirstPreprocessing => "FirstPreprocessing",
+ // CXCursor_LastPreprocessing => "LastPreprocessing",
CXCursor_PackedAttr => "PackedAttr",
CXCursor_ModuleImportDecl => "ModuleImportDecl",
CXCursor_TypeAliasTemplateDecl => "TypeAliasTemplateDecl",
@@ -1327,15 +1402,15 @@ pub fn type_to_str(x: Enum_CXTypeKind) -> &'static str {
CXType_Unexposed => "Unexposed",
CXType_Void => "Void",
CXType_Bool => "Bool",
- CXType_Char_U => "Char_U",
+ CXType_Char_U => "Char_U",
CXType_UChar => "UChar",
- CXType_Char16=> "Char16",
- CXType_Char32=> "Char32",
+ CXType_Char16 => "Char16",
+ CXType_Char32 => "Char32",
CXType_UShort => "UShort",
CXType_UInt => "UInt",
CXType_ULong => "ULong",
CXType_ULongLong => "ULongLong",
- CXType_UInt128=>"UInt128",
+ CXType_UInt128 => "UInt128",
CXType_Char_S => "Char_S",
CXType_SChar => "SChar",
CXType_WChar => "WChar",
@@ -1343,7 +1418,7 @@ pub fn type_to_str(x: Enum_CXTypeKind) -> &'static str {
CXType_Int => "Int",
CXType_Long => "Long",
CXType_LongLong => "LongLong",
- CXType_Int128=>"Int128",
+ CXType_Int128 => "Int128",
CXType_Float => "Float",
CXType_Double => "Double",
CXType_LongDouble => "LongDouble",
@@ -1377,12 +1452,12 @@ pub fn type_to_str(x: Enum_CXTypeKind) -> &'static str {
CXType_Auto => "Auto",
#[cfg(not(feature="llvm_stable"))]
CXType_Elaborated => "Elaborated",
- _ => "?"
+ _ => "?",
}
}
/// Dump the Clang AST to stdout for debugging purposes.
-pub fn ast_dump(c: &Cursor, depth: isize)-> Enum_CXVisitorResult {
+pub fn ast_dump(c: &Cursor, depth: isize) -> Enum_CXVisitorResult {
fn print_indent(depth: isize, s: &str) {
let mut i = 0;
while i < depth {
@@ -1392,14 +1467,12 @@ pub fn ast_dump(c: &Cursor, depth: isize)-> Enum_CXVisitorResult {
println!("{}", s);
}
let ct = c.cur_type().kind();
- print_indent(depth, &format!("({} {} {}",
- kind_to_str(c.kind()),
- c.spelling(),
- type_to_str(ct))
- );
- c.visit(| s, _: &Cursor| {
- ast_dump(s, depth + 1)
- });
+ print_indent(depth,
+ &format!("({} {} {}",
+ kind_to_str(c.kind()),
+ c.spelling(),
+ type_to_str(ct)));
+ c.visit(|s, _: &Cursor| ast_dump(s, depth + 1));
print_indent(depth, ")");
CXChildVisit_Continue
}
diff --git a/src/codegen/mod.rs b/src/codegen/mod.rs
index a656c2c1..a4d717d3 100755
--- a/src/codegen/mod.rs
+++ b/src/codegen/mod.rs
@@ -1,32 +1,32 @@
mod helpers;
-use self::helpers::{attributes, BlobTyBuilder};
+use aster;
+use ir::annotations::FieldAccessorKind;
+use ir::comp::{CompInfo, CompKind, Field, Method};
use ir::context::BindgenContext;
-use ir::item::{Item, ItemId, ItemCanonicalName, ItemCanonicalPath};
-use ir::ty::{Type, TypeKind};
-use ir::int::IntKind;
-use ir::module::Module;
-use ir::var::Var;
use ir::enum_ty::Enum;
use ir::function::{Function, FunctionSig};
+use ir::int::IntKind;
+use ir::item::{Item, ItemCanonicalName, ItemCanonicalPath, ItemId};
use ir::item_kind::ItemKind;
-use ir::comp::{CompKind, CompInfo, Field, Method};
use ir::layout::Layout;
-use ir::annotations::FieldAccessorKind;
+use ir::module::Module;
+use ir::ty::{Type, TypeKind};
use ir::type_collector::{ItemSet, TypeCollector};
-
-use std::ops;
+use ir::var::Var;
+use self::helpers::{BlobTyBuilder, attributes};
use std::borrow::Cow;
-use std::mem;
use std::collections::HashSet;
-use std::collections::hash_map::{HashMap, Entry};
+use std::collections::hash_map::{Entry, HashMap};
+use std::mem;
+
+use std::ops;
use syntax::abi::Abi;
use syntax::ast;
use syntax::codemap::{Span, respan};
use syntax::ptr::P;
-use aster;
fn root_import(ctx: &BindgenContext) -> P<ast::Item> {
assert!(ctx.options().enable_cxx_namespaces, "Somebody messed it up");
@@ -39,7 +39,8 @@ struct CodegenResult {
items: Vec<P<ast::Item>>,
saw_union: bool,
items_seen: HashSet<ItemId>,
- /// The set of generated function/var names, needed because in C/C++ is legal to
+ /// The set of generated function/var names, needed because in C/C++ is
+ /// legal to
/// do something like:
///
/// ```c++
@@ -99,7 +100,7 @@ impl CodegenResult {
}
fn inner<F>(&mut self, cb: F) -> Vec<P<ast::Item>>
- where F: FnOnce(&mut Self)
+ where F: FnOnce(&mut Self),
{
let mut new = Self::new();
@@ -135,7 +136,7 @@ impl ForeignModBuilder {
inner: ast::ForeignMod {
abi: abi,
items: vec![],
- }
+ },
}
}
@@ -146,7 +147,7 @@ impl ForeignModBuilder {
#[allow(dead_code)]
fn with_foreign_items<I>(mut self, items: I) -> Self
- where I: IntoIterator<Item=ast::ForeignItem>
+ where I: IntoIterator<Item = ast::ForeignItem>,
{
self.inner.items.extend(items.into_iter());
self
@@ -182,7 +183,7 @@ impl ToPtr for P<ast::Ty> {
ast::Mutability::Immutable
} else {
ast::Mutability::Mutable
- }
+ },
});
P(ast::Ty {
id: ast::DUMMY_NODE_ID,
@@ -217,20 +218,21 @@ impl CodeGenerator for Item {
match *self.kind() {
ItemKind::Module(ref module) => {
- if !ctx.options().enable_cxx_namespaces && self.id() == ctx.root_module() {
+ if !ctx.options().enable_cxx_namespaces &&
+ self.id() == ctx.root_module() {
return;
}
module.codegen(ctx, result, self);
- },
+ }
ItemKind::Function(ref fun) => {
if !ctx.options().ignore_functions {
fun.codegen(ctx, result, self);
}
- },
+ }
ItemKind::Var(ref var) => {
var.codegen(ctx, result, self);
- },
+ }
ItemKind::Type(ref ty) => {
ty.codegen(ctx, result, self);
}
@@ -265,8 +267,10 @@ impl CodeGenerator for Module {
});
let name = item.canonical_name(ctx);
- let item = aster::AstBuilder::new().item().pub_()
- .build_item_kind(name, module);
+ let item = aster::AstBuilder::new()
+ .item()
+ .pub_()
+ .build_item_kind(name, module);
result.push(item);
}
@@ -288,9 +292,13 @@ impl CodeGenerator for Var {
let ty = self.ty().to_rust_ty(ctx);
if let Some(val) = self.val() {
- let const_item = aster::AstBuilder::new().item().pub_()
- .const_(canonical_name)
- .expr().int(val).build(ty);
+ let const_item = aster::AstBuilder::new()
+ .item()
+ .pub_()
+ .const_(canonical_name)
+ .expr()
+ .int(val)
+ .build(ty);
result.push(const_item)
} else {
let mut attrs = vec![];
@@ -310,8 +318,8 @@ impl CodeGenerator for Var {
};
let item = ForeignModBuilder::new(Abi::C)
- .with_foreign_item(item)
- .build(ctx);
+ .with_foreign_item(item)
+ .build(ctx);
result.push(item);
}
}
@@ -368,7 +376,8 @@ impl CodeGenerator for Type {
return;
}
- let mut applicable_template_args = item.applicable_template_args(ctx);
+ let mut applicable_template_args =
+ item.applicable_template_args(ctx);
let inner_rust_type = if item.is_opaque(ctx) {
applicable_template_args.clear();
// Pray if there's no layout.
@@ -394,7 +403,8 @@ impl CodeGenerator for Type {
error!("Item contained `typename`'d template param: {:?}", item);
return;
}
- generics = generics.ty_param_id(template_arg.name().unwrap());
+ generics =
+ generics.ty_param_id(template_arg.name().unwrap());
}
}
@@ -402,8 +412,9 @@ impl CodeGenerator for Type {
result.push(typedef)
}
TypeKind::Enum(ref ei) => ei.codegen(ctx, result, item),
- ref u @ TypeKind::UnresolvedTypeRef(..)
- => unreachable!("Should have been resolved after parsing {:?}!", u),
+ ref u @ TypeKind::UnresolvedTypeRef(..) => {
+ unreachable!("Should have been resolved after parsing {:?}!", u)
+ }
}
}
}
@@ -417,7 +428,10 @@ struct Vtable<'a> {
}
impl<'a> Vtable<'a> {
- fn new(item_id: ItemId, methods: &'a [Method], base_classes: &'a [ItemId]) -> Self {
+ fn new(item_id: ItemId,
+ methods: &'a [Method],
+ base_classes: &'a [ItemId])
+ -> Self {
Vtable {
item_id: item_id,
methods: methods,
@@ -436,10 +450,12 @@ impl<'a> CodeGenerator for Vtable<'a> {
assert_eq!(item.id(), self.item_id);
// For now, generate an empty struct, later we should generate function
// pointers and whatnot.
- let vtable = aster::AstBuilder::new().item().pub_()
- .with_attr(attributes::repr("C"))
- .struct_(self.canonical_name(ctx))
- .build();
+ let vtable = aster::AstBuilder::new()
+ .item()
+ .pub_()
+ .with_attr(attributes::repr("C"))
+ .struct_(self.canonical_name(ctx))
+ .build();
result.push(vtable);
}
}
@@ -475,8 +491,9 @@ impl<'a> Bitfield<'a> {
methods: &mut Vec<ast::ImplItem>) {
use aster::struct_field::StructFieldBuilder;
use std::cmp;
- let mut total_width = self.fields.iter()
- .fold(0u32, |acc, f| acc + f.bitfield().unwrap());
+ let mut total_width = self.fields
+ .iter()
+ .fold(0u32, |acc, f| acc + f.bitfield().unwrap());
if !total_width.is_power_of_two() || total_width < 8 {
total_width = cmp::max(8, total_width.next_power_of_two());
@@ -485,11 +502,14 @@ impl<'a> Bitfield<'a> {
let total_width_in_bytes = total_width as usize / 8;
let bitfield_type =
- BlobTyBuilder::new(Layout::new(total_width_in_bytes, total_width_in_bytes)).build();
+ BlobTyBuilder::new(Layout::new(total_width_in_bytes,
+ total_width_in_bytes))
+ .build();
let field_name = format!("_bitfield_{}", self.index);
let field_ident = ctx.ext_cx().ident_of(&field_name);
- let field = StructFieldBuilder::named(&field_name).pub_()
- .build_ty(bitfield_type.clone());
+ let field = StructFieldBuilder::named(&field_name)
+ .pub_()
+ .build_ty(bitfield_type.clone());
fields.push(field);
@@ -497,19 +517,21 @@ impl<'a> Bitfield<'a> {
for field in self.fields {
let width = field.bitfield().unwrap();
let field_name = field.name()
- .map(ToOwned::to_owned)
- .unwrap_or_else(|| format!("at_offset_{}", offset));
+ .map(ToOwned::to_owned)
+ .unwrap_or_else(|| format!("at_offset_{}", offset));
let field_item = ctx.resolve_item(field.ty());
- let field_ty_layout = field_item.kind().expect_type()
- .layout(ctx)
- .expect("Bitfield without layout? Gah!");
+ let field_ty_layout = field_item.kind()
+ .expect_type()
+ .layout(ctx)
+ .expect("Bitfield without layout? Gah!");
let field_type = field_item.to_rust_ty(ctx);
let int_type = BlobTyBuilder::new(field_ty_layout).build();
let getter_name = ctx.ext_cx().ident_of(&field_name);
- let setter_name = ctx.ext_cx().ident_of(&format!("set_{}", &field_name));
+ let setter_name = ctx.ext_cx()
+ .ident_of(&format!("set_{}", &field_name));
let mask = ((1usize << width) - 1) << offset;
// The transmute is unfortunate, but it's needed for enums in
// bitfields.
@@ -555,7 +577,8 @@ impl CodeGenerator for CompInfo {
// also don't output template specializations, neither total or partial.
//
// TODO: Generate layout tests for template specializations, yay!
- if self.has_non_type_template_params() || self.is_template_specialization() {
+ if self.has_non_type_template_params() ||
+ self.is_template_specialization() {
return;
}
@@ -598,16 +621,21 @@ impl CodeGenerator for CompInfo {
attributes.push(attributes::derives(&derives))
}
- let mut template_args_used = vec![false; applicable_template_args.len()];
+ let mut template_args_used =
+ vec![false; applicable_template_args.len()];
let canonical_name = item.canonical_name(ctx);
let builder = if is_union && ctx.options().unstable_rust {
- aster::AstBuilder::new().item().pub_()
- .with_attrs(attributes)
- .union_(&canonical_name)
+ aster::AstBuilder::new()
+ .item()
+ .pub_()
+ .with_attrs(attributes)
+ .union_(&canonical_name)
} else {
- aster::AstBuilder::new().item().pub_()
- .with_attrs(attributes)
- .struct_(&canonical_name)
+ aster::AstBuilder::new()
+ .item()
+ .pub_()
+ .with_attrs(attributes)
+ .struct_(&canonical_name)
};
// Generate the vtable from the method list if appropriate.
@@ -623,15 +651,15 @@ impl CodeGenerator for CompInfo {
// the parent too.
let mut fields = vec![];
if self.needs_explicit_vtable(ctx) {
- let vtable = Vtable::new(item.id(),
- self.methods(),
- self.base_members());
+ let vtable =
+ Vtable::new(item.id(), self.methods(), self.base_members());
vtable.codegen(ctx, result, item);
let vtable_type = vtable.to_rust_ty(ctx).to_ptr(true, ctx.span());
- let vtable_field = StructFieldBuilder::named("vtable_").pub_()
- .build_ty(vtable_type);
+ let vtable_field = StructFieldBuilder::named("vtable_")
+ .pub_()
+ .build_ty(vtable_type);
fields.push(vtable_field);
}
@@ -663,7 +691,8 @@ impl CodeGenerator for CompInfo {
};
let field = StructFieldBuilder::named(field_name)
- .pub_().build_ty(inner);
+ .pub_()
+ .build_ty(inner);
fields.push(field);
}
if is_union {
@@ -678,11 +707,11 @@ impl CodeGenerator for CompInfo {
let mut bitfield_count = 0;
let struct_fields = self.fields();
let fields_should_be_private = item.annotations()
- .private_fields()
- .unwrap_or(false);
+ .private_fields()
+ .unwrap_or(false);
let struct_accessor_kind = item.annotations()
- .accessor_kind()
- .unwrap_or(FieldAccessorKind::None);
+ .accessor_kind()
+ .unwrap_or(FieldAccessorKind::None);
let mut methods = vec![];
let mut anonymous_field_count = 0;
@@ -695,15 +724,16 @@ impl CodeGenerator for CompInfo {
let field_ty = ctx.resolve_type(field.ty());
// Try to catch a bitfield contination early.
- if let (Some(ref mut bitfield_width), Some(width)) = (current_bitfield_width, field.bitfield()) {
+ if let (Some(ref mut bitfield_width), Some(width)) =
+ (current_bitfield_width, field.bitfield()) {
let layout = current_bitfield_layout.unwrap();
debug!("Testing bitfield continuation {} {} {:?}",
*bitfield_width, width, layout);
- if *bitfield_width + width <= (layout.size * 8) as u32 {
- *bitfield_width += width;
- current_bitfield_fields.push(field);
- continue;
- }
+ if *bitfield_width + width <= (layout.size * 8) as u32 {
+ *bitfield_width += width;
+ current_bitfield_fields.push(field);
+ continue;
+ }
}
// Flush the current bitfield.
@@ -721,7 +751,7 @@ impl CodeGenerator for CompInfo {
if let Some(width) = field.bitfield() {
let layout = field_ty.layout(ctx)
- .expect("Bitfield type without layout?");
+ .expect("Bitfield type without layout?");
current_bitfield_width = Some(width);
current_bitfield_layout = Some(layout);
current_bitfield_fields.push(field);
@@ -756,12 +786,12 @@ impl CodeGenerator for CompInfo {
};
let is_private = field.annotations()
- .private_fields()
- .unwrap_or(fields_should_be_private);
+ .private_fields()
+ .unwrap_or(fields_should_be_private);
let accessor_kind = field.annotations()
- .accessor_kind()
- .unwrap_or(struct_accessor_kind);
+ .accessor_kind()
+ .unwrap_or(struct_accessor_kind);
let mut field = StructFieldBuilder::named(&field_name);
@@ -770,7 +800,7 @@ impl CodeGenerator for CompInfo {
}
let field = field.with_attrs(attrs)
- .build_ty(ty.clone());
+ .build_ty(ty.clone());
fields.push(field);
@@ -830,9 +860,10 @@ impl CodeGenerator for CompInfo {
};
match accessor_methods_impl.unwrap().node {
- ast::ItemKind::Impl(_, _, _, _, _, ref items)
- => methods.extend(items.clone()),
- _ => unreachable!()
+ ast::ItemKind::Impl(_, _, _, _, _, ref items) => {
+ methods.extend(items.clone())
+ }
+ _ => unreachable!(),
}
}
@@ -842,7 +873,8 @@ impl CodeGenerator for CompInfo {
// FIXME: May need to pass current_bitfield_layout too.
if current_bitfield_width.is_some() {
debug_assert!(!current_bitfield_fields.is_empty());
- let bitfield_fields = mem::replace(&mut current_bitfield_fields, vec![]);
+ let bitfield_fields = mem::replace(&mut current_bitfield_fields,
+ vec![]);
bitfield_count += 1;
Bitfield::new(bitfield_count, bitfield_fields)
.codegen_fields(ctx, &mut fields, &mut methods);
@@ -852,8 +884,9 @@ impl CodeGenerator for CompInfo {
if is_union && !ctx.options().unstable_rust {
let layout = layout.expect("Unable to get layout information?");
let ty = BlobTyBuilder::new(layout).build();
- let field = StructFieldBuilder::named("bindgen_union_field").pub_()
- .build_ty(ty);
+ let field = StructFieldBuilder::named("bindgen_union_field")
+ .pub_()
+ .build_ty(ty);
fields.push(field);
}
@@ -868,8 +901,10 @@ impl CodeGenerator for CompInfo {
match layout {
Some(l) => {
let ty = BlobTyBuilder::new(l).build();
- let field = StructFieldBuilder::named("_bindgen_opaque_blob").pub_()
- .build_ty(ty);
+ let field =
+ StructFieldBuilder::named("_bindgen_opaque_blob")
+ .pub_()
+ .build_ty(ty);
fields.push(field);
}
None => {
@@ -885,8 +920,9 @@ impl CodeGenerator for CompInfo {
// may add for unused template parameters.
if self.is_unsized(ctx) {
let ty = BlobTyBuilder::new(Layout::new(1, 1)).build();
- let field = StructFieldBuilder::named("_address").pub_()
- .build_ty(ty);
+ let field = StructFieldBuilder::named("_address")
+ .pub_()
+ .build_ty(ty);
fields.push(field);
}
@@ -918,7 +954,8 @@ impl CodeGenerator for CompInfo {
let generics = generics.build();
let rust_struct = builder.with_generics(generics.clone())
- .with_fields(fields).build();
+ .with_fields(fields)
+ .build();
result.push(rust_struct);
// Generate the inner types and all that stuff.
@@ -957,19 +994,25 @@ impl CodeGenerator for CompInfo {
fn $fn_name() {
assert_eq!($size_of_expr, $size);
assert_eq!($align_of_expr, $align);
- }).unwrap();
+ })
+ .unwrap();
result.push(item);
}
let mut method_names = Default::default();
for method in self.methods() {
- method.codegen_method(ctx, &mut methods, &mut method_names, result, item);
+ method.codegen_method(ctx,
+ &mut methods,
+ &mut method_names,
+ result,
+ item);
}
}
// NB: We can't use to_rust_ty here since for opaque types this tries to
// use the specialization knowledge to generate a blob field.
- let ty_for_impl = aster::AstBuilder::new().ty().path().id(&canonical_name).build();
+ let ty_for_impl =
+ aster::AstBuilder::new().ty().path().id(&canonical_name).build();
if needs_clone_impl {
let impl_ = quote_item!(ctx.ext_cx(),
impl X {
@@ -982,22 +1025,26 @@ impl CodeGenerator for CompInfo {
_ => unreachable!(),
};
- let clone_impl =
- aster::AstBuilder::new().item().impl_()
- .trait_().id("Clone").build()
- .with_generics(generics.clone())
- .with_items(impl_)
- .build_ty(ty_for_impl.clone());
+ let clone_impl = aster::AstBuilder::new()
+ .item()
+ .impl_()
+ .trait_()
+ .id("Clone")
+ .build()
+ .with_generics(generics.clone())
+ .with_items(impl_)
+ .build_ty(ty_for_impl.clone());
result.push(clone_impl);
}
if !methods.is_empty() {
- let methods =
- aster::AstBuilder::new().item().impl_()
- .with_generics(generics)
- .with_items(methods)
- .build_ty(ty_for_impl);
+ let methods = aster::AstBuilder::new()
+ .item()
+ .impl_()
+ .with_generics(generics)
+ .with_items(methods)
+ .build_ty(ty_for_impl);
result.push(methods);
}
}
@@ -1040,7 +1087,7 @@ impl MethodCodegen for Method {
let count = {
let mut count = method_names.entry(name.clone())
- .or_insert(0);
+ .or_insert(0);
*count += 1;
*count - 1
};
@@ -1050,7 +1097,8 @@ impl MethodCodegen for Method {
}
let function_name = function_item.canonical_name(ctx);
- let mut fndecl = utils::rust_fndecl_from_signature(ctx, signature_item).unwrap();
+ let mut fndecl = utils::rust_fndecl_from_signature(ctx, signature_item)
+ .unwrap();
if !self.is_static() {
let mutability = if self.is_const() {
ast::Mutability::Immutable
@@ -1095,16 +1143,19 @@ impl MethodCodegen for Method {
// TODO: We need to keep in sync the argument names, so we should unify
// this with the other loop that decides them.
let mut unnamed_arguments = 0;
- let mut exprs = signature.argument_types().iter().map(|&(ref name, _ty)| {
- let arg_name = match *name {
- Some(ref name) => ctx.rust_mangle(name).into_owned(),
- None => {
- unnamed_arguments += 1;
- format!("arg{}", unnamed_arguments)
- }
- };
- aster::expr::ExprBuilder::new().id(arg_name)
- }).collect::<Vec<_>>();
+ let mut exprs = signature.argument_types()
+ .iter()
+ .map(|&(ref name, _ty)| {
+ let arg_name = match *name {
+ Some(ref name) => ctx.rust_mangle(name).into_owned(),
+ None => {
+ unnamed_arguments += 1;
+ format!("arg{}", unnamed_arguments)
+ }
+ };
+ aster::expr::ExprBuilder::new().id(arg_name)
+ })
+ .collect::<Vec<_>>();
if !self.is_static() {
assert!(!exprs.is_empty());
@@ -1115,10 +1166,11 @@ impl MethodCodegen for Method {
};
};
- let call = aster::expr::ExprBuilder::new().call()
- .id(function_name)
- .with_args(exprs)
- .build();
+ let call = aster::expr::ExprBuilder::new()
+ .call()
+ .id(function_name)
+ .with_args(exprs)
+ .build();
let block = ast::Block {
stmts: vec![
@@ -1164,10 +1216,12 @@ impl CodeGenerator for Enum {
let repr = self.repr().map(|repr| ctx.resolve_type(repr));
let repr = match repr {
- Some(repr) => match *repr.canonical_type(ctx).kind() {
- TypeKind::Int(int_kind) => int_kind,
- _ => panic!("Unexpected type as enum repr"),
- },
+ Some(repr) => {
+ match *repr.canonical_type(ctx).kind() {
+ TypeKind::Int(int_kind) => int_kind,
+ _ => panic!("Unexpected type as enum repr"),
+ }
+ }
None => {
warn!("Guessing type of enum! Forward declarations of enums shouldn't be legal!");
IntKind::Int
@@ -1203,8 +1257,12 @@ impl CodeGenerator for Enum {
builder = builder.with_attr(attributes::doc(comment));
}
- let derives =
- attributes::derives(&["Debug", "Copy", "Clone", "PartialEq", "Eq", "Hash"]);
+ let derives = attributes::derives(&["Debug",
+ "Copy",
+ "Clone",
+ "PartialEq",
+ "Eq",
+ "Hash"]);
builder = builder.with_attr(derives);
@@ -1213,7 +1271,8 @@ impl CodeGenerator for Enum {
fn add_constant(enum_: &Type,
// Only to avoid recomputing every time.
enum_canonical_name: &str,
- // May be the same as "variant" if it's because the enum
+ // May be the same as "variant" if it's because the
+ // enum
// is unnamed and we still haven't seen the value.
variant_name: &str,
referenced_name: &str,
@@ -1225,11 +1284,15 @@ impl CodeGenerator for Enum {
variant_name.into()
};
- let constant = aster::AstBuilder::new().item().pub_()
- .const_(constant_name)
- .expr().path()
- .ids(&[&*enum_canonical_name, referenced_name])
- .build().build(enum_rust_ty);
+ let constant = aster::AstBuilder::new()
+ .item()
+ .pub_()
+ .const_(constant_name)
+ .expr()
+ .path()
+ .ids(&[&*enum_canonical_name, referenced_name])
+ .build()
+ .build(enum_rust_ty);
result.push(constant);
}
@@ -1245,8 +1308,11 @@ impl CodeGenerator for Enum {
Entry::Occupied(ref entry) => {
let existing_variant_name = entry.get();
let variant_name = ctx.rust_mangle(variant.name());
- add_constant(enum_ty, &name, &*variant_name,
- existing_variant_name, enum_rust_ty.clone(),
+ add_constant(enum_ty,
+ &name,
+ &*variant_name,
+ existing_variant_name,
+ enum_rust_ty.clone(),
result);
}
Entry::Vacant(entry) => {
@@ -1272,7 +1338,8 @@ impl CodeGenerator for Enum {
variant_name.clone()
} else {
if parent_canonical_name.is_none() {
- parent_canonical_name = Some(item.parent_id().canonical_name(ctx));
+ parent_canonical_name = Some(item.parent_id()
+ .canonical_name(ctx));
}
Cow::Owned(
@@ -1280,8 +1347,11 @@ impl CodeGenerator for Enum {
variant_name))
};
- add_constant(enum_ty, &name, &mangled_name,
- &variant_name, enum_rust_ty.clone(),
+ add_constant(enum_ty,
+ &name,
+ &mangled_name,
+ &variant_name,
+ enum_rust_ty.clone(),
result);
}
@@ -1298,7 +1368,10 @@ impl CodeGenerator for Enum {
trait ToRustTy {
type Extra;
- fn to_rust_ty(&self, ctx: &BindgenContext, extra: &Self::Extra) -> P<ast::Ty>;
+ fn to_rust_ty(&self,
+ ctx: &BindgenContext,
+ extra: &Self::Extra)
+ -> P<ast::Ty>;
}
trait ItemToRustTy {
@@ -1336,7 +1409,9 @@ impl ToRustTy for Type {
TypeKind::Void => raw!(c_void),
// TODO: we should do something smart with nullptr, or maybe *const
// c_void is enough?
- TypeKind::NullPtr => quote_ty!(ctx.ext_cx(), *const ::std::os::raw::c_void),
+ TypeKind::NullPtr => {
+ quote_ty!(ctx.ext_cx(), *const ::std::os::raw::c_void)
+ }
TypeKind::Int(ik) => {
match ik {
IntKind::Bool => aster::ty::TyBuilder::new().bool(),
@@ -1355,8 +1430,9 @@ impl ToRustTy for Type {
// FIXME: This doesn't generate the proper alignment, but we
// can't do better right now. We should be able to use
// i128/u128 when they're available.
- IntKind::U128 |
- IntKind::I128 => aster::ty::TyBuilder::new().array(2).u64(),
+ IntKind::U128 | IntKind::I128 => {
+ aster::ty::TyBuilder::new().array(2).u64()
+ }
}
}
TypeKind::Float(fk) => {
@@ -1365,8 +1441,9 @@ impl ToRustTy for Type {
// account?
match fk {
FloatKind::Float => aster::ty::TyBuilder::new().f32(),
- FloatKind::Double |
- FloatKind::LongDouble => aster::ty::TyBuilder::new().f64(),
+ FloatKind::Double | FloatKind::LongDouble => {
+ aster::ty::TyBuilder::new().f64()
+ }
}
}
TypeKind::Function(ref fs) => {
@@ -1407,7 +1484,9 @@ impl ToRustTy for Type {
// Pray if there's no available layout.
let layout = self.layout(ctx).unwrap_or_else(Layout::zero);
BlobTyBuilder::new(layout).build()
- } else if let Some(ty) = utils::type_from_named(ctx, spelling, inner) {
+ } else if let Some(ty) = utils::type_from_named(ctx,
+ spelling,
+ inner) {
ty
} else {
utils::build_templated_path(item, ctx, true)
@@ -1416,22 +1495,22 @@ impl ToRustTy for Type {
TypeKind::Comp(ref info) => {
if item.is_opaque(ctx) || info.has_non_type_template_params() {
return match self.layout(ctx) {
- Some(layout) => {
- BlobTyBuilder::new(layout).build()
- }
+ Some(layout) => BlobTyBuilder::new(layout).build(),
None => {
warn!("Couldn't compute layout for a type with non \
type template params or opaque, expect dragons!");
aster::AstBuilder::new().ty().unit()
}
- }
+ };
}
utils::build_templated_path(item, ctx, false)
}
TypeKind::BlockPointer => {
let void = raw!(c_void);
- void.to_ptr(/* is_const = */ false, ctx.span())
+ void.to_ptr(/* is_const = */
+ false,
+ ctx.span())
}
TypeKind::Pointer(inner) |
TypeKind::Reference(inner) => {
@@ -1444,7 +1523,8 @@ impl ToRustTy for Type {
if inner_ty.canonical_type(ctx).is_function() {
ty
} else {
- let is_const = self.is_const() || inner.expect_type().is_const();
+ let is_const = self.is_const() ||
+ inner.expect_type().is_const();
ty.to_ptr(is_const, ctx.span())
}
}
@@ -1453,8 +1533,9 @@ impl ToRustTy for Type {
let ident = ctx.rust_ident(&name);
quote_ty!(ctx.ext_cx(), $ident)
}
- ref u @ TypeKind::UnresolvedTypeRef(..)
- => unreachable!("Should have been resolved after parsing {:?}!", u),
+ ref u @ TypeKind::UnresolvedTypeRef(..) => {
+ unreachable!("Should have been resolved after parsing {:?}!", u)
+ }
}
}
}
@@ -1465,11 +1546,12 @@ impl ToRustTy for FunctionSig {
fn to_rust_ty(&self, ctx: &BindgenContext, _item: &Item) -> P<ast::Ty> {
// TODO: we might want to consider ignoring the reference return value.
let return_item = ctx.resolve_item(self.return_type());
- let ret = if let TypeKind::Void = *return_item.kind().expect_type().kind() {
- ast::FunctionRetTy::Default(ctx.span())
- } else {
- ast::FunctionRetTy::Ty(return_item.to_rust_ty(ctx))
- };
+ let ret =
+ if let TypeKind::Void = *return_item.kind().expect_type().kind() {
+ ast::FunctionRetTy::Default(ctx.span())
+ } else {
+ ast::FunctionRetTy::Ty(return_item.to_rust_ty(ctx))
+ };
let mut unnamed_arguments = 0;
let arguments = self.argument_types().iter().map(|&(ref name, ty)| {
@@ -1566,15 +1648,14 @@ impl CodeGenerator for Function {
let foreign_item_kind =
ast::ForeignItemKind::Fn(fndecl, ast::Generics::default());
- let foreign_item =
- ast::ForeignItem {
- ident: ctx.rust_ident_raw(&canonical_name),
- attrs: attributes,
- node: foreign_item_kind,
- id: ast::DUMMY_NODE_ID,
- span: ctx.span(),
- vis: ast::Visibility::Public,
- };
+ let foreign_item = ast::ForeignItem {
+ ident: ctx.rust_ident_raw(&canonical_name),
+ attrs: attributes,
+ node: foreign_item_kind,
+ id: ast::DUMMY_NODE_ID,
+ span: ctx.span(),
+ vis: ast::Visibility::Public,
+ };
let item = ForeignModBuilder::new(signature.abi())
.with_foreign_item(foreign_item)
@@ -1596,7 +1677,8 @@ pub fn codegen(context: &mut BindgenContext) -> Vec<P<ast::Item>> {
context.options().whitelisted_functions.is_empty() &&
context.options().whitelisted_vars.is_empty() {
for (_item_id, item) in context.items() {
- // Non-toplevel item parents are the responsible one for generating
+ // Non-toplevel item parents are the responsible one for
+ // generating
// them.
if item.is_toplevel(context) {
item.codegen(context, &mut result, &());
@@ -1629,17 +1711,24 @@ pub fn codegen(context: &mut BindgenContext) -> Vec<P<ast::Item>> {
if let TypeKind::Enum(ref enum_) = *ty.kind() {
if ty.name().is_none() {
if enum_.variants().iter().any(|variant| {
- context.options().whitelisted_vars.matches(&variant.name())
+ context.options()
+ .whitelisted_vars
+ .matches(&variant.name())
}) {
- item.collect_types(context, &mut items, &());
+ item.collect_types(context,
+ &mut items,
+ &());
}
}
}
}
ItemKind::Function(ref fun) => {
- if context.options().whitelisted_functions.matches(&name) {
+ if context.options()
+ .whitelisted_functions
+ .matches(&name) {
items.insert(item.id());
- fun.signature().collect_types(context, &mut items, &());
+ fun.signature()
+ .collect_types(context, &mut items, &());
}
}
ItemKind::Var(ref var) => {
@@ -1652,7 +1741,10 @@ pub fn codegen(context: &mut BindgenContext) -> Vec<P<ast::Item>> {
}
}
- fn contains_parent(ctx: &BindgenContext, types: &ItemSet, id: ItemId) -> bool {
+ fn contains_parent(ctx: &BindgenContext,
+ types: &ItemSet,
+ id: ItemId)
+ -> bool {
let item = ctx.resolve_item(id);
let mut last = id;
let mut current = item.parent_id();
@@ -1670,7 +1762,8 @@ pub fn codegen(context: &mut BindgenContext) -> Vec<P<ast::Item>> {
for item_id in items.iter() {
let item = context.resolve_item(*item_id);
- if item.is_toplevel(context) || !contains_parent(context, &items, *item_id) {
+ if item.is_toplevel(context) ||
+ !contains_parent(context, &items, *item_id) {
item.codegen(context, &mut result, &());
}
}
@@ -1685,21 +1778,23 @@ pub fn codegen(context: &mut BindgenContext) -> Vec<P<ast::Item>> {
}
mod utils {
+ use aster;
use ir::context::BindgenContext;
use ir::item::{Item, ItemCanonicalPath, ItemId};
use ir::ty::TypeKind;
- use syntax::ast;
- use syntax::ptr::P;
use std::mem;
use super::ItemToRustTy;
- use aster;
+ use syntax::ast;
+ use syntax::ptr::P;
- pub fn prepend_union_types(ctx: &BindgenContext, result: &mut Vec<P<ast::Item>>) {
+ pub fn prepend_union_types(ctx: &BindgenContext,
+ result: &mut Vec<P<ast::Item>>) {
let union_field_decl = quote_item!(ctx.ext_cx(),
#[derive(Debug)]
#[repr(C)]
pub struct __BindgenUnionField<T>(::std::marker::PhantomData<T>);
- ).unwrap();
+ )
+ .unwrap();
let union_field_impl = quote_item!(&ctx.ext_cx(),
impl<T> __BindgenUnionField<T> {
@@ -1718,7 +1813,8 @@ mod utils {
::std::mem::transmute(self)
}
}
- ).unwrap();
+ )
+ .unwrap();
let union_field_default_impl = quote_item!(&ctx.ext_cx(),
impl<T> ::std::default::Default for __BindgenUnionField<T> {
@@ -1727,7 +1823,8 @@ mod utils {
Self::new()
}
}
- ).unwrap();
+ )
+ .unwrap();
let union_field_clone_impl = quote_item!(&ctx.ext_cx(),
impl<T> ::std::clone::Clone for __BindgenUnionField<T> {
@@ -1736,11 +1833,13 @@ mod utils {
Self::new()
}
}
- ).unwrap();
+ )
+ .unwrap();
let union_field_copy_impl = quote_item!(&ctx.ext_cx(),
impl<T> ::std::marker::Copy for __BindgenUnionField<T> {}
- ).unwrap();
+ )
+ .unwrap();
let items = vec![
union_field_decl, union_field_impl,
@@ -1754,26 +1853,32 @@ mod utils {
}
- pub fn build_templated_path(item: &Item, ctx: &BindgenContext, only_named: bool) -> P<ast::Ty> {
+ pub fn build_templated_path(item: &Item,
+ ctx: &BindgenContext,
+ only_named: bool)
+ -> P<ast::Ty> {
let path = item.canonical_path(ctx);
let builder = aster::AstBuilder::new().ty().path();
let template_args = if only_named {
- item.applicable_template_args(ctx).iter().filter(|arg| {
- ctx.resolve_type(**arg).is_named()
- }).map(|arg| {
- arg.to_rust_ty(ctx)
- }).collect::<Vec<_>>()
+ item.applicable_template_args(ctx)
+ .iter()
+ .filter(|arg| ctx.resolve_type(**arg).is_named())
+ .map(|arg| arg.to_rust_ty(ctx))
+ .collect::<Vec<_>>()
} else {
- item.applicable_template_args(ctx).iter().map(|arg| {
- arg.to_rust_ty(ctx)
- }).collect::<Vec<_>>()
+ item.applicable_template_args(ctx)
+ .iter()
+ .map(|arg| arg.to_rust_ty(ctx))
+ .collect::<Vec<_>>()
};
// XXX: I suck at aster.
if path.len() == 1 {
return builder.segment(&path[0])
- .with_tys(template_args).build().build();
+ .with_tys(template_args)
+ .build()
+ .build();
}
let mut builder = builder.id(&path[0]);
@@ -1782,7 +1887,8 @@ mod utils {
builder = if i == path.len() - 2 {
// XXX Extra clone courtesy of the borrow checker.
builder.segment(&segment)
- .with_tys(template_args.clone()).build()
+ .with_tys(template_args.clone())
+ .build()
} else {
builder.segment(&segment).build()
}
@@ -1798,7 +1904,8 @@ mod utils {
pub fn type_from_named(ctx: &BindgenContext,
name: &str,
- _inner: ItemId) -> Option<P<ast::Ty>> {
+ _inner: ItemId)
+ -> Option<P<ast::Ty>> {
// FIXME: We could use the inner item to check this is really a
// primitive type but, who the heck overrides these anyway?
macro_rules! ty {
@@ -1816,17 +1923,16 @@ mod utils {
"int64_t" => ty!(i64),
"uint64_t" => ty!(u64),
- "uintptr_t" |
- "size_t" => ty!(usize),
+ "uintptr_t" | "size_t" => ty!(usize),
- "intptr_t" |
- "ptrdiff_t" |
- "ssize_t" => ty!(isize),
+ "intptr_t" | "ptrdiff_t" | "ssize_t" => ty!(isize),
_ => return None,
})
}
- pub fn rust_fndecl_from_signature(ctx: &BindgenContext, sig: &Item) -> P<ast::FnDecl> {
+ pub fn rust_fndecl_from_signature(ctx: &BindgenContext,
+ sig: &Item)
+ -> P<ast::FnDecl> {
use codegen::ToRustTy;
let signature = sig.kind().expect_type();
diff --git a/src/ir/annotations.rs b/src/ir/annotations.rs
index 0ceb676d..58308d6d 100644
--- a/src/ir/annotations.rs
+++ b/src/ir/annotations.rs
@@ -58,7 +58,7 @@ impl Default for Annotations {
use_instead_of: None,
disallow_copy: false,
private_fields: None,
- accessor_kind: None
+ accessor_kind: None,
}
}
}
@@ -71,11 +71,7 @@ impl Annotations {
let mut matched_one = false;
anno.parse(&cursor.comment(), &mut matched_one);
- if matched_one {
- Some(anno)
- } else {
- None
- }
+ if matched_one { Some(anno) } else { None }
}
/// Should this type be hidden?
@@ -133,7 +129,9 @@ impl Annotations {
use clangll::CXComment_HTMLStartTag;
if comment.kind() == CXComment_HTMLStartTag &&
comment.get_tag_name() == "div" &&
- comment.get_tag_attrs().next().map_or(false, |attr| attr.name == "rustbindgen") {
+ comment.get_tag_attrs()
+ .next()
+ .map_or(false, |attr| attr.name == "rustbindgen") {
*matched = true;
for attr in comment.get_tag_attrs() {
match attr.name.as_str() {
@@ -141,10 +139,13 @@ impl Annotations {
"hide" => self.hide = true,
"nocopy" => self.disallow_copy = true,
"replaces" => self.use_instead_of = Some(attr.value),
- "private" => self.private_fields = Some(attr.value != "false"),
- "accessor"
- => self.accessor_kind = Some(parse_accessor(&attr.value)),
- _ => {},
+ "private" => {
+ self.private_fields = Some(attr.value != "false")
+ }
+ "accessor" => {
+ self.accessor_kind = Some(parse_accessor(&attr.value))
+ }
+ _ => {}
}
}
}
diff --git a/src/ir/comp.rs b/src/ir/comp.rs
index 98003936..27094003 100644
--- a/src/ir/comp.rs
+++ b/src/ir/comp.rs
@@ -1,15 +1,15 @@
//! Compound types (unions and structs) in our intermediate representation.
+use clang;
+use parse::{ClangItemParser, ParseError};
+use std::cell::Cell;
+use std::cmp;
use super::annotations::Annotations;
use super::context::BindgenContext;
-use super::layout::Layout;
use super::item::{Item, ItemId};
-use super::ty::{Type, RUST_DERIVE_IN_ARRAY_LIMIT};
+use super::layout::Layout;
+use super::ty::{RUST_DERIVE_IN_ARRAY_LIMIT, Type};
use super::type_collector::{ItemSet, TypeCollector};
-use std::cell::Cell;
-use std::cmp;
-use parse::{ClangItemParser, ParseError};
-use clang;
/// The kind of compound type.
#[derive(Debug, Copy, Clone, PartialEq)]
@@ -103,7 +103,8 @@ impl Field {
comment: Option<String>,
annotations: Option<Annotations>,
bitfield: Option<u32>,
- mutable: bool) -> Field {
+ mutable: bool)
+ -> Field {
Field {
name: name,
ty: ty,
@@ -199,7 +200,8 @@ pub struct CompInfo {
/// TODO: We should be able to compute this.
has_nonempty_base: bool,
- /// If this type has a template parameter which is not a type (e.g.: a size_t)
+ /// If this type has a template parameter which is not a type (e.g.: a
+ /// size_t)
has_non_type_template_params: bool,
/// Whether this struct layout is packed.
@@ -250,7 +252,10 @@ impl CompInfo {
}
/// Can we derive the `Debug` trait for this compound type?
- pub fn can_derive_debug(&self, ctx: &BindgenContext, layout: Option<Layout>) -> bool {
+ pub fn can_derive_debug(&self,
+ ctx: &BindgenContext,
+ layout: Option<Layout>)
+ -> bool {
// We can reach here recursively via template parameters of a member,
// for example.
if self.detect_derive_debug_cycle.get() {
@@ -258,7 +263,7 @@ impl CompInfo {
return true;
}
- if self.kind == CompKind::Union {
+ if self.kind == CompKind::Union {
if ctx.options().unstable_rust {
return false;
}
@@ -270,23 +275,22 @@ impl CompInfo {
self.detect_derive_debug_cycle.set(true);
- let can_derive_debug =
- self.base_members.iter().all(|ty| {
- ctx.resolve_type(*ty)
- .can_derive_debug(ctx)
- }) &&
- self.template_args.iter().all(|ty| {
- ctx.resolve_type(*ty)
- .can_derive_debug(ctx)
- }) &&
- self.fields.iter().all(|field| {
- ctx.resolve_type(field.ty)
- .can_derive_debug(ctx)
- }) &&
- self.ref_template.map_or(true, |template| {
- ctx.resolve_type(template)
- .can_derive_debug(ctx)
- });
+ let can_derive_debug = self.base_members.iter().all(|ty| {
+ ctx.resolve_type(*ty)
+ .can_derive_debug(ctx)
+ }) &&
+ self.template_args.iter().all(|ty| {
+ ctx.resolve_type(*ty)
+ .can_derive_debug(ctx)
+ }) &&
+ self.fields.iter().all(|field| {
+ ctx.resolve_type(field.ty)
+ .can_derive_debug(ctx)
+ }) &&
+ self.ref_template.map_or(true, |template| {
+ ctx.resolve_type(template)
+ .can_derive_debug(ctx)
+ });
self.detect_derive_debug_cycle.set(false);
@@ -296,15 +300,13 @@ impl CompInfo {
/// Is this compound type unsized?
pub fn is_unsized(&self, ctx: &BindgenContext) -> bool {
!self.has_vtable(ctx) && self.fields.is_empty() &&
- self.base_members.iter().all(|base| {
- ctx
- .resolve_type(*base)
- .canonical_type(ctx)
- .is_unsized(ctx)
- }) &&
- self.ref_template.map_or(true, |template| {
- ctx.resolve_type(template).is_unsized(ctx)
- })
+ self.base_members.iter().all(|base| {
+ ctx.resolve_type(*base)
+ .canonical_type(ctx)
+ .is_unsized(ctx)
+ }) &&
+ self.ref_template
+ .map_or(true, |template| ctx.resolve_type(template).is_unsized(ctx))
}
/// Does this compound type have a destructor?
@@ -317,7 +319,8 @@ impl CompInfo {
self.detect_has_destructor_cycle.set(true);
- let has_destructor = self.has_destructor || match self.kind {
+ let has_destructor = self.has_destructor ||
+ match self.kind {
CompKind::Union => false,
CompKind::Struct => {
// NB: We can't rely on a type with type parameters
@@ -327,15 +330,15 @@ impl CompInfo {
self.ref_template.as_ref().map_or(false, |t| {
ctx.resolve_type(*t).has_destructor(ctx)
}) ||
- self.template_args.iter().any(|t| {
- ctx.resolve_type(*t).has_destructor(ctx)
- }) ||
- self.base_members.iter().any(|t| {
- ctx.resolve_type(*t).has_destructor(ctx)
- }) ||
+ self.template_args
+ .iter()
+ .any(|t| ctx.resolve_type(*t).has_destructor(ctx)) ||
+ self.base_members
+ .iter()
+ .any(|t| ctx.resolve_type(*t).has_destructor(ctx)) ||
self.fields.iter().any(|field| {
ctx.resolve_type(field.ty)
- .has_destructor(ctx)
+ .has_destructor(ctx)
})
}
};
@@ -360,24 +363,23 @@ impl CompInfo {
}
// https://github.com/rust-lang/rust/issues/36640
- if !self.template_args.is_empty() ||
- self.ref_template.is_some() ||
- !item.applicable_template_args(ctx).is_empty() {
+ if !self.template_args.is_empty() || self.ref_template.is_some() ||
+ !item.applicable_template_args(ctx).is_empty() {
return false;
}
}
// With template args, use a safe subset of the types,
// since copyability depends on the types itself.
- self.ref_template.as_ref().map_or(true, |t| {
- ctx.resolve_item(*t).can_derive_copy(ctx)
- }) &&
- self.base_members.iter().all(|t| {
- ctx.resolve_item(*t).can_derive_copy(ctx)
- }) &&
+ self.ref_template
+ .as_ref()
+ .map_or(true, |t| ctx.resolve_item(*t).can_derive_copy(ctx)) &&
+ self.base_members
+ .iter()
+ .all(|t| ctx.resolve_item(*t).can_derive_copy(ctx)) &&
self.fields.iter().all(|field| {
ctx.resolve_item(field.ty)
- .can_derive_copy(ctx)
+ .can_derive_copy(ctx)
})
}
@@ -411,7 +413,7 @@ impl CompInfo {
let mut max_align = 0;
for field in &self.fields {
let field_layout = ctx.resolve_type(field.ty)
- .layout(ctx);
+ .layout(ctx);
if let Some(layout) = field_layout {
max_size = cmp::max(max_size, layout.size);
@@ -441,11 +443,12 @@ impl CompInfo {
/// Does this type have a virtual table?
pub fn has_vtable(&self, ctx: &BindgenContext) -> bool {
- self.has_vtable || self.base_members().iter().any(|base| {
- ctx
- .resolve_type(*base)
+ self.has_vtable ||
+ self.base_members().iter().any(|base| {
+ ctx.resolve_type(*base)
.has_vtable(ctx)
- }) || self.ref_template.map_or(false, |template| {
+ }) ||
+ self.ref_template.map_or(false, |template| {
ctx.resolve_type(template).has_vtable(ctx)
})
}
@@ -469,7 +472,8 @@ impl CompInfo {
pub fn from_ty(potential_id: ItemId,
ty: &clang::Type,
location: Option<clang::Cursor>,
- ctx: &mut BindgenContext) -> Result<Self, ParseError> {
+ ctx: &mut BindgenContext)
+ -> Result<Self, ParseError> {
use clangll::*;
// Sigh... For class templates we want the location, for
// specialisations, we want the declaration... So just try both.
@@ -491,14 +495,15 @@ impl CompInfo {
let mut ci = CompInfo::new(kind);
ci.is_anonymous = cursor.is_anonymous();
ci.template_args = match ty.template_args() {
- // In forward declarations and not specializations, etc, they are in
- // the ast, we'll meet them in CXCursor_TemplateTypeParameter
+ // In forward declarations and not specializations,
+ // etc, they are in
+ // the ast, we'll meet them in
+ // CXCursor_TemplateTypeParameter
None => vec![],
Some(arg_types) => {
let num_arg_types = arg_types.len();
- let args = arg_types
- .filter(|t| t.kind() != CXType_Invalid)
+ let args = arg_types.filter(|t| t.kind() != CXType_Invalid)
.map(|t| Item::from_ty_or_ref(t, None, None, ctx))
.collect::<Vec<_>>();
@@ -724,7 +729,8 @@ impl CompInfo {
Ok(ci)
}
- fn kind_from_cursor(cursor: &clang::Cursor) -> Result<CompKind, ParseError> {
+ fn kind_from_cursor(cursor: &clang::Cursor)
+ -> Result<CompKind, ParseError> {
use clangll::*;
Ok(match cursor.kind() {
CXCursor_UnionDecl => CompKind::Union,
@@ -750,7 +756,8 @@ impl CompInfo {
/// See also documentation for `ir::Item::signature_contains_named_type`.
pub fn signature_contains_named_type(&self,
ctx: &BindgenContext,
- ty: &Type) -> bool {
+ ty: &Type)
+ -> bool {
// We don't generate these, so rather don't make the codegen step to
// think we got it covered.
if self.has_non_type_template_params() {
@@ -758,7 +765,7 @@ impl CompInfo {
}
self.template_args.iter().any(|arg| {
ctx.resolve_type(*arg)
- .signature_contains_named_type(ctx, ty)
+ .signature_contains_named_type(ctx, ty)
})
}
@@ -787,19 +794,18 @@ impl CompInfo {
/// Returns whether this type needs an explicit vtable because it has
/// virtual methods and none of its base classes has already a vtable.
pub fn needs_explicit_vtable(&self, ctx: &BindgenContext) -> bool {
- self.has_vtable(ctx) && !self.base_members.iter().any(|base| {
+ self.has_vtable(ctx) &&
+ !self.base_members.iter().any(|base| {
// NB: Ideally, we could rely in all these types being `comp`, and
// life would be beautiful.
//
// Unfortunately, given the way we implement --match-pat, and also
// that you can inherit from templated types, we need to handle
// other cases here too.
- ctx
- .resolve_type(*base)
+ ctx.resolve_type(*base)
.canonical_type(ctx)
- .as_comp().map_or(false, |ci| {
- ci.has_vtable(ctx)
- })
+ .as_comp()
+ .map_or(false, |ci| ci.has_vtable(ctx))
})
}
}
diff --git a/src/ir/context.rs b/src/ir/context.rs
index 729a1c02..5e29e0c9 100644
--- a/src/ir/context.rs
+++ b/src/ir/context.rs
@@ -1,20 +1,20 @@
//! Common context that is passed around during parsing and codegen.
-use super::ty::{Type, TypeKind, FloatKind};
-use super::item::{Item, ItemCanonicalName, ItemId};
-use super::item_kind::ItemKind;
-use super::int::IntKind;
-use super::module::Module;
+use BindgenOptions;
use clang::{self, Cursor};
-use std::borrow::{Cow, Borrow};
+use parse::ClangItemParser;
+use std::borrow::{Borrow, Cow};
+use std::collections::{HashMap, HashSet};
use std::collections::btree_map::{self, BTreeMap};
-use std::collections::{HashSet, HashMap};
use std::fmt;
+use super::int::IntKind;
+use super::item::{Item, ItemCanonicalName, ItemId};
+use super::item_kind::ItemKind;
+use super::module::Module;
+use super::ty::{FloatKind, Type, TypeKind};
use syntax::ast::Ident;
use syntax::codemap::{DUMMY_SP, Span};
use syntax::ext::base::ExtCtxt;
-use parse::ClangItemParser;
-use BindgenOptions;
/// A key used to index a resolved type, so we only process it once.
///
@@ -141,8 +141,12 @@ impl<'ctx> BindgenContext<'ctx> {
item: Item,
declaration: Option<Cursor>,
location: Option<Cursor>) {
- use clangll::{CXCursor_ClassTemplate, CXCursor_ClassTemplatePartialSpecialization};
- debug!("BindgenContext::add_item({:?}, declaration: {:?}, loc: {:?}", item, declaration, location);
+ use clangll::{CXCursor_ClassTemplate,
+ CXCursor_ClassTemplatePartialSpecialization};
+ debug!("BindgenContext::add_item({:?}, declaration: {:?}, loc: {:?}",
+ item,
+ declaration,
+ location);
debug_assert!(declaration.is_some() || !item.kind().is_type() ||
item.kind().expect_type().is_builtin_or_named(),
"Adding a type without declaration?");
@@ -161,7 +165,8 @@ impl<'ctx> BindgenContext<'ctx> {
if !declaration.is_valid() {
if let Some(location) = location {
if location.kind() == CXCursor_ClassTemplate ||
- location.kind() == CXCursor_ClassTemplatePartialSpecialization {
+ location.kind() ==
+ CXCursor_ClassTemplatePartialSpecialization {
declaration = location;
}
}
@@ -174,7 +179,8 @@ impl<'ctx> BindgenContext<'ctx> {
// Fortunately, we don't care about those types being
// duplicated, so we can just ignore them.
debug!("Invalid declaration {:?} found for type {:?}",
- declaration, self.items.get(&id).unwrap().kind().expect_type());
+ declaration,
+ self.items.get(&id).unwrap().kind().expect_type());
return;
}
@@ -183,7 +189,9 @@ impl<'ctx> BindgenContext<'ctx> {
} else if let Some(usr) = declaration.usr() {
TypeKey::USR(usr)
} else {
- error!("Valid declaration with no USR: {:?}, {:?}", declaration, location);
+ error!("Valid declaration with no USR: {:?}, {:?}",
+ declaration,
+ location);
return;
};
@@ -209,18 +217,15 @@ impl<'ctx> BindgenContext<'ctx> {
use syntax::parse::token;
let ident = self.rust_ident_raw(&name);
let token = token::Ident(ident);
- if token.is_any_keyword() ||
- name.contains("@") ||
- name.contains("?") ||
- name.contains("$") ||
- "bool" == name
- {
+ if token.is_any_keyword() || name.contains("@") ||
+ name.contains("?") || name.contains("$") ||
+ "bool" == name {
let mut s = name.to_owned();
s = s.replace("@", "_");
s = s.replace("?", "_");
s = s.replace("$", "_");
s.push_str("_");
- return Cow::Owned(s)
+ return Cow::Owned(s);
}
Cow::Borrowed(name)
}
@@ -248,7 +253,9 @@ impl<'ctx> BindgenContext<'ctx> {
}
/// Gather all the unresolved type references.
- fn collect_typerefs(&mut self) -> Vec<(ItemId, clang::Type, Option<clang::Cursor>, Option<ItemId>)> {
+ fn collect_typerefs
+ (&mut self)
+ -> Vec<(ItemId, clang::Type, Option<clang::Cursor>, Option<ItemId>)> {
debug_assert!(!self.collected_typerefs);
self.collected_typerefs = true;
let mut typerefs = vec![];
@@ -263,7 +270,7 @@ impl<'ctx> BindgenContext<'ctx> {
TypeKind::UnresolvedTypeRef(ref ty, loc, parent_id) => {
typerefs.push((*id, ty.clone(), loc, parent_id));
}
- _ => {},
+ _ => {}
};
}
typerefs
@@ -276,7 +283,7 @@ impl<'ctx> BindgenContext<'ctx> {
for (id, ty, loc, parent_id) in typerefs {
let _resolved = {
let resolved = Item::from_ty(&ty, loc, parent_id, self)
- .expect("What happened?");
+ .expect("What happened?");
let mut item = self.items.get_mut(&id).unwrap();
*item.kind_mut().as_type_mut().unwrap().kind_mut() =
@@ -321,7 +328,8 @@ impl<'ctx> BindgenContext<'ctx> {
continue;
}
- if let Some(replacement) = self.replacements.get(&item.canonical_name(self)) {
+ if let Some(replacement) = self.replacements
+ .get(&item.canonical_name(self)) {
if replacement != id {
// We set this just after parsing the annotation. It's
// very unlikely, but this can happen.
@@ -342,7 +350,7 @@ impl<'ctx> BindgenContext<'ctx> {
/// Enter the code generation phase, invoke the given callback `cb`, and
/// leave the code generation phase.
pub fn gen<F, Out>(&mut self, cb: F) -> Out
- where F: FnOnce(&Self) -> Out
+ where F: FnOnce(&Self) -> Out,
{
use syntax::ext::expand::ExpansionConfig;
use syntax::codemap::{ExpnInfo, MacroBang, NameAndSpan};
@@ -361,8 +369,8 @@ impl<'ctx> BindgenContext<'ctx> {
callee: NameAndSpan {
format: MacroBang(parse::token::intern("")),
allow_internal_unstable: false,
- span: None
- }
+ span: None,
+ },
});
// FIXME: This is evil, we should move code generation to use a wrapper
@@ -471,7 +479,8 @@ impl<'ctx> BindgenContext<'ctx> {
wrapping: ItemId,
parent_id: ItemId,
ty: &clang::Type,
- location: clang::Cursor) -> ItemId {
+ location: clang::Cursor)
+ -> ItemId {
use clangll::*;
let mut args = vec![];
let mut found_invalid_template_ref = false;
@@ -481,8 +490,10 @@ impl<'ctx> BindgenContext<'ctx> {
found_invalid_template_ref = true;
}
if c.kind() == CXCursor_TypeRef {
- let new_ty =
- Item::from_ty_or_ref(c.cur_type(), Some(*c), Some(with_id), self);
+ let new_ty = Item::from_ty_or_ref(c.cur_type(),
+ Some(*c),
+ Some(with_id),
+ self);
args.push(new_ty);
}
CXChildVisit_Continue
@@ -527,7 +538,10 @@ impl<'ctx> BindgenContext<'ctx> {
let type_kind = TypeKind::TemplateRef(wrapping, args);
let name = ty.spelling();
let name = if name.is_empty() { None } else { Some(name) };
- let ty = Type::new(name, ty.fallible_layout().ok(), type_kind, ty.is_const());
+ let ty = Type::new(name,
+ ty.fallible_layout().ok(),
+ type_kind,
+ ty.is_const());
Item::new(with_id, None, None, parent_id, ItemKind::Type(ty))
};
@@ -542,32 +556,40 @@ impl<'ctx> BindgenContext<'ctx> {
with_id: ItemId,
parent_id: Option<ItemId>,
ty: &clang::Type,
- location: Option<clang::Cursor>) -> Option<ItemId> {
- use clangll::{CXCursor_ClassTemplate, CXCursor_ClassTemplatePartialSpecialization};
- debug!("builtin_or_resolved_ty: {:?}, {:?}, {:?}", ty, location, parent_id);
+ location: Option<clang::Cursor>)
+ -> Option<ItemId> {
+ use clangll::{CXCursor_ClassTemplate,
+ CXCursor_ClassTemplatePartialSpecialization};
+ debug!("builtin_or_resolved_ty: {:?}, {:?}, {:?}",
+ ty,
+ location,
+ parent_id);
let mut declaration = ty.declaration();
if !declaration.is_valid() {
if let Some(location) = location {
if location.kind() == CXCursor_ClassTemplate ||
- location.kind() == CXCursor_ClassTemplatePartialSpecialization {
+ location.kind() ==
+ CXCursor_ClassTemplatePartialSpecialization {
declaration = location;
}
}
}
let canonical_declaration = declaration.canonical();
if canonical_declaration.is_valid() {
- let id =
- self.types.get(&TypeKey::Declaration(canonical_declaration))
- .map(|id| *id)
- .or_else(|| {
- canonical_declaration.usr().and_then(|usr| {
- self.types.get(&TypeKey::USR(usr))
- })
+ let id = self.types
+ .get(&TypeKey::Declaration(canonical_declaration))
+ .map(|id| *id)
+ .or_else(|| {
+ canonical_declaration.usr()
+ .and_then(|usr| self.types.get(&TypeKey::USR(usr)))
.map(|id| *id)
- });
+ });
if let Some(id) = id {
debug!("Already resolved ty {:?}, {:?}, {:?} {:?}",
- id, declaration, ty, location);
+ id,
+ declaration,
+ ty,
+ location);
// If the declaration existed, we *might* be done, but it's not
// the case for class templates, where the template arguments
@@ -580,13 +602,16 @@ impl<'ctx> BindgenContext<'ctx> {
// location for building the new arguments, the template
// argument names don't matter in the global context.
if (declaration.kind() == CXCursor_ClassTemplate ||
- declaration.kind() == CXCursor_ClassTemplatePartialSpecialization) &&
+ declaration.kind() ==
+ CXCursor_ClassTemplatePartialSpecialization) &&
*ty != canonical_declaration.cur_type() &&
- location.is_some() && parent_id.is_some() {
- return Some(
- self.build_template_wrapper(with_id, id,
- parent_id.unwrap(), ty,
- location.unwrap()));
+ location.is_some() &&
+ parent_id.is_some() {
+ return Some(self.build_template_wrapper(with_id,
+ id,
+ parent_id.unwrap(),
+ ty,
+ location.unwrap()));
}
return Some(self.build_ty_wrapper(with_id, id, parent_id, ty));
@@ -608,21 +633,26 @@ impl<'ctx> BindgenContext<'ctx> {
with_id: ItemId,
wrapped_id: ItemId,
parent_id: Option<ItemId>,
- ty: &clang::Type) -> ItemId {
+ ty: &clang::Type)
+ -> ItemId {
let spelling = ty.spelling();
let is_const = ty.is_const();
let layout = ty.fallible_layout().ok();
let type_kind = TypeKind::ResolvedTypeRef(wrapped_id);
let ty = Type::new(Some(spelling), layout, type_kind, is_const);
- let item = Item::new(with_id, None, None,
- parent_id.unwrap_or(self.current_module), ItemKind::Type(ty));
+ let item = Item::new(with_id,
+ None,
+ None,
+ parent_id.unwrap_or(self.current_module),
+ ItemKind::Type(ty));
self.add_builtin_item(item);
with_id
}
fn build_builtin_ty(&mut self,
ty: &clang::Type,
- _declaration: Cursor) -> Option<ItemId> {
+ _declaration: Cursor)
+ -> Option<ItemId> {
use clangll::*;
let type_kind = match ty.kind() {
CXType_NullPtr => TypeKind::NullPtr,
@@ -630,14 +660,11 @@ impl<'ctx> BindgenContext<'ctx> {
CXType_Bool => TypeKind::Int(IntKind::Bool),
CXType_Int => TypeKind::Int(IntKind::Int),
CXType_UInt => TypeKind::Int(IntKind::UInt),
- CXType_SChar |
- CXType_Char_S => TypeKind::Int(IntKind::Char),
- CXType_UChar |
- CXType_Char_U => TypeKind::Int(IntKind::UChar),
+ CXType_SChar | CXType_Char_S => TypeKind::Int(IntKind::Char),
+ CXType_UChar | CXType_Char_U => TypeKind::Int(IntKind::UChar),
CXType_Short => TypeKind::Int(IntKind::Short),
CXType_UShort => TypeKind::Int(IntKind::UShort),
- CXType_WChar |
- CXType_Char16 => TypeKind::Int(IntKind::U16),
+ CXType_WChar | CXType_Char16 => TypeKind::Int(IntKind::U16),
CXType_Char32 => TypeKind::Int(IntKind::U32),
CXType_Long => TypeKind::Int(IntKind::Long),
CXType_ULong => TypeKind::Int(IntKind::ULong),
@@ -656,7 +683,8 @@ impl<'ctx> BindgenContext<'ctx> {
let layout = ty.fallible_layout().ok();
let ty = Type::new(Some(spelling), layout, type_kind, is_const);
let id = ItemId::next();
- let item = Item::new(id, None, None, self.root_module, ItemKind::Type(ty));
+ let item =
+ Item::new(id, None, None, self.root_module, ItemKind::Type(ty));
self.add_builtin_item(item);
Some(id)
}
@@ -697,7 +725,7 @@ impl<'ctx> BindgenContext<'ctx> {
debug_assert!(self.in_codegen_phase(),
"You're not supposed to call this yet");
self.options.hidden_types.contains(name) ||
- self.is_replaced_type(name, id)
+ self.is_replaced_type(name, id)
}
/// Has the item with the given `name` and `id` been replaced by another
@@ -733,19 +761,23 @@ impl<'ctx> BindgenContext<'ctx> {
};
let module_name = self.translation_unit
- .tokens(&cursor).and_then(|tokens| {
- if tokens.len() <= 1 {
- None
- } else {
- match &*tokens[1].spelling {
- "{" => None,
- s => Some(s.to_owned()),
+ .tokens(&cursor)
+ .and_then(|tokens| {
+ if tokens.len() <= 1 {
+ None
+ } else {
+ match &*tokens[1].spelling {
+ "{" => None,
+ s => Some(s.to_owned()),
+ }
}
- }
- });
+ });
let module = Module::new(module_name);
- let module = Item::new(module_id, None, None, self.current_module,
+ let module = Item::new(module_id,
+ None,
+ None,
+ self.current_module,
ItemKind::Module(module));
self.add_item(module, None, None);
@@ -756,7 +788,7 @@ impl<'ctx> BindgenContext<'ctx> {
/// Start traversing the module with the given `module_id`, invoke the
/// callback `cb`, and then return to traversing the original module.
pub fn with_module<F>(&mut self, module_id: ItemId, cb: F)
- where F: FnOnce(&mut Self, &mut Vec<ItemId>)
+ where F: FnOnce(&mut Self, &mut Vec<ItemId>),
{
debug_assert!(self.resolve_item(module_id).kind().is_module(), "Wat");
@@ -766,9 +798,13 @@ impl<'ctx> BindgenContext<'ctx> {
let mut children = vec![];
cb(self, &mut children);
- self.items.get_mut(&module_id).unwrap()
- .as_module_mut().expect("Not a module?")
- .children_mut().extend(children.into_iter());
+ self.items
+ .get_mut(&module_id)
+ .unwrap()
+ .as_module_mut()
+ .expect("Not a module?")
+ .children_mut()
+ .extend(children.into_iter());
self.current_module = previous_id;
}
diff --git a/src/ir/enum_ty.rs b/src/ir/enum_ty.rs
index aff5130b..fd7dbb45 100644
--- a/src/ir/enum_ty.rs
+++ b/src/ir/enum_ty.rs
@@ -1,10 +1,10 @@
//! Intermediate representation for C/C++ enumerations.
+use clang;
+use parse::{ClangItemParser, ParseError};
+use super::context::BindgenContext;
use super::item::{Item, ItemId};
use super::ty::TypeKind;
-use super::context::BindgenContext;
-use parse::{ClangItemParser, ParseError};
-use clang;
/// A C/C++ enumeration.
#[derive(Debug)]
@@ -41,14 +41,16 @@ impl Enum {
/// Construct an enumeration from the given Clang type.
pub fn from_ty(ty: &clang::Type,
- ctx: &mut BindgenContext) -> Result<Self, ParseError> {
+ ctx: &mut BindgenContext)
+ -> Result<Self, ParseError> {
use clangll::*;
if ty.kind() != CXType_Enum {
return Err(ParseError::Continue);
}
let declaration = ty.declaration().canonical();
- let repr = Item::from_ty(&declaration.enum_type(), None, None, ctx).ok();
+ let repr = Item::from_ty(&declaration.enum_type(), None, None, ctx)
+ .ok();
let mut variants = vec![];
let is_signed = match repr {
@@ -56,10 +58,14 @@ impl Enum {
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? {:?}", other),
+ ref other => {
+ panic!("Since when enums can be non-integers? {:?}",
+ other)
+ }
}
}
- // Assume signedness since the default type by the C standard is an
+ // Assume signedness since the default type by the C
+ // standard is an
// int.
None => true,
};
@@ -107,7 +113,10 @@ pub enum EnumVariantValue {
impl EnumVariant {
/// Construct a new enumeration variant from the given parts.
- pub fn new(name: String, comment: Option<String>, val: EnumVariantValue) -> Self {
+ pub fn new(name: String,
+ comment: Option<String>,
+ val: EnumVariantValue)
+ -> Self {
EnumVariant {
name: name,
comment: comment,
diff --git a/src/ir/function.rs b/src/ir/function.rs
index e9fd4a25..c2e6ffd0 100644
--- a/src/ir/function.rs
+++ b/src/ir/function.rs
@@ -1,13 +1,13 @@
//! Intermediate representation for C/C++ functions and methods.
+use clang;
+use clangll::Enum_CXCallingConv;
+use parse::{ClangItemParser, ClangSubItemParser, ParseError, ParseResult};
use super::context::BindgenContext;
use super::item::{Item, ItemId};
use super::ty::TypeKind;
use super::type_collector::{ItemSet, TypeCollector};
use syntax::abi;
-use clang;
-use clangll::Enum_CXCallingConv;
-use parse::{ClangItemParser, ClangSubItemParser, ParseError, ParseResult};
/// A function declaration, with a signature, arguments, and argument names.
///
@@ -33,7 +33,8 @@ impl Function {
pub fn new(name: String,
mangled_name: Option<String>,
sig: ItemId,
- comment: Option<String>) -> Self {
+ comment: Option<String>)
+ -> Self {
Function {
name: name,
mangled_name: mangled_name,
@@ -115,7 +116,8 @@ impl FunctionSig {
pub fn new(return_type: ItemId,
arguments: Vec<(Option<String>, ItemId)>,
is_variadic: bool,
- abi: abi::Abi) -> Self {
+ abi: abi::Abi)
+ -> Self {
FunctionSig {
return_type: return_type,
argument_types: arguments,
@@ -127,7 +129,8 @@ impl FunctionSig {
/// Construct a new function signature from the given Clang type.
pub fn from_ty(ty: &clang::Type,
cursor: &clang::Cursor,
- ctx: &mut BindgenContext) -> Result<Self, ParseError> {
+ ctx: &mut BindgenContext)
+ -> Result<Self, ParseError> {
use clangll::*;
debug!("FunctionSig::from_ty {:?} {:?}", ty, cursor);
@@ -147,14 +150,18 @@ impl FunctionSig {
CXCursor_CXXMethod => {
// For CXCursor_FunctionDecl, cursor.args() is the reliable way
// to get parameter names and types.
- cursor.args().iter().map(|arg| {
- let arg_ty = arg.cur_type();
- let name = arg.spelling();
- let name = if name.is_empty() { None } else { Some(name) };
- let ty = Item::from_ty(&arg_ty, Some(*arg), None, ctx)
- .expect("Argument?");
- (name, ty)
- }).collect()
+ cursor.args()
+ .iter()
+ .map(|arg| {
+ let arg_ty = arg.cur_type();
+ let name = arg.spelling();
+ let name =
+ if name.is_empty() { None } else { Some(name) };
+ let ty = Item::from_ty(&arg_ty, Some(*arg), None, ctx)
+ .expect("Argument?");
+ (name, ty)
+ })
+ .collect()
}
_ => {
// For non-CXCursor_FunctionDecl, visiting the cursor's children
@@ -162,10 +169,12 @@ impl FunctionSig {
let mut args = vec![];
cursor.visit(|c, _| {
if c.kind() == CXCursor_ParmDecl {
- let ty = Item::from_ty(&c.cur_type(), Some(*c), None, ctx)
- .expect("ParmDecl?");
+ let ty =
+ Item::from_ty(&c.cur_type(), Some(*c), None, ctx)
+ .expect("ParmDecl?");
let name = c.spelling();
- let name = if name.is_empty() { None } else { Some(name) };
+ let name =
+ if name.is_empty() { None } else { Some(name) };
args.push((name, ty));
}
CXChildVisit_Continue
@@ -180,12 +189,14 @@ impl FunctionSig {
let is_static = cursor.method_is_static();
if !is_static && !is_virtual {
let class = Item::parse(cursor.semantic_parent(), None, ctx)
- .expect("Expected to parse the class");
- let ptr = Item::builtin_type(TypeKind::Pointer(class), is_const, ctx);
+ .expect("Expected to parse the class");
+ let ptr =
+ Item::builtin_type(TypeKind::Pointer(class), is_const, ctx);
args.insert(0, (Some("this".into()), ptr));
} else if is_virtual {
let void = Item::builtin_type(TypeKind::Void, false, ctx);
- let ptr = Item::builtin_type(TypeKind::Pointer(void), false, ctx);
+ let ptr =
+ Item::builtin_type(TypeKind::Pointer(void), false, ctx);
args.insert(0, (Some("this".into()), ptr));
}
}
@@ -223,18 +234,22 @@ impl FunctionSig {
impl ClangSubItemParser for Function {
fn parse(cursor: clang::Cursor,
- context: &mut BindgenContext) -> Result<ParseResult<Self>, ParseError> {
+ context: &mut BindgenContext)
+ -> Result<ParseResult<Self>, ParseError> {
use clangll::*;
match cursor.kind() {
CXCursor_FunctionDecl |
- CXCursor_CXXMethod => {},
+ CXCursor_CXXMethod => {}
_ => return Err(ParseError::Continue),
};
debug!("Function::parse({:?}, {:?})", cursor, cursor.cur_type());
// Grab the signature using Item::from_ty.
- let sig = try!(Item::from_ty(&cursor.cur_type(), Some(cursor), None, context));
+ let sig = try!(Item::from_ty(&cursor.cur_type(),
+ Some(cursor),
+ None,
+ context));
let name = cursor.spelling();
assert!(!name.is_empty(), "Empty function name?");
diff --git a/src/ir/int.rs b/src/ir/int.rs
index ed26acc4..a18e4c58 100644
--- a/src/ir/int.rs
+++ b/src/ir/int.rs
@@ -46,9 +46,8 @@ pub enum IntKind {
I128,
/// A `uint128_t`.
- U128,
-
- // Though now we're at it we could add equivalents for the rust types...
+ U128, /* Though now we're at it we could add equivalents for the rust
+ * types... */
}
impl IntKind {
@@ -56,11 +55,10 @@ impl IntKind {
pub fn is_signed(&self) -> bool {
use self::IntKind::*;
match *self {
- Bool | UChar | UShort |
- UInt | ULong | ULongLong | U16 | U32 | U128 => false,
+ Bool | UChar | UShort | UInt | ULong | ULongLong | U16 | U32 |
+ U128 => false,
- Char | Short | Int |
- Long | LongLong | I128 => true,
+ Char | Short | Int | Long | LongLong | I128 => true,
}
}
}
diff --git a/src/ir/item.rs b/src/ir/item.rs
index a6d15cd7..6857bc70 100644
--- a/src/ir/item.rs
+++ b/src/ir/item.rs
@@ -1,17 +1,17 @@
//! Bindgen's core intermediate representation type.
+use clang;
+use parse::{ClangItemParser, ClangSubItemParser, ParseError, ParseResult};
use regex::Regex;
+use std::cell::{Cell, RefCell};
+use std::sync::atomic::{ATOMIC_USIZE_INIT, AtomicUsize, Ordering};
+use super::annotations::Annotations;
use super::context::BindgenContext;
+use super::function::Function;
use super::item_kind::ItemKind;
+use super::module::Module;
use super::ty::{Type, TypeKind};
use super::type_collector::{ItemSet, TypeCollector};
-use super::function::Function;
-use super::module::Module;
-use super::annotations::Annotations;
-use std::cell::{Cell, RefCell};
-use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
-use parse::{ClangItemParser, ClangSubItemParser, ParseError, ParseResult};
-use clang;
/// A trait to get the canonical name from an item.
///
@@ -105,7 +105,7 @@ impl TypeCollector for Item {
ty.collect_types(context, types, self);
}
}
- _ => {}, // FIXME.
+ _ => {} // FIXME.
}
}
}
@@ -171,7 +171,8 @@ impl Item {
comment: Option<String>,
annotations: Option<Annotations>,
parent_id: ItemId,
- kind: ItemKind) -> Self {
+ kind: ItemKind)
+ -> Self {
debug_assert!(id != parent_id || kind.is_module());
Item {
id: id,
@@ -248,8 +249,7 @@ impl Item {
pub fn is_toplevel(&self, ctx: &BindgenContext) -> bool {
// FIXME: Workaround for some types falling behind when parsing weird
// stl classes, for example.
- if ctx.options().enable_cxx_namespaces &&
- self.kind().is_module() &&
+ if ctx.options().enable_cxx_namespaces && self.kind().is_module() &&
self.id() != ctx.root_module() {
return false;
}
@@ -263,7 +263,8 @@ impl Item {
if parent_item.id() == ctx.root_module() {
return true;
- } else if ctx.options().enable_cxx_namespaces || !parent_item.kind().is_module() {
+ } else if ctx.options().enable_cxx_namespaces ||
+ !parent_item.kind().is_module() {
return false;
}
@@ -328,16 +329,20 @@ impl Item {
/// Normally we could do this check just in the `Type` kind, but we also
/// need to check the `applicable_template_args` more generally, since we
/// could need a type transitively from our parent, see the test added in
- /// <https://github.com/servo/rust-bindgen/pull/85/commits/2a3f93074dd2898669dbbce6e97e5cc4405d7cb1>
+ /// <https://github.
+ /// com/servo/rust-bindgen/pull/85/commits/2a3f93074dd2898669dbbce6e97e5cc4405d7cb1>
///
/// It's kind of unfortunate (in the sense that it's a sort of complex
/// process), but I think it should get all the cases.
- fn signature_contains_named_type(&self, ctx: &BindgenContext, ty: &Type) -> bool {
+ fn signature_contains_named_type(&self,
+ ctx: &BindgenContext,
+ ty: &Type)
+ -> bool {
debug_assert!(ty.is_named());
self.expect_type().signature_contains_named_type(ctx, ty) ||
- self.applicable_template_args(ctx).iter().any(|template| {
- ctx.resolve_type(*template).signature_contains_named_type(ctx, ty)
- })
+ self.applicable_template_args(ctx).iter().any(|template| {
+ ctx.resolve_type(*template).signature_contains_named_type(ctx, ty)
+ })
}
/// Returns the template arguments that apply to a struct. This is a concept
@@ -373,7 +378,9 @@ impl Item {
/// the template parameter type `T`, and that's exactly what this method
/// represents. The unused template parameters get stripped in the
/// `signature_contains_named_type` check.
- pub fn applicable_template_args(&self, ctx: &BindgenContext) -> Vec<ItemId> {
+ pub fn applicable_template_args(&self,
+ ctx: &BindgenContext)
+ -> Vec<ItemId> {
let ty = match *self.kind() {
ItemKind::Type(ref ty) => ty,
_ => return vec![],
@@ -381,12 +388,14 @@ impl Item {
fn parent_contains(ctx: &BindgenContext,
parent_template_args: &[ItemId],
- item: ItemId) -> bool {
+ item: ItemId)
+ -> bool {
let item_ty = ctx.resolve_type(item);
parent_template_args.iter().any(|parent_item| {
let parent_ty = ctx.resolve_type(*parent_item);
match (parent_ty.kind(), item_ty.kind()) {
- (&TypeKind::Named(ref n, _), &TypeKind::Named(ref i, _)) => n == i,
+ (&TypeKind::Named(ref n, _),
+ &TypeKind::Named(ref i, _)) => n == i,
_ => false,
}
})
@@ -402,21 +411,23 @@ impl Item {
}
TypeKind::Alias(_, inner) => {
let parent_args = ctx.resolve_item(self.parent_id())
- .applicable_template_args(ctx);
+ .applicable_template_args(ctx);
let inner = ctx.resolve_item(inner);
// Avoid unused type parameters, sigh.
- parent_args.iter().cloned().filter(|arg| {
- let arg = ctx.resolve_type(*arg);
- arg.is_named() && inner.signature_contains_named_type(ctx, arg)
- }).collect()
+ parent_args.iter()
+ .cloned()
+ .filter(|arg| {
+ let arg = ctx.resolve_type(*arg);
+ arg.is_named() &&
+ inner.signature_contains_named_type(ctx, arg)
+ })
+ .collect()
}
// XXX Is this completely correct? Partial template specialization
// is hard anyways, sigh...
TypeKind::TemplateAlias(_, ref args) |
- TypeKind::TemplateRef(_, ref args) => {
- args.clone()
- }
+ TypeKind::TemplateRef(_, ref args) => args.clone(),
// In a template specialization we've got all we want.
TypeKind::Comp(ref ci) if ci.is_template_specialization() => {
ci.template_args().iter().cloned().collect()
@@ -424,7 +435,7 @@ impl Item {
TypeKind::Comp(ref ci) => {
let mut parent_template_args =
ctx.resolve_item(self.parent_id())
- .applicable_template_args(ctx);
+ .applicable_template_args(ctx);
for ty in ci.template_args() {
if !parent_contains(ctx, &parent_template_args, *ty) {
@@ -457,7 +468,7 @@ impl Item {
debug_assert!(ctx.in_codegen_phase(),
"You're not supposed to call this yet");
self.annotations.hide() ||
- ctx.hidden_by_name(&self.real_canonical_name(ctx, false, true), self.id)
+ ctx.hidden_by_name(&self.real_canonical_name(ctx, false, true), self.id)
}
/// Is this item opaque?
@@ -465,7 +476,7 @@ impl Item {
debug_assert!(ctx.in_codegen_phase(),
"You're not supposed to call this yet");
self.annotations.opaque() ||
- ctx.opaque_by_name(&self.real_canonical_name(ctx, false, true))
+ ctx.opaque_by_name(&self.real_canonical_name(ctx, false, true))
}
/// Get the canonical name without taking into account the replaces
@@ -482,7 +493,8 @@ impl Item {
fn real_canonical_name(&self,
ctx: &BindgenContext,
count_namespaces: bool,
- for_name_checking: bool) -> String {
+ for_name_checking: bool)
+ -> String {
let base_name = match *self.kind() {
ItemKind::Type(ref ty) => {
match *ty.kind() {
@@ -538,7 +550,7 @@ impl Item {
break;
}
let fun = ctx.resolve_item(method.signature())
- .expect_function();
+ .expect_function();
if fun.name() == base {
count += 1;
}
@@ -552,9 +564,7 @@ impl Item {
}
Some(base)
}
- ItemKind::Var(ref var) => {
- Some(var.name().to_owned())
- }
+ ItemKind::Var(ref var) => Some(var.name().to_owned()),
ItemKind::Module(ref module) => {
module.name().map(ToOwned::to_owned)
}
@@ -595,7 +605,8 @@ impl Item {
fn make_exposed_name(&self,
parent_name: Option<String>,
base_name: Option<String>,
- ctx: &BindgenContext) -> String {
+ ctx: &BindgenContext)
+ -> String {
lazy_static! {
static ref RE_ENDS_WITH_BINDGEN_TY: Regex = Regex::new(r"_bindgen_ty(_\d+)+$").unwrap();
static ref RE_ENDS_WITH_BINDGEN_MOD: Regex = Regex::new(r"_bindgen_mod(_\d+)+$").unwrap();
@@ -606,18 +617,24 @@ impl Item {
_ => (&*RE_ENDS_WITH_BINDGEN_TY, "ty"),
};
- let parent_name = parent_name.and_then(|n| if n.is_empty() { None } else { Some(n) });
+ let parent_name =
+ parent_name.and_then(|n| if n.is_empty() { None } else { Some(n) });
match (parent_name, base_name) {
(Some(parent), Some(base)) => format!("{}_{}", parent, base),
(Some(parent), None) => {
if re.is_match(parent.as_str()) {
format!("{}_{}", parent, self.exposed_id(ctx))
} else {
- format!("{}__bindgen_{}_{}", parent, kind, self.exposed_id(ctx))
+ format!("{}__bindgen_{}_{}",
+ parent,
+ kind,
+ self.exposed_id(ctx))
}
}
(None, Some(base)) => base,
- (None, None) => format!("_bindgen_{}_{}", kind, self.exposed_id(ctx)),
+ (None, None) => {
+ format!("_bindgen_{}_{}", kind, self.exposed_id(ctx))
+ }
}
}
@@ -645,13 +662,16 @@ impl Item {
}
impl ClangItemParser for Item {
- fn builtin_type(kind: TypeKind, is_const: bool, ctx: &mut BindgenContext) -> ItemId {
+ fn builtin_type(kind: TypeKind,
+ is_const: bool,
+ ctx: &mut BindgenContext)
+ -> ItemId {
// Feel free to add more here, I'm just lazy.
match kind {
TypeKind::Void |
TypeKind::Int(..) |
TypeKind::Pointer(..) |
- TypeKind::Float(..) => {},
+ TypeKind::Float(..) => {}
_ => panic!("Unsupported builtin type"),
}
@@ -659,14 +679,16 @@ impl ClangItemParser for Item {
let id = ItemId::next();
let module = ctx.root_module();
ctx.add_item(Item::new(id, None, None, module, ItemKind::Type(ty)),
- None, None);
+ None,
+ None);
id
}
fn parse(cursor: clang::Cursor,
parent_id: Option<ItemId>,
- context: &mut BindgenContext) -> Result<ItemId, ParseError> {
+ context: &mut BindgenContext)
+ -> Result<ItemId, ParseError> {
use ir::function::Function;
use ir::module::Module;
use ir::var::Var;
@@ -723,11 +745,12 @@ impl ClangItemParser for Item {
cursor
};
match Self::from_ty(&applicable_cursor.cur_type(),
- Some(applicable_cursor), parent_id, context)
- {
+ Some(applicable_cursor),
+ parent_id,
+ context) {
Ok(ty) => return Ok(ty),
Err(ParseError::Recurse) => return Err(ParseError::Recurse),
- Err(ParseError::Continue) => {},
+ Err(ParseError::Continue) => {}
}
}
@@ -741,11 +764,13 @@ impl ClangItemParser for Item {
CXCursor_MacroDefinition |
CXCursor_InclusionDirective => {
debug!("Unhandled cursor kind {:?}: {:?}",
- cursor.kind(), cursor);
- },
- _ =>{
+ cursor.kind(),
+ cursor);
+ }
+ _ => {
error!("Unhandled cursor kind {:?}: {:?}",
- cursor.kind(), cursor);
+ cursor.kind(),
+ cursor);
}
}
@@ -756,8 +781,13 @@ impl ClangItemParser for Item {
fn from_ty_or_ref(ty: clang::Type,
location: Option<clang::Cursor>,
parent_id: Option<ItemId>,
- context: &mut BindgenContext) -> ItemId {
- Self::from_ty_or_ref_with_id(ItemId::next(), ty, location, parent_id, context)
+ context: &mut BindgenContext)
+ -> ItemId {
+ Self::from_ty_or_ref_with_id(ItemId::next(),
+ ty,
+ location,
+ parent_id,
+ context)
}
/// Parse a C++ type. If we find a reference to a type that has not been
@@ -774,13 +804,22 @@ impl ClangItemParser for Item {
ty: clang::Type,
location: Option<clang::Cursor>,
parent_id: Option<ItemId>,
- context: &mut BindgenContext) -> ItemId {
- debug!("from_ty_or_ref_with_id: {:?} {:?}, {:?}, {:?}", potential_id, ty, location, parent_id);
+ context: &mut BindgenContext)
+ -> ItemId {
+ debug!("from_ty_or_ref_with_id: {:?} {:?}, {:?}, {:?}",
+ potential_id,
+ ty,
+ location,
+ parent_id);
if context.collected_typerefs() {
debug!("refs already collected, resolving directly");
- return Self::from_ty_with_id(potential_id, &ty, location, parent_id, context)
- .expect("Unable to resolve type");
+ return Self::from_ty_with_id(potential_id,
+ &ty,
+ location,
+ parent_id,
+ context)
+ .expect("Unable to resolve type");
}
if let Some(ty) = context.builtin_or_resolved_ty(potential_id,
@@ -795,9 +834,14 @@ impl ClangItemParser for Item {
let is_const = ty.is_const();
let kind = TypeKind::UnresolvedTypeRef(ty, location, parent_id);
let current_module = context.current_module();
- context.add_item(Item::new(potential_id, None, None,
+ context.add_item(Item::new(potential_id,
+ None,
+ None,
parent_id.unwrap_or(current_module),
- ItemKind::Type(Type::new(None, None, kind, is_const))),
+ ItemKind::Type(Type::new(None,
+ None,
+ kind,
+ is_const))),
Some(clang::Cursor::null()),
None);
potential_id
@@ -807,7 +851,8 @@ impl ClangItemParser for Item {
fn from_ty(ty: &clang::Type,
location: Option<clang::Cursor>,
parent_id: Option<ItemId>,
- context: &mut BindgenContext) -> Result<ItemId, ParseError> {
+ context: &mut BindgenContext)
+ -> Result<ItemId, ParseError> {
Self::from_ty_with_id(ItemId::next(), ty, location, parent_id, context)
}
@@ -823,7 +868,8 @@ impl ClangItemParser for Item {
ty: &clang::Type,
location: Option<clang::Cursor>,
parent_id: Option<ItemId>,
- context: &mut BindgenContext) -> Result<ItemId, ParseError> {
+ context: &mut BindgenContext)
+ -> Result<ItemId, ParseError> {
use clangll::*;
let decl = {
@@ -836,19 +882,18 @@ impl ClangItemParser for Item {
}
};
- let comment =
- decl.raw_comment()
- .or_else(|| location.as_ref().and_then(|l| l.raw_comment()));
- let annotations =
- Annotations::new(&decl)
- .or_else(|| location.as_ref().and_then(|l| Annotations::new(l)));
+ let comment = decl.raw_comment()
+ .or_else(|| location.as_ref().and_then(|l| l.raw_comment()));
+ let annotations = Annotations::new(&decl)
+ .or_else(|| location.as_ref().and_then(|l| Annotations::new(l)));
- if let Some(ref replaced) = annotations.as_ref().and_then(|a| a.use_instead_of()) {
+ if let Some(ref replaced) = annotations.as_ref()
+ .and_then(|a| a.use_instead_of()) {
context.replace(replaced, id);
}
- if let Some(ty) = context.builtin_or_resolved_ty(id, parent_id,
- ty, location) {
+ if let Some(ty) =
+ context.builtin_or_resolved_ty(id, parent_id, ty, location) {
return Ok(ty);
}
@@ -856,7 +901,9 @@ impl ClangItemParser for Item {
let mut valid_decl = decl.kind() != CXCursor_NoDeclFound;
let declaration_to_look_for = if valid_decl {
decl.canonical()
- } else if location.is_some() && location.unwrap().kind() == CXCursor_ClassTemplate {
+ } else if location.is_some() &&
+ location.unwrap().kind() ==
+ CXCursor_ClassTemplate {
valid_decl = true;
location.unwrap()
} else {
@@ -864,7 +911,9 @@ impl ClangItemParser for Item {
};
if valid_decl {
- if let Some(&(_, item_id)) = context.currently_parsed_types.iter().find(|&&(d, _)| d == declaration_to_look_for) {
+ if let Some(&(_, item_id)) = context.currently_parsed_types
+ .iter()
+ .find(|&&(d, _)| d == declaration_to_look_for) {
debug!("Avoiding recursion parsing type: {:?}", ty);
return Ok(item_id);
}
@@ -879,11 +928,13 @@ impl ClangItemParser for Item {
let ret = match result {
Ok(ParseResult::AlreadyResolved(ty)) => Ok(ty),
Ok(ParseResult::New(item, declaration)) => {
- context.add_item(Item::new(id, comment, annotations,
- parent_id.unwrap_or(current_module),
- ItemKind::Type(item)),
- declaration,
- location);
+ context.add_item(Item::new(id,
+ comment,
+ annotations,
+ parent_id.unwrap_or(current_module),
+ ItemKind::Type(item)),
+ declaration,
+ location);
Ok(id)
}
Err(ParseError::Continue) => Err(ParseError::Continue),
@@ -897,13 +948,18 @@ impl ClangItemParser for Item {
// declaration_to_look_for suspiciously shares a lot of
// logic with ir::context, so we should refactor that.
if valid_decl {
- let (popped_decl, _) = context.currently_parsed_types.pop().unwrap();
+ let (popped_decl, _) =
+ context.currently_parsed_types.pop().unwrap();
assert_eq!(popped_decl, declaration_to_look_for);
}
location.visit(|cur, _other| {
use clangll::*;
- result = Item::from_ty_with_id(id, ty, Some(*cur), parent_id, context);
+ result = Item::from_ty_with_id(id,
+ ty,
+ Some(*cur),
+ parent_id,
+ context);
match result {
Ok(..) => CXChildVisit_Break,
Err(ParseError::Recurse) => CXChildVisit_Recurse,
@@ -912,7 +968,8 @@ impl ClangItemParser for Item {
});
if valid_decl {
- context.currently_parsed_types.push((declaration_to_look_for, id));
+ context.currently_parsed_types
+ .push((declaration_to_look_for, id));
}
}
// If we have recursed into the AST all we know, and we still
@@ -936,7 +993,8 @@ impl ClangItemParser for Item {
};
if valid_decl {
- let (popped_decl, _) = context.currently_parsed_types.pop().unwrap();
+ let (popped_decl, _) =
+ context.currently_parsed_types.pop().unwrap();
assert_eq!(popped_decl, declaration_to_look_for);
}
@@ -954,14 +1012,18 @@ impl ClangItemParser for Item {
name: S,
default: Option<ItemId>,
parent_id: ItemId,
- context: &mut BindgenContext) -> ItemId
- where S: Into<String>
+ context: &mut BindgenContext)
+ -> ItemId
+ where S: Into<String>,
{
// see tests/headers/const_tparam.hpp
// and tests/headers/variadic_tname.hpp
let name = name.into().replace("const ", "").replace(".", "");
- context.add_item(Item::new(id, None, None, parent_id,
+ context.add_item(Item::new(id,
+ None,
+ None,
+ parent_id,
ItemKind::Type(Type::named(name, default))),
None,
None);
@@ -972,10 +1034,15 @@ impl ClangItemParser for Item {
fn named_type<S>(name: S,
default: Option<ItemId>,
parent_id: ItemId,
- context: &mut BindgenContext) -> ItemId
- where S: Into<String>
+ context: &mut BindgenContext)
+ -> ItemId
+ where S: Into<String>,
{
- Self::named_type_with_id(ItemId::next(), name, default, parent_id, context)
+ Self::named_type_with_id(ItemId::next(),
+ name,
+ default,
+ parent_id,
+ context)
}
}
@@ -989,7 +1056,8 @@ impl ItemCanonicalName for Item {
if self.canonical_name_cache.borrow().is_none() {
*self.canonical_name_cache.borrow_mut() =
Some(self.real_canonical_name(ctx,
- ctx.options().enable_cxx_namespaces,
+ ctx.options()
+ .enable_cxx_namespaces,
false));
}
return self.canonical_name_cache.borrow().as_ref().unwrap().clone();
@@ -1015,8 +1083,10 @@ impl ItemCanonicalPath for Item {
if let ItemKind::Type(ref ty) = *self.kind() {
match *ty.kind() {
TypeKind::Comp(ref ci) if ci.is_template_specialization() => {
- return ci.specialized_template().unwrap().canonical_path(ctx);
- },
+ return ci.specialized_template()
+ .unwrap()
+ .canonical_path(ctx);
+ }
TypeKind::ResolvedTypeRef(inner) |
TypeKind::TemplateRef(inner, _) => {
return inner.canonical_path(ctx);
@@ -1029,7 +1099,8 @@ impl ItemCanonicalPath for Item {
}
let mut parent_path = self.parent_id().canonical_path(&ctx);
- if parent_path.last().map_or(false, |parent_name| parent_name.is_empty()) {
+ if parent_path.last()
+ .map_or(false, |parent_name| parent_name.is_empty()) {
// This only happens (or should only happen) when we're an alias,
// and our parent is a templated alias, in which case the last
// component of the path will be empty.
diff --git a/src/ir/module.rs b/src/ir/module.rs
index 591a4e3a..c582d3eb 100644
--- a/src/ir/module.rs
+++ b/src/ir/module.rs
@@ -1,10 +1,10 @@
//! Intermediate representation for modules (AKA C++ namespaces).
-use super::context::BindgenContext;
-use super::item::ItemId;
use clang;
use parse::{ClangSubItemParser, ParseError, ParseResult};
use parse_one;
+use super::context::BindgenContext;
+use super::item::ItemId;
/// A module, as in, a C++ namespace.
#[derive(Clone, Debug)]
@@ -41,18 +41,22 @@ impl Module {
}
impl ClangSubItemParser for Module {
- fn parse(cursor: clang::Cursor, ctx: &mut BindgenContext) -> Result<ParseResult<Self>, ParseError> {
+ fn parse(cursor: clang::Cursor,
+ ctx: &mut BindgenContext)
+ -> Result<ParseResult<Self>, ParseError> {
use clangll::*;
match cursor.kind() {
CXCursor_Namespace => {
let module_id = ctx.module(cursor);
ctx.with_module(module_id, |ctx, children| {
- cursor.visit(|cursor, _| parse_one(ctx, *cursor, Some(module_id), children))
+ cursor.visit(|cursor, _| {
+ parse_one(ctx, *cursor, Some(module_id), children)
+ })
});
Ok(ParseResult::AlreadyResolved(module_id))
}
- _ => Err(ParseError::Continue)
+ _ => Err(ParseError::Continue),
}
}
}
diff --git a/src/ir/ty.rs b/src/ir/ty.rs
index a914ce14..bab50024 100644
--- a/src/ir/ty.rs
+++ b/src/ir/ty.rs
@@ -1,15 +1,15 @@
//! Everything related to types in our intermediate representation.
+use clang::{self, Cursor};
+use parse::{ClangItemParser, ParseError, ParseResult};
use super::comp::CompInfo;
+use super::context::BindgenContext;
use super::enum_ty::Enum;
use super::function::FunctionSig;
-use super::item::{Item, ItemId};
use super::int::IntKind;
+use super::item::{Item, ItemId};
use super::layout::Layout;
-use super::context::BindgenContext;
use super::type_collector::{ItemSet, TypeCollector};
-use parse::{ClangItemParser, ParseResult, ParseError};
-use clang::{self, Cursor};
/// The base representation of a type in bindgen.
///
@@ -49,7 +49,8 @@ impl Type {
pub fn new(name: Option<String>,
layout: Option<Layout>,
kind: TypeKind,
- is_const: bool) -> Self {
+ is_const: bool)
+ -> Self {
Type {
name: name,
layout: layout,
@@ -141,15 +142,17 @@ impl Type {
self.layout.or_else(|| {
match self.kind {
- TypeKind::Comp(ref ci)
- => ci.layout(ctx),
+ TypeKind::Comp(ref ci) => ci.layout(ctx),
// FIXME(emilio): This is a hack for anonymous union templates.
// Use the actual pointer size!
TypeKind::Pointer(..) |
- TypeKind::BlockPointer
- => Some(Layout::new(mem::size_of::<*mut ()>(), mem::align_of::<*mut ()>())),
- TypeKind::ResolvedTypeRef(inner)
- => ctx.resolve_type(inner).layout(ctx),
+ TypeKind::BlockPointer => {
+ Some(Layout::new(mem::size_of::<*mut ()>(),
+ mem::align_of::<*mut ()>()))
+ }
+ TypeKind::ResolvedTypeRef(inner) => {
+ ctx.resolve_type(inner).layout(ctx)
+ }
_ => None,
}
})
@@ -168,9 +171,7 @@ impl Type {
}
TypeKind::ResolvedTypeRef(t) |
TypeKind::TemplateAlias(t, _) |
- TypeKind::Alias(_, t) => {
- ctx.resolve_type(t).can_derive_debug(ctx)
- }
+ TypeKind::Alias(_, t) => ctx.resolve_type(t).can_derive_debug(ctx),
TypeKind::Comp(ref info) => {
info.can_derive_debug(ctx, self.layout(ctx))
}
@@ -200,14 +201,17 @@ impl Type {
/// is an error.
///
/// That's the whole point of the existence of `can_derive_copy_in_array`.
- pub fn can_derive_copy_in_array(&self, ctx: &BindgenContext, item: &Item) -> bool {
+ pub fn can_derive_copy_in_array(&self,
+ ctx: &BindgenContext,
+ item: &Item)
+ -> bool {
match self.kind {
TypeKind::ResolvedTypeRef(t) |
TypeKind::TemplateAlias(t, _) |
TypeKind::Alias(_, t) |
TypeKind::Array(t, _) => {
ctx.resolve_item(t)
- .can_derive_copy_in_array(ctx)
+ .can_derive_copy_in_array(ctx)
}
TypeKind::Named(..) => false,
_ => self.can_derive_copy(ctx, item),
@@ -225,12 +229,8 @@ impl Type {
TypeKind::ResolvedTypeRef(t) |
TypeKind::TemplateAlias(t, _) |
TypeKind::TemplateRef(t, _) |
- TypeKind::Alias(_, t) => {
- ctx.resolve_item(t).can_derive_copy(ctx)
- }
- TypeKind::Comp(ref info) => {
- info.can_derive_copy(ctx, item)
- }
+ TypeKind::Alias(_, t) => ctx.resolve_item(t).can_derive_copy(ctx),
+ TypeKind::Comp(ref info) => info.can_derive_copy(ctx, item),
_ => true,
}
}
@@ -242,12 +242,8 @@ impl Type {
TypeKind::TemplateRef(t, _) |
TypeKind::TemplateAlias(t, _) |
TypeKind::Alias(_, t) |
- TypeKind::ResolvedTypeRef(t) => {
- ctx.resolve_type(t).has_vtable(ctx)
- }
- TypeKind::Comp(ref info) => {
- info.has_vtable(ctx)
- }
+ TypeKind::ResolvedTypeRef(t) => ctx.resolve_type(t).has_vtable(ctx),
+ TypeKind::Comp(ref info) => info.has_vtable(ctx),
_ => false,
}
@@ -262,9 +258,7 @@ impl Type {
TypeKind::ResolvedTypeRef(t) => {
ctx.resolve_type(t).has_destructor(ctx)
}
- TypeKind::Comp(ref info) => {
- info.has_destructor(ctx)
- }
+ TypeKind::Comp(ref info) => info.has_destructor(ctx),
_ => false,
}
}
@@ -272,7 +266,8 @@ impl Type {
/// See the comment in `Item::signature_contains_named_type`.
pub fn signature_contains_named_type(&self,
ctx: &BindgenContext,
- ty: &Type) -> bool {
+ ty: &Type)
+ -> bool {
debug_assert!(ty.is_named());
let name = match *ty.kind() {
TypeKind::Named(ref name, _) => name,
@@ -280,38 +275,40 @@ impl Type {
};
match self.kind {
- TypeKind::Named(ref this_name, _)
- => this_name == name,
+ TypeKind::Named(ref this_name, _) => this_name == name,
TypeKind::ResolvedTypeRef(t) |
TypeKind::Array(t, _) |
TypeKind::Pointer(t) |
- TypeKind::Alias(_, t)
- => ctx.resolve_type(t)
- .signature_contains_named_type(ctx, ty),
+ TypeKind::Alias(_, t) => {
+ ctx.resolve_type(t)
+ .signature_contains_named_type(ctx, ty)
+ }
TypeKind::Function(ref sig) => {
sig.argument_types().iter().any(|&(_, arg)| {
ctx.resolve_type(arg)
- .signature_contains_named_type(ctx, ty)
+ .signature_contains_named_type(ctx, ty)
}) ||
ctx.resolve_type(sig.return_type())
- .signature_contains_named_type(ctx, ty)
- },
+ .signature_contains_named_type(ctx, ty)
+ }
TypeKind::TemplateAlias(_, ref template_args) |
TypeKind::TemplateRef(_, ref template_args) => {
template_args.iter().any(|arg| {
ctx.resolve_type(*arg)
- .signature_contains_named_type(ctx, ty)
+ .signature_contains_named_type(ctx, ty)
})
}
- TypeKind::Comp(ref ci)
- => ci.signature_contains_named_type(ctx, ty),
- _ => false,
+ TypeKind::Comp(ref ci) => ci.signature_contains_named_type(ctx, ty),
+ _ => false,
}
}
/// See safe_canonical_type.
- pub fn canonical_type<'tr>(&'tr self, ctx: &'tr BindgenContext) -> &'tr Type {
- self.safe_canonical_type(ctx).expect("Should have been resolved after parsing!")
+ pub fn canonical_type<'tr>(&'tr self,
+ ctx: &'tr BindgenContext)
+ -> &'tr Type {
+ self.safe_canonical_type(ctx)
+ .expect("Should have been resolved after parsing!")
}
/// Returns the canonical type of this type, that is, the "inner type".
@@ -319,7 +316,9 @@ impl Type {
/// For example, for a `typedef`, the canonical type would be the
/// `typedef`ed type, for a template specialization, would be the template
/// its specializing, and so on. Return None if the type is unresolved.
- pub fn safe_canonical_type<'tr>(&'tr self, ctx: &'tr BindgenContext) -> Option<&'tr Type> {
+ pub fn safe_canonical_type<'tr>(&'tr self,
+ ctx: &'tr BindgenContext)
+ -> Option<&'tr Type> {
match self.kind {
TypeKind::Named(..) |
TypeKind::Array(..) |
@@ -337,8 +336,9 @@ impl Type {
TypeKind::ResolvedTypeRef(inner) |
TypeKind::Alias(_, inner) |
TypeKind::TemplateAlias(inner, _) |
- TypeKind::TemplateRef(inner, _)
- => ctx.resolve_type(inner).safe_canonical_type(ctx),
+ TypeKind::TemplateRef(inner, _) => {
+ ctx.resolve_type(inner).safe_canonical_type(ctx)
+ }
TypeKind::UnresolvedTypeRef(..) => None,
}
@@ -413,7 +413,10 @@ pub enum TypeKind {
/// already known types, and are converted to ResolvedTypeRef.
///
/// see tests/headers/typeref.hpp to see somewhere where this is a problem.
- UnresolvedTypeRef(clang::Type, Option<clang::Cursor>, /* parent_id */ Option<ItemId>),
+ UnresolvedTypeRef(clang::Type,
+ Option<clang::Cursor>,
+ /* parent_id */
+ Option<ItemId>),
/// An indirection to another type.
///
@@ -438,14 +441,14 @@ impl Type {
TypeKind::Void => true,
TypeKind::Comp(ref ci) => ci.is_unsized(ctx),
TypeKind::Array(inner, size) => {
- size == 0 ||
- ctx.resolve_type(inner).is_unsized(ctx)
+ size == 0 || ctx.resolve_type(inner).is_unsized(ctx)
}
TypeKind::ResolvedTypeRef(inner) |
TypeKind::Alias(_, inner) |
TypeKind::TemplateAlias(inner, _) |
- TypeKind::TemplateRef(inner, _)
- => ctx.resolve_type(inner).is_unsized(ctx),
+ TypeKind::TemplateRef(inner, _) => {
+ ctx.resolve_type(inner).is_unsized(ctx)
+ }
TypeKind::Named(..) |
TypeKind::Int(..) |
TypeKind::Float(..) |
@@ -456,8 +459,9 @@ impl Type {
TypeKind::BlockPointer |
TypeKind::Pointer(..) => false,
- TypeKind::UnresolvedTypeRef(..)
- => unreachable!("Should have been resolved after parsing!"),
+ TypeKind::UnresolvedTypeRef(..) => {
+ unreachable!("Should have been resolved after parsing!")
+ }
}
}
@@ -470,10 +474,11 @@ impl Type {
ty: &clang::Type,
location: Option<Cursor>,
parent_id: Option<ItemId>,
- ctx: &mut BindgenContext) -> Result<ParseResult<Self>, ParseError> {
+ ctx: &mut BindgenContext)
+ -> Result<ParseResult<Self>, ParseError> {
use clangll::*;
- if let Some(ty) = ctx.builtin_or_resolved_ty(potential_id, parent_id,
- ty, location) {
+ if let Some(ty) =
+ ctx.builtin_or_resolved_ty(potential_id, parent_id, ty, location) {
debug!("{:?} already resolved: {:?}", ty, location);
return Ok(ParseResult::AlreadyResolved(ty));
}
@@ -490,11 +495,13 @@ impl Type {
CXType_Unexposed if *ty != canonical_ty &&
canonical_ty.kind() != CXType_Invalid => {
debug!("Looking for canonical type: {:?}", canonical_ty);
- return Self::from_clang_ty(potential_id, &canonical_ty,
- location, parent_id, ctx);
+ return Self::from_clang_ty(potential_id,
+ &canonical_ty,
+ location,
+ parent_id,
+ ctx);
}
- CXType_Unexposed |
- CXType_Invalid => {
+ CXType_Unexposed | CXType_Invalid => {
// For some reason Clang doesn't give us any hint
// in some situations where we should generate a
// function pointer (see
@@ -505,22 +512,25 @@ impl Type {
let signature =
try!(FunctionSig::from_ty(ty, &location.unwrap_or(cursor), ctx));
TypeKind::Function(signature)
- // Same here, with template specialisations we can safely assume
- // this is a Comp(..)
+ // Same here, with template specialisations we can safely
+ // assume
+ // this is a Comp(..)
} else if ty.template_args().map_or(false, |x| x.len() > 0) {
debug!("Template specialization: {:?}", ty);
let complex =
CompInfo::from_ty(potential_id, ty, location, ctx)
- .expect("C'mon");
+ .expect("C'mon");
TypeKind::Comp(complex)
} else if let Some(location) = location {
match location.kind() {
CXCursor_ClassTemplatePartialSpecialization |
CXCursor_ClassTemplate => {
name = location.spelling();
- let complex =
- CompInfo::from_ty(potential_id, ty, Some(location), ctx)
- .expect("C'mon");
+ let complex = CompInfo::from_ty(potential_id,
+ ty,
+ Some(location),
+ ctx)
+ .expect("C'mon");
TypeKind::Comp(complex)
}
CXCursor_TypeAliasTemplateDecl => {
@@ -633,40 +643,49 @@ impl Type {
return Err(ParseError::Continue);
}
}
- // NOTE: We don't resolve pointers eagerly because the pointee type
- // might not have been parsed, and if it contains templates or
- // something else we might get confused, see the comment inside
+ // NOTE: We don't resolve pointers eagerly because the
+ // pointee type
+ // might not have been parsed, and if it contains templates
+ // or
+ // something else we might get confused, see the comment
+ // inside
// TypeRef.
//
- // We might need to, though, if the context is already in the
+ // We might need to, though, if the context is already in
+ // the
// process of resolving them.
CXType_MemberPointer |
CXType_Pointer => {
- let inner =
- Item::from_ty_or_ref(ty.pointee_type(), location,
- parent_id, ctx);
+ let inner = Item::from_ty_or_ref(ty.pointee_type(),
+ location,
+ parent_id,
+ ctx);
TypeKind::Pointer(inner)
}
- CXType_BlockPointer => {
- TypeKind::BlockPointer
- }
- // XXX: RValueReference is most likely wrong, but I don't think we
+ CXType_BlockPointer => TypeKind::BlockPointer,
+ // XXX: RValueReference is most likely wrong, but I don't
+ // think we
// can even add bindings for that, so huh.
CXType_RValueReference |
CXType_LValueReference => {
- let inner =
- Item::from_ty_or_ref(ty.pointee_type(), location,
- parent_id, ctx);
+ let inner = Item::from_ty_or_ref(ty.pointee_type(),
+ location,
+ parent_id,
+ ctx);
TypeKind::Reference(inner)
}
// XXX DependentSizedArray is wrong
CXType_VariableArray |
CXType_DependentSizedArray |
CXType_IncompleteArray => {
- let inner = Item::from_ty(ty.elem_type().as_ref()
- .expect("Not an appropriate type?"),
- location, parent_id, ctx)
- .expect("Not able to resolve array element?");
+ let inner =
+ Item::from_ty(ty.elem_type()
+ .as_ref()
+ .expect("Not an appropriate type?"),
+ location,
+ parent_id,
+ ctx)
+ .expect("Not able to resolve array element?");
TypeKind::Pointer(inner)
}
CXType_FunctionNoProto |
@@ -681,41 +700,55 @@ impl Type {
TypeKind::Alias(ty.spelling(), inner)
}
CXType_Enum => {
- let enum_ = Enum::from_ty(ty, ctx)
- .expect("Not an enum?");
+ let enum_ = Enum::from_ty(ty, ctx).expect("Not an enum?");
TypeKind::Enum(enum_)
}
CXType_Record => {
- let complex = CompInfo::from_ty(potential_id, ty, location, ctx)
- .expect("Not a complex type?");
+ let complex =
+ CompInfo::from_ty(potential_id, ty, location, ctx)
+ .expect("Not a complex type?");
TypeKind::Comp(complex)
}
- // FIXME: We stub vectors as arrays since in 99% of the cases the
- // layout is going to be correct, and there's no way we can generate
+ // FIXME: We stub vectors as arrays since in 99% of the
+ // cases the
+ // layout is going to be correct, and there's no way we can
+ // generate
// vector types properly in Rust for now.
//
// That being said, that should be fixed eventually.
CXType_Vector |
CXType_ConstantArray => {
- let inner = Item::from_ty(ty.elem_type().as_ref()
- .expect("Not an appropriate type?"),
- location, parent_id, ctx)
- .expect("Not able to resolve array element?");
+ let inner =
+ Item::from_ty(ty.elem_type()
+ .as_ref()
+ .expect("Not an appropriate type?"),
+ location,
+ parent_id,
+ ctx)
+ .expect("Not able to resolve array element?");
TypeKind::Array(inner, ty.num_elements().unwrap())
}
- // A complex number is always a real and an imaginary part, so
+ // A complex number is always a real and an imaginary part,
+ // so
// represent that as a two-item array.
CXType_Complex => {
- let inner = Item::from_ty(ty.elem_type().as_ref()
- .expect("Not an appropriate type?"),
- location, parent_id, ctx)
- .expect("Not able to resolve array element?");
+ let inner =
+ Item::from_ty(ty.elem_type()
+ .as_ref()
+ .expect("Not an appropriate type?"),
+ location,
+ parent_id,
+ ctx)
+ .expect("Not able to resolve array element?");
TypeKind::Array(inner, 2)
}
#[cfg(not(feature="llvm_stable"))]
CXType_Elaborated => {
- return Self::from_clang_ty(potential_id, &ty.named(),
- location, parent_id, ctx);
+ return Self::from_clang_ty(potential_id,
+ &ty.named(),
+ location,
+ parent_id,
+ ctx);
}
_ => {
error!("unsupported type {:?} at {:?}", ty, location);
@@ -746,8 +779,9 @@ impl TypeCollector for Type {
TypeKind::TemplateAlias(inner, _) |
TypeKind::Alias(_, inner) |
TypeKind::Named(_, Some(inner)) |
- TypeKind::ResolvedTypeRef(inner)
- => inner.collect_types(context, types, &()),
+ TypeKind::ResolvedTypeRef(inner) => {
+ inner.collect_types(context, types, &())
+ }
TypeKind::TemplateRef(inner, ref template_args) => {
inner.collect_types(context, types, &());
@@ -762,7 +796,7 @@ impl TypeCollector for Type {
// FIXME: Pending types!
ref other @ _ => {
debug!("Ignoring: {:?}", other);
- },
+ }
}
}
}
diff --git a/src/ir/var.rs b/src/ir/var.rs
index e9245e1a..6d9b61e1 100644
--- a/src/ir/var.rs
+++ b/src/ir/var.rs
@@ -1,12 +1,12 @@
//! Intermediate representation of variables.
-use super::item::{Item, ItemId};
+use clang;
+use parse::{ClangItemParser, ClangSubItemParser, ParseError, ParseResult};
use super::context::BindgenContext;
-use super::ty::TypeKind;
-use super::int::IntKind;
use super::function::cursor_mangling;
-use parse::{ClangItemParser, ClangSubItemParser, ParseResult, ParseError};
-use clang;
+use super::int::IntKind;
+use super::item::{Item, ItemId};
+use super::ty::TypeKind;
/// A `Var` is our intermediate representation of a variable.
#[derive(Debug)]
@@ -30,7 +30,8 @@ impl Var {
mangled: Option<String>,
ty: ItemId,
val: Option<i64>,
- is_const: bool) -> Var {
+ is_const: bool)
+ -> Var {
assert!(!name.is_empty());
Var {
name: name,
@@ -69,7 +70,8 @@ impl Var {
impl ClangSubItemParser for Var {
fn parse(cursor: clang::Cursor,
- context: &mut BindgenContext) -> Result<ParseResult<Self>, ParseError> {
+ context: &mut BindgenContext)
+ -> Result<ParseResult<Self>, ParseError> {
use clangll::*;
match cursor.kind() {
CXCursor_MacroDefinition => {
@@ -91,14 +93,25 @@ impl ClangSubItemParser for Var {
context.note_parsed_macro(name.clone());
let ty = if value < 0 {
- Item::builtin_type(TypeKind::Int(IntKind::Int), true, context)
- } else if value.abs() > u32::max_value() as i64 {
- Item::builtin_type(TypeKind::Int(IntKind::ULongLong), true, context)
+ Item::builtin_type(TypeKind::Int(IntKind::Int),
+ true,
+ context)
+ } else if value.abs() > u32::max_value() as i64 {
+ Item::builtin_type(TypeKind::Int(IntKind::ULongLong),
+ true,
+ context)
} else {
- Item::builtin_type(TypeKind::Int(IntKind::UInt), true, context)
+ Item::builtin_type(TypeKind::Int(IntKind::UInt),
+ true,
+ context)
};
- Ok(ParseResult::New(Var::new(name, None, ty, Some(value), true), Some(cursor)))
+ Ok(ParseResult::New(Var::new(name,
+ None,
+ ty,
+ Some(value),
+ true),
+ Some(cursor)))
}
CXCursor_VarDecl => {
let name = cursor.spelling();
@@ -113,7 +126,7 @@ impl ClangSubItemParser for Var {
let is_const = ty.is_const();
let ty = Item::from_ty(&ty, Some(cursor), None, context)
- .expect("Unable to resolve constant type?");
+ .expect("Unable to resolve constant type?");
// Note: Ty might not be totally resolved yet, see
// tests/headers/inner_const.hpp
@@ -144,7 +157,8 @@ impl ClangSubItemParser for Var {
/// Try and parse the immediately found tokens from an unit (if any) to integers
fn parse_int_literal_tokens(cursor: &clang::Cursor,
- unit: &clang::TranslationUnit) -> Option<i64> {
+ unit: &clang::TranslationUnit)
+ -> Option<i64> {
use clangll::{CXToken_Literal, CXToken_Punctuation};
let tokens = match unit.tokens(cursor) {
@@ -158,11 +172,11 @@ fn parse_int_literal_tokens(cursor: &clang::Cursor,
match token.kind {
CXToken_Punctuation if token.spelling == "-" => {
negate = !negate;
- },
+ }
CXToken_Literal => {
literal = Some(token.spelling);
- break
- },
+ break;
+ }
_ => {
// Reset values if we found anything else
negate = false;
@@ -172,21 +186,23 @@ fn parse_int_literal_tokens(cursor: &clang::Cursor,
}
literal.and_then(|lit| {
- if lit.starts_with("0x") {
- // TODO: try to preserve hex literals?
- i64::from_str_radix(&lit[2..], 16).ok()
- } else if lit == "0" {
- Some(0)
- } else if lit.starts_with("0") {
- i64::from_str_radix(&lit[1..], 8).ok()
- } else {
- lit.parse().ok()
- }
- }).map(|lit| if negate { -lit } else { lit })
+ if lit.starts_with("0x") {
+ // TODO: try to preserve hex literals?
+ i64::from_str_radix(&lit[2..], 16).ok()
+ } else if lit == "0" {
+ Some(0)
+ } else if lit.starts_with("0") {
+ i64::from_str_radix(&lit[1..], 8).ok()
+ } else {
+ lit.parse().ok()
+ }
+ })
+ .map(|lit| if negate { -lit } else { lit })
}
fn get_integer_literal_from_cursor(cursor: &clang::Cursor,
- unit: &clang::TranslationUnit) -> Option<i64> {
+ unit: &clang::TranslationUnit)
+ -> Option<i64> {
use clangll::*;
let mut value = None;
cursor.visit(|c, _| {
@@ -198,7 +214,7 @@ fn get_integer_literal_from_cursor(cursor: &clang::Cursor,
CXCursor_UnexposedExpr => {
value = get_integer_literal_from_cursor(&c, unit);
}
- _ => ()
+ _ => (),
}
if value.is_some() {
CXChildVisit_Break
diff --git a/src/lib.rs b/src/lib.rs
index 4f126672..1592c275 100755
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -73,23 +73,23 @@ mod codegen {
include!(concat!(env!("OUT_DIR"), "/codegen.rs"));
}
+
+use ir::context::BindgenContext;
+use ir::item::{Item, ItemId};
+use parse::{ClangItemParser, ParseError};
+use regex_set::RegexSet;
use std::borrow::Borrow;
-use std::io::{self, Write};
+use std::collections::HashSet;
use std::fs::OpenOptions;
+use std::io::{self, Write};
use std::path::Path;
-use std::collections::HashSet;
use syntax::ast;
use syntax::codemap::{DUMMY_SP, Span};
-use syntax::print::pprust;
use syntax::print::pp::eof;
+use syntax::print::pprust;
use syntax::ptr::P;
-use ir::context::BindgenContext;
-use ir::item::{Item, ItemId};
-use parse::{ClangItemParser, ParseError};
-use regex_set::RegexSet;
-
/// Configure and generate Rust bindings for a C/C++ header.
///
/// This is the main entry point to the library.
@@ -310,7 +310,7 @@ pub enum LinkType {
/// Use static linking.
Static,
/// The library is an OSX framework.
- Framework
+ Framework,
}
/// Generated Rust bindings.
@@ -325,7 +325,9 @@ impl Bindings {
///
/// Deprecated - use a `Builder` instead
#[deprecated]
- pub fn generate(options: BindgenOptions, span: Option<Span>) -> Result<Bindings, ()> {
+ pub fn generate(options: BindgenOptions,
+ span: Option<Span>)
+ -> Result<Bindings, ()> {
let span = span.unwrap_or(DUMMY_SP);
let mut context = BindgenContext::new(options);
@@ -359,7 +361,11 @@ impl Bindings {
/// Write these bindings as source text to a file.
pub fn write_to_file<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
- let file = try!(OpenOptions::new().write(true).truncate(true).create(true).open(path));
+ let file = try!(OpenOptions::new()
+ .write(true)
+ .truncate(true)
+ .create(true)
+ .open(path));
self.write(Box::new(file))
}
@@ -367,7 +373,8 @@ impl Bindings {
// https://github.com/Manishearth/rust-clippy/issues/740
#[cfg_attr(feature = "clippy", allow(needless_lifetimes))]
pub fn write<'a>(&self, mut writer: Box<Write + 'a>) -> io::Result<()> {
- try!(writer.write("/* automatically generated by rust-bindgen */\n\n".as_bytes()));
+ try!(writer.write("/* automatically generated by rust-bindgen */\n\n"
+ .as_bytes()));
for line in self.raw_lines.iter() {
try!(writer.write(line.as_bytes()));
@@ -400,15 +407,16 @@ fn filter_builtins(ctx: &BindgenContext, cursor: &clang::Cursor) -> bool {
pub fn parse_one(ctx: &mut BindgenContext,
cursor: clang::Cursor,
parent: Option<ItemId>,
- children: &mut Vec<ItemId>) -> clangll::Enum_CXVisitorResult {
+ children: &mut Vec<ItemId>)
+ -> clangll::Enum_CXVisitorResult {
if !filter_builtins(ctx, &cursor) {
- return CXChildVisit_Continue
+ return CXChildVisit_Continue;
}
use clangll::CXChildVisit_Continue;
match Item::parse(cursor, parent, ctx) {
Ok(id) => children.push(id),
- Err(ParseError::Continue) => {},
+ Err(ParseError::Continue) => {}
Err(ParseError::Recurse) => {
cursor.visit(|child, _| parse_one(ctx, *child, parent, children));
}
diff --git a/src/parse.rs b/src/parse.rs
index 1f556643..98cf6b13 100644
--- a/src/parse.rs
+++ b/src/parse.rs
@@ -1,9 +1,9 @@
//! Common traits and types related to parsing our IR from Clang cursors.
use clang;
-use ir::ty::TypeKind;
-use ir::item::ItemId;
use ir::context::BindgenContext;
+use ir::item::ItemId;
+use ir::ty::TypeKind;
/// Not so much an error in the traditional sense, but a control flow message
/// when walking over Clang's AST with a cursor.
@@ -30,12 +30,14 @@ pub enum ParseResult<T> {
/// An intermediate representation "sub-item" (i.e. one of the types contained
/// inside an `ItemKind` variant) that can be parsed from a Clang cursor.
-pub trait ClangSubItemParser : Sized {
+pub trait ClangSubItemParser: Sized {
/// Attempt to parse this type from the given cursor.
///
/// The fact that is a reference guarantees it's held by the context, and
/// allow returning already existing types.
- fn parse(cursor: clang::Cursor, context: &mut BindgenContext) -> Result<ParseResult<Self>, ParseError>;
+ fn parse(cursor: clang::Cursor,
+ context: &mut BindgenContext)
+ -> Result<ParseResult<Self>, ParseError>;
}
/// An intermediate representation item that can be parsed from a Clang cursor.
@@ -43,13 +45,15 @@ pub trait ClangItemParser: Sized {
/// Parse this item from the given Clang cursor.
fn parse(cursor: clang::Cursor,
parent: Option<ItemId>,
- context: &mut BindgenContext) -> Result<ItemId, ParseError>;
+ context: &mut BindgenContext)
+ -> Result<ItemId, ParseError>;
/// Parse this item from the given Clang type.
fn from_ty(ty: &clang::Type,
location: Option<clang::Cursor>,
parent: Option<ItemId>,
- ctx: &mut BindgenContext) -> Result<ItemId, ParseError>;
+ ctx: &mut BindgenContext)
+ -> Result<ItemId, ParseError>;
/// Identical to `from_ty`, but use the given `id` as the `ItemId` for the
/// newly parsed item.
@@ -57,14 +61,16 @@ pub trait ClangItemParser: Sized {
ty: &clang::Type,
location: Option<clang::Cursor>,
parent: Option<ItemId>,
- ctx: &mut BindgenContext) -> Result<ItemId, ParseError>;
+ ctx: &mut BindgenContext)
+ -> Result<ItemId, ParseError>;
/// Parse this item from the given Clang type, or if we haven't resolved all
/// the other items this one depends on, an unresolved reference.
fn from_ty_or_ref(ty: clang::Type,
location: Option<clang::Cursor>,
parent_id: Option<ItemId>,
- context: &mut BindgenContext) -> ItemId;
+ context: &mut BindgenContext)
+ -> ItemId;
/// Identical to `from_ty_or_ref`, but use the given `potential_id` as the
/// `ItemId` for the newly parsed item.
@@ -72,19 +78,30 @@ pub trait ClangItemParser: Sized {
ty: clang::Type,
location: Option<clang::Cursor>,
parent_id: Option<ItemId>,
- context: &mut BindgenContext) -> ItemId;
+ context: &mut BindgenContext)
+ -> ItemId;
/// Create a named template type.
- fn named_type<S>(name: S, default: Option<ItemId>, parent: ItemId,
- context: &mut BindgenContext) -> ItemId
+ fn named_type<S>(name: S,
+ default: Option<ItemId>,
+ parent: ItemId,
+ context: &mut BindgenContext)
+ -> ItemId
where S: Into<String>;
/// Identical to `named_type`, but use `id` as the resulting item's
/// `ItemId`.
- fn named_type_with_id<S>(id: ItemId, name: S, default: Option<ItemId>,
- parent: ItemId, context: &mut BindgenContext) -> ItemId
+ fn named_type_with_id<S>(id: ItemId,
+ name: S,
+ default: Option<ItemId>,
+ parent: ItemId,
+ context: &mut BindgenContext)
+ -> ItemId
where S: Into<String>;
/// Create a builtin type.
- fn builtin_type(kind: TypeKind, is_const: bool, context: &mut BindgenContext) -> ItemId;
+ fn builtin_type(kind: TypeKind,
+ is_const: bool,
+ context: &mut BindgenContext)
+ -> ItemId;
}
diff --git a/src/regex_set.rs b/src/regex_set.rs
index ff899d78..93130590 100644
--- a/src/regex_set.rs
+++ b/src/regex_set.rs
@@ -1,7 +1,7 @@
//! A type that represents the union of a set of regular expressions.
-use std::borrow::Borrow;
use regex::Regex;
+use std::borrow::Borrow;
// Yeah, I'm aware this is sorta crappy, should be cheaper to compile a regex
// ORing all the patterns, I guess...
@@ -9,7 +9,7 @@ use regex::Regex;
/// A dynamic set of regular expressions.
#[derive(Debug)]
pub struct RegexSet {
- items: Vec<Regex>
+ items: Vec<Regex>,
}
impl RegexSet {
@@ -20,7 +20,7 @@ impl RegexSet {
/// Extend this set with every regex in the iterator.
pub fn extend<I>(&mut self, iter: I)
- where I: IntoIterator<Item=String>
+ where I: IntoIterator<Item = String>,
{
for s in iter.into_iter() {
self.insert(&s)
@@ -29,7 +29,7 @@ impl RegexSet {
/// Insert a new regex into this set.
pub fn insert<S>(&mut self, string: &S)
- where S: Borrow<str>
+ where S: Borrow<str>,
{
let s = string.borrow();
match Regex::new(&format!("^{}$", s)) {
@@ -44,7 +44,7 @@ impl RegexSet {
/// Does the given `string` match any of the regexes in this set?
pub fn matches<S>(&self, string: &S) -> bool
- where S: Borrow<str>
+ where S: Borrow<str>,
{
let s = string.borrow();
for r in &self.items {