diff --git a/build.rs b/build.rs index 06cb9e9686..a699f5abbc 100644 --- a/build.rs +++ b/build.rs @@ -16,9 +16,10 @@ mod codegen { println!("cargo:rerun-if-changed=src/codegen/helpers.rs"); println!("cargo:rerun-if-changed=src/codegen/struct_layout.rs"); - let mut dst = - File::create(Path::new(&out_dir).join("host-target.txt")).unwrap(); - dst.write_all(env::var("TARGET").unwrap().as_bytes()).unwrap(); + let mut dst = File::create(Path::new(&out_dir).join("host-target.txt")) + .unwrap(); + dst.write_all(env::var("TARGET").unwrap().as_bytes()) + .unwrap(); } } @@ -32,9 +33,11 @@ mod testgen { pub fn main() { let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap()); - let mut dst = File::create(Path::new(&out_dir).join("tests.rs")).unwrap(); + let mut dst = File::create(Path::new(&out_dir).join("tests.rs")) + .unwrap(); - let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()); + let manifest_dir = + PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()); let headers_dir = manifest_dir.join("tests").join("headers"); let headers = match fs::read_dir(headers_dir) { @@ -51,12 +54,19 @@ mod testgen { for entry in entries { match entry.path().extension().and_then(OsStr::to_str) { Some("h") | Some("hpp") => { - let func = entry.file_name().to_str().unwrap() + let func = entry + .file_name() + .to_str() + .unwrap() .replace(|c| !char::is_alphanumeric(c), "_") .replace("__", "_") .to_lowercase(); - writeln!(dst, "test_header!(header_{}, {:?});", - func, entry.path()).unwrap(); + writeln!( + dst, + "test_header!(header_{}, {:?});", + func, + entry.path() + ).unwrap(); } _ => {} } diff --git a/src/callbacks.rs b/src/callbacks.rs index ef85fdd7ab..30bd3faad5 100644 --- a/src/callbacks.rs +++ b/src/callbacks.rs @@ -8,7 +8,6 @@ use std::panic::UnwindSafe; /// A trait to allow configuring different kinds of types in different /// situations. pub trait ParseCallbacks: fmt::Debug + UnwindSafe { - /// This function will be run on every macro that is identified fn parsed_macro(&self, _name: &str) {} @@ -21,11 +20,12 @@ pub trait ParseCallbacks: fmt::Debug + UnwindSafe { /// This function should return whether, given the a given enum variant /// name, and value, returns whether this enum variant will forcibly be a /// constant. - fn enum_variant_behavior(&self, - _enum_name: Option<&str>, - _variant_name: &str, - _variant_value: EnumVariantValue) - -> Option { + fn enum_variant_behavior( + &self, + _enum_name: Option<&str>, + _variant_name: &str, + _variant_value: EnumVariantValue, + ) -> Option { None } } diff --git a/src/clang.rs b/src/clang.rs index beacb5deda..a0e7fa3d78 100644 --- a/src/clang.rs +++ b/src/clang.rs @@ -24,12 +24,14 @@ pub struct Cursor { 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() + ) } } @@ -213,11 +215,12 @@ impl Cursor { let mut semantic_parent = self.fallible_semantic_parent(); while semantic_parent.is_some() && - (semantic_parent.unwrap().kind() == CXCursor_Namespace || - semantic_parent.unwrap().kind() == CXCursor_NamespaceAlias || - semantic_parent.unwrap().kind() == CXCursor_NamespaceRef) { - semantic_parent = semantic_parent.unwrap() - .fallible_semantic_parent(); + (semantic_parent.unwrap().kind() == CXCursor_Namespace || + semantic_parent.unwrap().kind() == CXCursor_NamespaceAlias || + semantic_parent.unwrap().kind() == CXCursor_NamespaceRef) + { + semantic_parent = + semantic_parent.unwrap().fallible_semantic_parent(); } let tu = self.translation_unit(); @@ -256,8 +259,8 @@ impl Cursor { /// remaining free template arguments? pub fn is_fully_specialized_template(&self) -> bool { self.is_template_specialization() && - self.kind() != CXCursor_ClassTemplatePartialSpecialization && - self.num_template_args().unwrap_or(0) > 0 + self.kind() != CXCursor_ClassTemplatePartialSpecialization && + self.num_template_args().unwrap_or(0) > 0 } /// Is the referent a template specialization that still has remaining free @@ -388,12 +391,15 @@ impl Cursor { /// /// Call the given function on each AST node traversed. pub fn visit(&self, mut visitor: Visitor) - where Visitor: FnMut(Cursor) -> CXChildVisitResult, + where + Visitor: FnMut(Cursor) -> CXChildVisitResult, { unsafe { - clang_visitChildren(self.x, - visit_children::, - mem::transmute(&mut visitor)); + clang_visitChildren( + self.x, + visit_children::, + mem::transmute(&mut visitor), + ); } } @@ -451,7 +457,7 @@ impl Cursor { /// Is the referent an inlined function? pub fn is_inlined_function(&self) -> bool { clang_Cursor_isFunctionInlined::is_loaded() && - unsafe { clang_Cursor_isFunctionInlined(self.x) != 0 } + unsafe { clang_Cursor_isFunctionInlined(self.x) != 0 } } /// Get the width of this cursor's referent bit field, or `None` if the @@ -572,7 +578,7 @@ impl Cursor { /// `mutable`? pub fn is_mutable_field(&self) -> bool { clang_CXXField_isMutable::is_loaded() && - unsafe { clang_CXXField_isMutable(self.x) != 0 } + unsafe { clang_CXXField_isMutable(self.x) != 0 } } /// Get the offset of the field represented by the Cursor. @@ -628,18 +634,21 @@ impl Cursor { /// (including '_') and does not start with a digit. pub fn is_valid_identifier(name: &str) -> bool { let mut chars = name.chars(); - let first_valid = chars.next() + let first_valid = chars + .next() .map(|c| c.is_alphabetic() || c == '_') .unwrap_or(false); first_valid && chars.all(|c| c.is_alphanumeric() || c == '_') } -extern "C" fn visit_children(cur: CXCursor, - _parent: CXCursor, - data: CXClientData) - -> CXChildVisitResult - where Visitor: FnMut(Cursor) -> CXChildVisitResult, +extern "C" fn visit_children( + cur: CXCursor, + _parent: CXCursor, + data: CXClientData, +) -> CXChildVisitResult +where + Visitor: FnMut(Cursor) -> CXChildVisitResult, { let func: &mut Visitor = unsafe { mem::transmute(data) }; let child = Cursor { @@ -679,13 +688,15 @@ impl Eq for Type {} impl fmt::Debug for Type { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - write!(fmt, - "Type({}, kind: {}, cconv: {}, decl: {:?}, canon: {:?})", - self.spelling(), - type_to_str(self.kind()), - self.call_conv(), - self.declaration(), - self.declaration().canonical()) + write!( + fmt, + "Type({}, kind: {}, cconv: {}, decl: {:?}, canon: {:?})", + self.spelling(), + type_to_str(self.kind()), + self.call_conv(), + self.declaration(), + self.declaration().canonical() + ) } } @@ -738,9 +749,10 @@ impl Type { } /// Get the canonical declaration of this type, if it is available. - pub fn canonical_declaration(&self, - location: Option<&Cursor>) - -> Option { + pub fn canonical_declaration( + &self, + location: Option<&Cursor>, + ) -> Option { let mut declaration = self.declaration(); if !declaration.is_valid() { if let Some(location) = location { @@ -833,13 +845,6 @@ impl Type { /// Get the number of template arguments this type has, or `None` if it is /// not some kind of template. pub fn num_template_args(&self) -> Option { - // If an old libclang is loaded, we have no hope of answering this - // question correctly. However, that's no reason to panic when - // generating bindings for simple C headers with an old libclang. - if !clang_Type_getNumTemplateArguments::is_loaded() { - return None - } - let n = unsafe { clang_Type_getNumTemplateArguments(self.x) }; if n >= 0 { Some(n as u32) @@ -964,12 +969,12 @@ impl Type { // nasty... But can happen in . Unfortunately I couldn't // reduce it enough :( self.template_args().map_or(false, |args| args.len() > 0) && - match self.declaration().kind() { - CXCursor_ClassTemplatePartialSpecialization | - CXCursor_TypeAliasTemplateDecl | - CXCursor_TemplateTemplateParameter => false, - _ => true, - } + match self.declaration().kind() { + CXCursor_ClassTemplatePartialSpecialization | + CXCursor_TypeAliasTemplateDecl | + CXCursor_TemplateTemplateParameter => false, + _ => true, + } } /// Is this type an associated template type? Eg `T::Associated` in @@ -992,8 +997,8 @@ impl Type { } self.kind() == CXType_Unexposed && - (hacky_parse_associated_type(self.spelling()) || - hacky_parse_associated_type(self.canonical_type().spelling())) + (hacky_parse_associated_type(self.spelling()) || + hacky_parse_associated_type(self.canonical_type().spelling())) } } @@ -1061,17 +1066,21 @@ 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, + ) } } } @@ -1171,11 +1180,13 @@ impl Iterator for CommentAttributesIterator { Some(CommentAttribute { name: unsafe { cxstring_into_string( - clang_HTMLStartTag_getAttrName(self.x, idx)) + clang_HTMLStartTag_getAttrName(self.x, idx), + ) }, value: unsafe { cxstring_into_string( - clang_HTMLStartTag_getAttrValue(self.x, idx)) + clang_HTMLStartTag_getAttrValue(self.x, idx), + ) }, }) } else { @@ -1271,27 +1282,32 @@ 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: CXTranslationUnit_Flags) - -> Option { + pub fn parse( + ix: &Index, + file: &str, + cmd_args: &[String], + unsaved: &[UnsavedFile], + opts: CXTranslationUnit_Flags, + ) -> Option { let fname = CString::new(file).unwrap(); - let _c_args: Vec = - cmd_args.iter().map(|s| CString::new(s.clone()).unwrap()).collect(); + let _c_args: Vec = 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 = unsaved.iter().map(|f| f.x).collect(); let tu = unsafe { - clang_parseTranslationUnit(ix.x, - fname.as_ptr(), - c_args.as_ptr(), - c_args.len() as c_int, - c_unsaved.as_mut_ptr(), - c_unsaved.len() as c_uint, - opts) + clang_parseTranslationUnit( + ix.x, + fname.as_ptr(), + c_args.as_ptr(), + c_args.len() as c_int, + c_unsaved.as_mut_ptr(), + c_unsaved.len() as c_uint, + opts, + ) }; if tu.is_null() { None @@ -1344,8 +1360,8 @@ impl TranslationUnit { return None; } - let token_array = slice::from_raw_parts(token_ptr, - num_tokens as usize); + let token_array = + slice::from_raw_parts(token_ptr, num_tokens as usize); for &token in token_array.iter() { let kind = clang_getTokenKind(token); let spelling = @@ -1363,9 +1379,10 @@ impl TranslationUnit { /// Convert a set of tokens from clang into `cexpr` tokens, for further /// processing. - pub fn cexpr_tokens(&self, - cursor: &Cursor) - -> Option> { + pub fn cexpr_tokens( + &self, + cursor: &Cursor, + ) -> Option> { use cexpr::token; self.tokens(cursor).map(|tokens| { @@ -1382,7 +1399,7 @@ impl TranslationUnit { CXToken_Comment => return None, _ => { error!("Found unexpected token kind: {:?}", token); - return None + return None; } }; @@ -1464,10 +1481,12 @@ impl UnsavedFile { impl fmt::Debug for UnsavedFile { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - write!(fmt, - "UnsavedFile(name: {:?}, contents: {:?})", - self.name, - self.contents) + write!( + fmt, + "UnsavedFile(name: {:?}, contents: {:?})", + self.name, + self.contents + ) } } @@ -1492,30 +1511,38 @@ pub fn ast_dump(c: &Cursor, depth: isize) -> CXChildVisitResult { fn print_cursor>(depth: isize, prefix: S, c: &Cursor) { let prefix = prefix.as_ref(); - print_indent(depth, - format!(" {}kind = {}", prefix, kind_to_str(c.kind()))); - print_indent(depth, - format!(" {}spelling = \"{}\"", prefix, c.spelling())); + print_indent( + depth, + format!(" {}kind = {}", prefix, kind_to_str(c.kind())), + ); + print_indent( + depth, + format!(" {}spelling = \"{}\"", prefix, c.spelling()), + ); print_indent(depth, format!(" {}location = {}", prefix, c.location())); - print_indent(depth, - format!(" {}is-definition? {}", - prefix, - c.is_definition())); - print_indent(depth, - format!(" {}is-declaration? {}", - prefix, - c.is_declaration())); - print_indent(depth, - format!(" {}is-inlined-function? {}", - prefix, - c.is_inlined_function())); + print_indent( + depth, + format!(" {}is-definition? {}", prefix, c.is_definition()), + ); + print_indent( + depth, + format!(" {}is-declaration? {}", prefix, c.is_declaration()), + ); + print_indent( + depth, + format!( + " {}is-inlined-function? {}", + prefix, + c.is_inlined_function() + ), + ); let templ_kind = c.template_kind(); if templ_kind != CXCursor_NoDeclFound { - print_indent(depth, - format!(" {}template-kind = {}", - prefix, - kind_to_str(templ_kind))); + print_indent( + depth, + format!(" {}template-kind = {}", prefix, kind_to_str(templ_kind)), + ); } if let Some(usr) = c.usr() { print_indent(depth, format!(" {}usr = \"{}\"", prefix, usr)); @@ -1524,67 +1551,75 @@ pub fn ast_dump(c: &Cursor, depth: isize) -> CXChildVisitResult { print_indent(depth, format!(" {}number-of-args = {}", prefix, num)); } if let Some(num) = c.num_template_args() { - print_indent(depth, - format!(" {}number-of-template-args = {}", - prefix, - num)); + print_indent( + depth, + format!(" {}number-of-template-args = {}", prefix, num), + ); } if let Some(width) = c.bit_width() { print_indent(depth, format!(" {}bit-width = {}", prefix, width)); } if let Some(ty) = c.enum_type() { - print_indent(depth, - format!(" {}enum-type = {}", - prefix, - type_to_str(ty.kind()))); + print_indent( + depth, + format!(" {}enum-type = {}", prefix, type_to_str(ty.kind())), + ); } if let Some(val) = c.enum_val_signed() { print_indent(depth, format!(" {}enum-val = {}", prefix, val)); } if let Some(ty) = c.typedef_type() { - print_indent(depth, - format!(" {}typedef-type = {}", - prefix, - type_to_str(ty.kind()))); + print_indent( + depth, + format!(" {}typedef-type = {}", prefix, type_to_str(ty.kind())), + ); } if let Some(ty) = c.ret_type() { - print_indent(depth, - format!(" {}ret-type = {}", - prefix, - type_to_str(ty.kind()))); + print_indent( + depth, + format!(" {}ret-type = {}", prefix, type_to_str(ty.kind())), + ); } if let Some(refd) = c.referenced() { if refd != *c { println!(""); - print_cursor(depth, - String::from(prefix) + "referenced.", - &refd); + print_cursor( + depth, + String::from(prefix) + "referenced.", + &refd, + ); } } let canonical = c.canonical(); if canonical != *c { println!(""); - print_cursor(depth, - String::from(prefix) + "canonical.", - &canonical); + print_cursor( + depth, + String::from(prefix) + "canonical.", + &canonical, + ); } if let Some(specialized) = c.specialized() { if specialized != *c { println!(""); - print_cursor(depth, - String::from(prefix) + "specialized.", - &specialized); + print_cursor( + depth, + String::from(prefix) + "specialized.", + &specialized, + ); } } if let Some(parent) = c.fallible_semantic_parent() { println!(""); - print_cursor(depth, - String::from(prefix) + "semantic-parent.", - &parent); + print_cursor( + depth, + String::from(prefix) + "semantic-parent.", + &parent, + ); } } @@ -1599,27 +1634,32 @@ pub fn ast_dump(c: &Cursor, depth: isize) -> CXChildVisitResult { print_indent(depth, format!(" {}cconv = {}", prefix, ty.call_conv())); - print_indent(depth, - format!(" {}spelling = \"{}\"", prefix, ty.spelling())); - - let num_template_args = if clang_Type_getNumTemplateArguments::is_loaded() { - unsafe { clang_Type_getNumTemplateArguments(ty.x) } - } else { - -1 - }; + print_indent( + depth, + format!(" {}spelling = \"{}\"", prefix, ty.spelling()), + ); + let num_template_args = + unsafe { clang_Type_getNumTemplateArguments(ty.x) }; if num_template_args >= 0 { - print_indent(depth, - format!(" {}number-of-template-args = {}", - prefix, - num_template_args)); + print_indent( + depth, + format!( + " {}number-of-template-args = {}", + prefix, + num_template_args + ), + ); } - if let Some(num) = ty.num_elements() { - print_indent(depth, - format!(" {}number-of-elements = {}", prefix, num)); + print_indent( + depth, + format!(" {}number-of-elements = {}", prefix, num), + ); } - print_indent(depth, - format!(" {}is-variadic? {}", prefix, ty.is_variadic())); + print_indent( + depth, + format!(" {}is-variadic? {}", prefix, ty.is_variadic()), + ); let canonical = ty.canonical_type(); if canonical != *ty { @@ -1711,7 +1751,8 @@ impl EvalResult { // `CXType_Unexposed` from evaluation. let mut found_cant_eval = false; cursor.visit(|c| if c.kind() == CXCursor_TypeRef && - c.cur_type().kind() == CXType_Unexposed { + c.cur_type().kind() == CXType_Unexposed + { found_cant_eval = true; CXChildVisit_Break } else { diff --git a/src/codegen/derive_debug.rs b/src/codegen/derive_debug.rs index 2fd9cd6558..066af33913 100644 --- a/src/codegen/derive_debug.rs +++ b/src/codegen/derive_debug.rs @@ -2,7 +2,7 @@ use ir::comp::{BitfieldUnit, CompKind, Field, FieldData, FieldMethods}; use ir::context::BindgenContext; use ir::derive::CanTriviallyDeriveDebug; use ir::item::{HasTypeParamInArray, IsOpaque, Item, ItemCanonicalName}; -use ir::ty::{TypeKind, RUST_DERIVE_IN_ARRAY_LIMIT}; +use ir::ty::{RUST_DERIVE_IN_ARRAY_LIMIT, TypeKind}; use syntax::ast; use syntax::codemap::DUMMY_SP; use syntax::parse::token::Token; @@ -171,17 +171,16 @@ impl<'a> ImplDebug<'a> for Item { } // The generic is not required to implement Debug, so we can not debug print that type - TypeKind::Named => { + TypeKind::TypeParam => { Some((format!("{}: Non-debuggable generic", name), vec![])) } TypeKind::Array(_, len) => { // Generics are not required to implement Debug if self.has_type_param_in_array(ctx) { - Some(( - format!("{}: Array with length {}", name, len), - vec![], - )) + Some( + (format!("{}: Array with length {}", name, len), vec![]), + ) } else if len < RUST_DERIVE_IN_ARRAY_LIMIT { // The simple case debug_print(ctx, name, name_ident) @@ -211,8 +210,7 @@ impl<'a> ImplDebug<'a> for Item { let inner_type = ctx.resolve_type(inner).canonical_type(ctx); match *inner_type.kind() { TypeKind::Function(ref sig) - if !sig.can_trivially_derive_debug() => - { + if !sig.can_trivially_derive_debug() => { Some((format!("{}: FunctionPointer", name), vec![])) } _ => debug_print(ctx, name, name_ident), diff --git a/src/codegen/helpers.rs b/src/codegen/helpers.rs index 4a64f79949..2bc3ad4498 100644 --- a/src/codegen/helpers.rs +++ b/src/codegen/helpers.rs @@ -11,19 +11,35 @@ pub mod attributes { use syntax::ast; pub fn allow(which_ones: &[&str]) -> ast::Attribute { - aster::AstBuilder::new().attr().list("allow").words(which_ones).build() + aster::AstBuilder::new() + .attr() + .list("allow") + .words(which_ones) + .build() } pub fn repr(which: &str) -> ast::Attribute { - aster::AstBuilder::new().attr().list("repr").words(&[which]).build() + aster::AstBuilder::new() + .attr() + .list("repr") + .words(&[which]) + .build() } pub fn repr_list(which_ones: &[&str]) -> ast::Attribute { - aster::AstBuilder::new().attr().list("repr").words(which_ones).build() + aster::AstBuilder::new() + .attr() + .list("repr") + .words(which_ones) + .build() } pub fn derives(which_ones: &[&str]) -> ast::Attribute { - aster::AstBuilder::new().attr().list("derive").words(which_ones).build() + aster::AstBuilder::new() + .attr() + .list("derive") + .words(which_ones) + .build() } pub fn inline() -> ast::Attribute { @@ -35,7 +51,10 @@ pub mod attributes { } pub fn link_name(name: &str) -> ast::Attribute { - aster::AstBuilder::new().attr().name_value("link_name").str(name) + aster::AstBuilder::new() + .attr() + .name_value("link_name") + .str(name) } } @@ -97,9 +116,10 @@ pub mod ast_ty { } } - pub fn float_kind_rust_type(ctx: &BindgenContext, - fk: FloatKind) - -> P { + pub fn float_kind_rust_type( + ctx: &BindgenContext, + fk: FloatKind, + ) -> P { // TODO: we probably should just take the type layout into // account? // @@ -153,14 +173,17 @@ pub mod ast_ty { pub fn cstr_expr(mut string: String) -> P { string.push('\0'); - aster::AstBuilder::new() - .expr() - .build_lit(aster::AstBuilder::new().lit().byte_str(string)) + aster::AstBuilder::new().expr().build_lit( + aster::AstBuilder::new() + .lit() + .byte_str(string), + ) } - pub fn float_expr(ctx: &BindgenContext, - f: f64) - -> Result, ()> { + pub fn float_expr( + ctx: &BindgenContext, + f: f64, + ) -> Result, ()> { use aster::symbol::ToSymbol; if f.is_finite() { @@ -171,8 +194,9 @@ pub mod ast_ty { string.push('.'); } - let kind = ast::LitKind::FloatUnsuffixed(string.as_str().to_symbol()); - return Ok(aster::AstBuilder::new().expr().lit().build_lit(kind)) + let kind = + ast::LitKind::FloatUnsuffixed(string.as_str().to_symbol()); + return Ok(aster::AstBuilder::new().expr().lit().build_lit(kind)); } let prefix = ctx.trait_prefix(); @@ -192,13 +216,15 @@ pub mod ast_ty { return Err(()); } - pub fn arguments_from_signature(signature: &FunctionSig, - ctx: &BindgenContext) - -> Vec> { + pub fn arguments_from_signature( + signature: &FunctionSig, + ctx: &BindgenContext, + ) -> Vec> { // 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; - signature.argument_types() + signature + .argument_types() .iter() .map(|&(ref name, _ty)| { let arg_name = match *name { diff --git a/src/codegen/mod.rs b/src/codegen/mod.rs index 1e4a5d48fc..2ab507da6e 100644 --- a/src/codegen/mod.rs +++ b/src/codegen/mod.rs @@ -3,7 +3,7 @@ mod error; mod helpers; pub mod struct_layout; -use self::helpers::{attributes, BlobTyBuilder}; +use self::helpers::{BlobTyBuilder, attributes}; use self::struct_layout::StructLayoutTracker; use aster; @@ -14,7 +14,8 @@ use ir::comment; use ir::comp::{Base, Bitfield, BitfieldUnit, CompInfo, CompKind, Field, FieldData, FieldMethods, Method, MethodKind}; use ir::context::{BindgenContext, ItemId}; -use ir::derive::{CanDeriveCopy, CanDeriveDebug, CanDeriveDefault, CanDeriveHash, CanDerivePartialEq}; +use ir::derive::{CanDeriveCopy, CanDeriveDebug, CanDeriveDefault, + CanDeriveHash, CanDerivePartialEq}; use ir::dot; use ir::enum_ty::{Enum, EnumVariant, EnumVariantValue}; use ir::function::{Abi, Function, FunctionSig}; @@ -37,7 +38,7 @@ use std::mem; use std::ops; use syntax::abi; use syntax::ast; -use syntax::codemap::{respan, Span, DUMMY_SP}; +use syntax::codemap::{DUMMY_SP, Span, respan}; use syntax::ptr::P; // Name of type defined in constified enum module @@ -175,8 +176,7 @@ impl<'a> CodegenResult<'a> { /// counter internally so the next time we ask for the overload for this /// name, we get the incremented value, and so on. fn overload_number(&mut self, name: &str) -> u32 { - let counter = - self.overload_counters.entry(name.into()).or_insert(0); + let counter = self.overload_counters.entry(name.into()).or_insert(0); let number = *counter; *counter += 1; number @@ -480,12 +480,16 @@ impl CodeGenerator for Var { let ty = quote_ty!(ctx.ext_cx(), [u8; $len]); match String::from_utf8(bytes.clone()) { - Ok(string) => const_item - .build(helpers::ast_ty::cstr_expr(string)) - .build(quote_ty!(ctx.ext_cx(), &'static $ty)), - Err(..) => const_item - .build(helpers::ast_ty::byte_array_expr(bytes)) - .build(ty), + Ok(string) => { + const_item + .build(helpers::ast_ty::cstr_expr(string)) + .build(quote_ty!(ctx.ext_cx(), &'static $ty)) + } + Err(..) => { + const_item + .build(helpers::ast_ty::byte_array_expr(bytes)) + .build(ty) + } } } VarType::Float(f) => { @@ -494,9 +498,11 @@ impl CodeGenerator for Var { Err(..) => return, } } - VarType::Char(c) => const_item - .build(aster::AstBuilder::new().expr().lit().byte(c)) - .build(ty), + VarType::Char(c) => { + const_item + .build(aster::AstBuilder::new().expr().lit().byte(c)) + .build(ty) + } }; result.push(item); @@ -550,7 +556,7 @@ impl CodeGenerator for Type { TypeKind::Function(..) | TypeKind::ResolvedTypeRef(..) | TypeKind::Opaque | - TypeKind::Named => { + TypeKind::TypeParam => { // These items don't need code generation, they only need to be // converted to rust types in fields, arguments, and such. return; @@ -559,7 +565,8 @@ impl CodeGenerator for Type { inst.codegen(ctx, result, item) } TypeKind::Comp(ref ci) => ci.codegen(ctx, result, item), - TypeKind::TemplateAlias(inner, _) | TypeKind::Alias(inner) => { + TypeKind::TemplateAlias(inner, _) | + TypeKind::Alias(inner) => { let inner_item = ctx.resolve_item(inner); let name = item.canonical_name(ctx); @@ -606,7 +613,7 @@ impl CodeGenerator for Type { // code. let inner_canon_type = inner_item.expect_type().canonical_type(ctx); - if inner_canon_type.is_invalid_named_type() { + if inner_canon_type.is_invalid_type_param() { warn!( "Item contained invalid named type, skipping: \ {:?}, {:?}", @@ -627,18 +634,19 @@ impl CodeGenerator for Type { // We prefer using `pub use` over `pub type` because of: // https://github.com/rust-lang/rust/issues/26264 let simple_enum_path = match inner_rust_type.node { - ast::TyKind::Path(None, ref p) => if used_template_params - .is_none() && - inner_item - .expect_type() - .canonical_type(ctx) - .is_enum() && - p.segments.iter().all(|p| p.parameters.is_none()) - { - Some(p.clone()) - } else { - None - }, + ast::TyKind::Path(None, ref p) => { + if used_template_params.is_none() && + inner_item + .expect_type() + .canonical_type(ctx) + .is_enum() && + p.segments.iter().all(|p| p.parameters.is_none()) + { + Some(p.clone()) + } else { + None + } + } _ => None, }; @@ -657,11 +665,11 @@ impl CodeGenerator for Type { let mut generics = typedef.type_(rust_name).generics(); if let Some(ref params) = used_template_params { for template_param in params { - if let Some(id) = - template_param.as_template_param(ctx, &()) + if let Some(id) = template_param + .as_template_param(ctx, &()) { let template_param = ctx.resolve_type(id); - if template_param.is_invalid_named_type() { + if template_param.is_invalid_type_param() { warn!( "Item contained invalid template \ parameter: {:?}", @@ -982,9 +990,10 @@ impl<'a> FieldCodegen<'a> for FieldData { } } - let field_name = self.name() - .map(|name| ctx.rust_mangle(name).into_owned()) - .unwrap_or_else(|| anon_field_names.next().unwrap()); + let field_name = + self.name() + .map(|name| ctx.rust_mangle(name).into_owned()) + .unwrap_or_else(|| anon_field_names.next().unwrap()); if !parent.is_union() { if let Some(padding_field) = @@ -994,9 +1003,9 @@ impl<'a> FieldCodegen<'a> for FieldData { } } - let is_private = self.annotations() - .private_fields() - .unwrap_or(fields_should_be_private); + let is_private = self.annotations().private_fields().unwrap_or( + fields_should_be_private, + ); let accessor_kind = self.annotations().accessor_kind().unwrap_or(accessor_kind); @@ -1023,7 +1032,8 @@ impl<'a> FieldCodegen<'a> for FieldData { let accessor_methods_impl = match accessor_kind { FieldAccessorKind::None => unreachable!(), - FieldAccessorKind::Regular => quote_item!(ctx.ext_cx(), + FieldAccessorKind::Regular => { + quote_item!(ctx.ext_cx(), impl X { #[inline] pub fn $getter_name(&self) -> &$ty { @@ -1035,8 +1045,10 @@ impl<'a> FieldCodegen<'a> for FieldData { &mut self.$field_name } } - ), - FieldAccessorKind::Unsafe => quote_item!(ctx.ext_cx(), + ) + } + FieldAccessorKind::Unsafe => { + quote_item!(ctx.ext_cx(), impl X { #[inline] pub unsafe fn $getter_name(&self) -> &$ty { @@ -1049,15 +1061,18 @@ impl<'a> FieldCodegen<'a> for FieldData { &mut self.$field_name } } - ), - FieldAccessorKind::Immutable => quote_item!(ctx.ext_cx(), + ) + } + FieldAccessorKind::Immutable => { + quote_item!(ctx.ext_cx(), impl X { #[inline] pub fn $getter_name(&self) -> &$ty { &self.$field_name } } - ), + ) + } }; match accessor_methods_impl.unwrap().node { @@ -1137,9 +1152,9 @@ impl Bitfield { let bitfield_ty_item = ctx.resolve_item(self.ty()); let bitfield_ty = bitfield_ty_item.expect_type(); - let bitfield_ty_layout = bitfield_ty - .layout(ctx) - .expect("Bitfield without layout? Gah!"); + let bitfield_ty_layout = bitfield_ty.layout(ctx).expect( + "Bitfield without layout? Gah!", + ); let bitfield_int_ty = BlobTyBuilder::new(bitfield_ty_layout).build(); let bitfield_ty = bitfield_ty.to_rust_ty_or_opaque(ctx, bitfield_ty_item); @@ -1264,12 +1279,14 @@ fn parent_has_method( parent.methods().iter().any(|method| { let method_name = match *ctx.resolve_item(method.signature()).kind() { ItemKind::Function(ref func) => func.name(), - ref otherwise => panic!( - "a method's signature should always be a \ + ref otherwise => { + panic!( + "a method's signature should always be a \ item of kind ItemKind::Function, found: \ {:?}", - otherwise - ), + otherwise + ) + } }; method_name == name || ctx.rust_mangle(&method_name) == name @@ -1335,9 +1352,9 @@ impl<'a> FieldCodegen<'a> for Bitfield { let bitfield_ty_item = ctx.resolve_item(self.ty()); let bitfield_ty = bitfield_ty_item.expect_type(); - let bitfield_ty_layout = bitfield_ty - .layout(ctx) - .expect("Bitfield without layout? Gah!"); + let bitfield_ty_layout = bitfield_ty.layout(ctx).expect( + "Bitfield without layout? Gah!", + ); let bitfield_int_ty = BlobTyBuilder::new(bitfield_ty_layout).build(); let bitfield_ty = @@ -1466,8 +1483,8 @@ impl CodeGenerator for CompInfo { if item.can_derive_debug(ctx) { derives.push("Debug"); } else { - needs_debug_impl = - ctx.options().derive_debug && ctx.options().impl_debug + needs_debug_impl = ctx.options().derive_debug && + ctx.options().impl_debug } if item.can_derive_default(ctx) { @@ -1619,10 +1636,9 @@ impl CodeGenerator for CompInfo { if is_union { let layout = layout.expect("Unable to get layout information?"); let ty = BlobTyBuilder::new(layout).build(); - + let field = if self.can_be_rust_union(ctx) { - StructFieldBuilder::named("_bindgen_union_align") - .build_ty(ty) + StructFieldBuilder::named("_bindgen_union_align").build_ty(ty) } else { struct_layout.saw_union(layout); @@ -1784,8 +1800,8 @@ impl CodeGenerator for CompInfo { .count() > 1; - let should_skip_field_offset_checks = - is_opaque || too_many_base_vtables; + let should_skip_field_offset_checks = is_opaque || + too_many_base_vtables; let check_field_offset = if should_skip_field_offset_checks { @@ -2000,9 +2016,8 @@ impl MethodCodegen for Method { MethodKind::Constructor => cc.constructors, MethodKind::Destructor => cc.destructors, MethodKind::VirtualDestructor => cc.destructors, - MethodKind::Static | MethodKind::Normal | MethodKind::Virtual => { - cc.methods - } + MethodKind::Static | MethodKind::Normal | + MethodKind::Virtual => cc.methods, } }); @@ -2044,8 +2059,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() && !self.is_constructor() { let mutability = if self.is_const() { ast::Mutability::Immutable @@ -2296,9 +2311,9 @@ impl<'a> EnumBuilder<'a> { .. } => { // Variant type - let inside_module_type = aster::AstBuilder::new() - .ty() - .id(CONSTIFIED_ENUM_MODULE_REPR_NAME); + let inside_module_type = aster::AstBuilder::new().ty().id( + CONSTIFIED_ENUM_MODULE_REPR_NAME, + ); let constant = aster::AstBuilder::new() .item() @@ -2425,10 +2440,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 \ @@ -2466,9 +2483,9 @@ impl CodeGenerator for Enum { let is_bitfield = { ctx.options().bitfield_enums.matches(&name) || (enum_ty.name().is_none() && - self.variants().iter().any( - |v| ctx.options().bitfield_enums.matches(&v.name()), - )) + self.variants().iter().any(|v| { + ctx.options().bitfield_enums.matches(&v.name()) + })) }; let is_constified_enum_module = @@ -2478,9 +2495,9 @@ impl CodeGenerator for Enum { is_constified_enum_module || ctx.options().constified_enums.matches(&name) || (enum_ty.name().is_none() && - self.variants().iter().any( - |v| ctx.options().constified_enums.matches(&v.name()), - )) + self.variants().iter().any(|v| { + ctx.options().constified_enums.matches(&v.name()) + })) }; let is_rust_enum = !is_bitfield && !is_constified_enum; @@ -2502,9 +2519,10 @@ impl CodeGenerator for Enum { } if !is_constified_enum { - 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); } @@ -2544,9 +2562,10 @@ impl CodeGenerator for Enum { result.push(constant); } - let repr = self.repr() - .and_then(|repr| repr.try_to_rust_ty_or_opaque(ctx, &()).ok()) - .unwrap_or_else(|| helpers::ast_ty::raw_type(ctx, repr_name)); + let repr = + self.repr() + .and_then(|repr| repr.try_to_rust_ty_or_opaque(ctx, &()).ok()) + .unwrap_or_else(|| helpers::ast_ty::raw_type(ctx, repr_name)); let mut builder = EnumBuilder::new( builder, @@ -2585,8 +2604,9 @@ impl CodeGenerator for Enum { let mut constified_variants = VecDeque::new(); let mut iter = self.variants().iter().peekable(); - while let Some(variant) = - iter.next().or_else(|| constified_variants.pop_front()) + while let Some(variant) = iter.next().or_else(|| { + constified_variants.pop_front() + }) { if variant.hidden() { continue; @@ -2598,38 +2618,41 @@ impl CodeGenerator for Enum { } match seen_values.entry(variant.val()) { - Entry::Occupied(ref entry) => if is_rust_enum { - let variant_name = ctx.rust_mangle(variant.name()); - let mangled_name = if is_toplevel || - enum_ty.name().is_some() - { - variant_name - } else { - let parent_name = - parent_canonical_name.as_ref().unwrap(); - - Cow::Owned(format!("{}_{}", parent_name, variant_name)) - }; + Entry::Occupied(ref entry) => { + if is_rust_enum { + let variant_name = ctx.rust_mangle(variant.name()); + let mangled_name = + if is_toplevel || enum_ty.name().is_some() { + variant_name + } else { + let parent_name = + parent_canonical_name.as_ref().unwrap(); + + Cow::Owned( + format!("{}_{}", parent_name, variant_name), + ) + }; - let existing_variant_name = entry.get(); - add_constant( - ctx, - enum_ty, - &name, - &*mangled_name, - existing_variant_name, - enum_rust_ty.clone(), - result, - ); - } else { - builder = builder.with_variant( - ctx, - variant, - constant_mangling_prefix, - enum_rust_ty.clone(), - result, - ); - }, + let existing_variant_name = entry.get(); + add_constant( + ctx, + enum_ty, + &name, + &*mangled_name, + existing_variant_name, + enum_rust_ty.clone(), + result, + ); + } else { + builder = builder.with_variant( + ctx, + variant, + constant_mangling_prefix, + enum_rust_ty.clone(), + result, + ); + } + } Entry::Vacant(entry) => { builder = builder.with_variant( ctx, @@ -2700,8 +2723,9 @@ trait TryToOpaque { ctx: &BindgenContext, extra: &Self::Extra, ) -> error::Result> { - self.try_get_layout(ctx, extra) - .map(|layout| BlobTyBuilder::new(layout).build()) + self.try_get_layout(ctx, extra).map(|layout| { + BlobTyBuilder::new(layout).build() + }) } } @@ -2717,8 +2741,9 @@ trait TryToOpaque { /// leverage the blanket impl for this trait. trait ToOpaque: TryToOpaque { fn get_layout(&self, ctx: &BindgenContext, extra: &Self::Extra) -> Layout { - self.try_get_layout(ctx, extra) - .unwrap_or_else(|_| Layout::for_size(1)) + self.try_get_layout(ctx, extra).unwrap_or_else( + |_| Layout::for_size(1), + ) } fn to_opaque( @@ -2771,7 +2796,8 @@ trait TryToRustTyOrOpaque: TryToRustTy + TryToOpaque { impl TryToRustTyOrOpaque for T where - T: TryToRustTy + TryToOpaque, + T: TryToRustTy + + TryToOpaque, { type Extra = E; @@ -2781,7 +2807,9 @@ where extra: &E, ) -> error::Result> { self.try_to_rust_ty(ctx, extra).or_else( - |_| if let Ok(layout) = self.try_get_layout(ctx, extra) { + |_| if let Ok(layout) = + self.try_get_layout(ctx, extra) + { Ok(BlobTyBuilder::new(layout).build()) } else { Err(error::Error::NoLayoutForOpaqueBlob) @@ -2828,8 +2856,9 @@ where ctx: &BindgenContext, extra: &E, ) -> P { - self.try_to_rust_ty(ctx, extra) - .unwrap_or_else(|_| self.to_opaque(ctx, extra)) + self.try_to_rust_ty(ctx, extra).unwrap_or_else(|_| { + self.to_opaque(ctx, extra) + }) } } @@ -2982,7 +3011,8 @@ impl TryToRustTy for Type { inst.try_to_rust_ty(ctx, item) } TypeKind::ResolvedTypeRef(inner) => inner.try_to_rust_ty(ctx, &()), - TypeKind::TemplateAlias(inner, _) | TypeKind::Alias(inner) => { + TypeKind::TemplateAlias(inner, _) | + TypeKind::Alias(inner) => { let template_params = item.used_template_params(ctx) .unwrap_or(vec![]) .into_iter() @@ -2992,8 +3022,11 @@ impl TryToRustTy for Type { let spelling = self.name().expect("Unnamed alias?"); if item.is_opaque(ctx, &()) && !template_params.is_empty() { self.try_to_opaque(ctx, item) - } else if let Some(ty) = - utils::type_from_named(ctx, spelling, inner) + } else if let Some(ty) = utils::type_from_named( + ctx, + spelling, + inner, + ) { Ok(ty) } else { @@ -3020,7 +3053,8 @@ impl TryToRustTy for Type { ctx.span(), )) } - TypeKind::Pointer(inner) | TypeKind::Reference(inner) => { + TypeKind::Pointer(inner) | + TypeKind::Reference(inner) => { let inner = ctx.resolve_item(inner); let inner_ty = inner.expect_type(); @@ -3034,12 +3068,12 @@ impl TryToRustTy for Type { if inner_ty.canonical_type(ctx).is_function() { Ok(ty) } else { - let is_const = - self.is_const() || inner.expect_type().is_const(); + let is_const = self.is_const() || + inner.expect_type().is_const(); Ok(ty.to_ptr(is_const, ctx.span())) } } - TypeKind::Named => { + TypeKind::TypeParam => { let name = item.canonical_name(ctx); let ident = ctx.rust_ident(&name); Ok(quote_ty!(ctx.ext_cx(), $ident)) @@ -3047,9 +3081,8 @@ impl TryToRustTy for Type { TypeKind::ObjCSel => { Ok(quote_ty!(ctx.ext_cx(), objc::runtime::Sel)) } - TypeKind::ObjCId | TypeKind::ObjCInterface(..) => { - Ok(quote_ty!(ctx.ext_cx(), id)) - } + TypeKind::ObjCId | + TypeKind::ObjCInterface(..) => Ok(quote_ty!(ctx.ext_cx(), id)), ref u @ TypeKind::UnresolvedTypeRef(..) => { unreachable!("Should have been resolved after parsing {:?}!", u) } @@ -3065,9 +3098,9 @@ impl TryToOpaque for TemplateInstantiation { ctx: &BindgenContext, item: &Item, ) -> error::Result { - item.expect_type() - .layout(ctx) - .ok_or(error::Error::NoLayoutForOpaqueBlob) + item.expect_type().layout(ctx).ok_or( + error::Error::NoLayoutForOpaqueBlob, + ) } } @@ -3390,8 +3423,12 @@ impl CodeGenerator for ObjCInterface { trait_items.push(trait_item) } - let instance_method_names: Vec<_> = - self.methods().iter().map({ |m| m.rust_name() }).collect(); + let instance_method_names: Vec<_> = self.methods() + .iter() + .map({ + |m| m.rust_name() + }) + .collect(); for class_method in self.class_methods() { @@ -3463,7 +3500,7 @@ pub fn codegen(context: &mut BindgenContext) -> Vec> { } mod utils { - use super::{error, ToRustTyOrOpaque, TryToRustTy}; + use super::{ToRustTyOrOpaque, TryToRustTy, error}; use aster; use ir::context::{BindgenContext, ItemId}; use ir::function::FunctionSig; @@ -3570,8 +3607,7 @@ mod utils { fn hash(&self, _state: &mut H) { } } - ) - .unwrap(); + ).unwrap(); let union_field_partialeq_impl = quote_item!(&ctx.ext_cx(), impl ::$prefix::cmp::PartialEq for __BindgenUnionField { @@ -3579,8 +3615,7 @@ mod utils { true } } - ) - .unwrap(); + ).unwrap(); let items = vec![union_field_decl, union_field_impl, @@ -3767,9 +3802,9 @@ mod utils { _ => panic!("How?"), }; - let decl_ty = signature - .try_to_rust_ty(ctx, sig) - .expect("function signature to Rust type conversion is infallible"); + let decl_ty = signature.try_to_rust_ty(ctx, sig).expect( + "function signature to Rust type conversion is infallible", + ); match decl_ty.unwrap().node { ast::TyKind::BareFn(bare_fn) => bare_fn.unwrap().decl, _ => panic!("How did this happen exactly?"), diff --git a/src/codegen/struct_layout.rs b/src/codegen/struct_layout.rs index 2ba39badcc..cd2d62f4a4 100644 --- a/src/codegen/struct_layout.rs +++ b/src/codegen/struct_layout.rs @@ -81,7 +81,11 @@ fn test_bytes_from_bits_pow2() { } impl<'a, 'ctx> StructLayoutTracker<'a, 'ctx> { - pub fn new(ctx: &'a BindgenContext<'ctx>, comp: &'a CompInfo, name: &'a str) -> Self { + pub fn new( + ctx: &'a BindgenContext<'ctx>, + comp: &'a CompInfo, + name: &'a str, + ) -> Self { StructLayoutTracker { name: name, ctx: ctx, @@ -121,9 +125,11 @@ impl<'a, 'ctx> StructLayoutTracker<'a, 'ctx> { self.latest_offset += layout.size; - debug!("Offset: : {} -> {}", - self.latest_offset - layout.size, - self.latest_offset); + debug!( + "Offset: : {} -> {}", + self.latest_offset - layout.size, + self.latest_offset + ); self.latest_field_layout = Some(layout); self.last_field_was_bitfield = true; @@ -143,30 +149,33 @@ impl<'a, 'ctx> StructLayoutTracker<'a, 'ctx> { /// Add a padding field if necessary for a given new field _before_ adding /// that field. - pub fn pad_field(&mut self, - field_name: &str, - field_ty: &Type, - field_offset: Option) - -> Option { + pub fn pad_field( + &mut self, + field_name: &str, + field_ty: &Type, + field_offset: Option, + ) -> Option { let mut field_layout = match field_ty.layout(self.ctx) { Some(l) => l, None => return None, }; if let TypeKind::Array(inner, len) = - *field_ty.canonical_type(self.ctx).kind() { + *field_ty.canonical_type(self.ctx).kind() + { // FIXME(emilio): As an _ultra_ hack, we correct the layout returned // by arrays of structs that have a bigger alignment than what we // can support. // // This means that the structs in the array are super-unsafe to // access, since they won't be properly aligned, but *shrug*. - if let Some(layout) = self.ctx - .resolve_type(inner) - .layout(self.ctx) { + if let Some(layout) = self.ctx.resolve_type(inner).layout( + self.ctx, + ) + { if layout.align > mem::size_of::<*mut ()>() { field_layout.size = align_to(layout.size, layout.align) * - len; + len; field_layout.align = mem::size_of::<*mut ()>(); } } @@ -187,25 +196,30 @@ impl<'a, 'ctx> StructLayoutTracker<'a, 'ctx> { // Otherwise the padding is useless. let need_padding = padding_bytes >= field_layout.align || - field_layout.align > mem::size_of::<*mut ()>(); + field_layout.align > mem::size_of::<*mut ()>(); self.latest_offset += padding_bytes; - debug!("Offset: : {} -> {}", - self.latest_offset - padding_bytes, - self.latest_offset); - - debug!("align field {} to {}/{} with {} padding bytes {:?}", - field_name, - self.latest_offset, - field_offset.unwrap_or(0) / 8, - padding_bytes, - field_layout); + debug!( + "Offset: : {} -> {}", + self.latest_offset - padding_bytes, + self.latest_offset + ); + + debug!( + "align field {} to {}/{} with {} padding bytes {:?}", + field_name, + self.latest_offset, + field_offset.unwrap_or(0) / 8, + padding_bytes, + field_layout + ); if need_padding && padding_bytes != 0 { - Some(Layout::new(padding_bytes, - cmp::min(field_layout.align, - mem::size_of::<*mut ()>()))) + Some(Layout::new( + padding_bytes, + cmp::min(field_layout.align, mem::size_of::<*mut ()>()), + )) } else { None } @@ -213,25 +227,33 @@ impl<'a, 'ctx> StructLayoutTracker<'a, 'ctx> { self.latest_offset += field_layout.size; self.latest_field_layout = Some(field_layout); - self.max_field_align = cmp::max(self.max_field_align, - field_layout.align); + self.max_field_align = + cmp::max(self.max_field_align, field_layout.align); self.last_field_was_bitfield = false; - debug!("Offset: {}: {} -> {}", - field_name, - self.latest_offset - field_layout.size, - self.latest_offset); + debug!( + "Offset: {}: {} -> {}", + field_name, + self.latest_offset - field_layout.size, + self.latest_offset + ); padding_layout.map(|layout| self.padding_field(layout)) } pub fn pad_struct(&mut self, layout: Layout) -> Option { - debug!("pad_struct:\n\tself = {:#?}\n\tlayout = {:#?}", self, layout); + debug!( + "pad_struct:\n\tself = {:#?}\n\tlayout = {:#?}", + self, + layout + ); if layout.size < self.latest_offset { - error!("Calculated wrong layout for {}, too more {} bytes", - self.name, - self.latest_offset - layout.size); + error!( + "Calculated wrong layout for {}, too more {} bytes", + self.name, + self.latest_offset - layout.size + ); return None; } @@ -244,14 +266,17 @@ impl<'a, 'ctx> StructLayoutTracker<'a, 'ctx> { // regardless, because bitfields don't respect alignment as strictly as // other fields. if padding_bytes > 0 && - (padding_bytes >= layout.align || - (self.last_field_was_bitfield && - padding_bytes >= self.latest_field_layout.unwrap().align) || - layout.align > mem::size_of::<*mut ()>()) { + (padding_bytes >= layout.align || + (self.last_field_was_bitfield && + padding_bytes >= + self.latest_field_layout.unwrap().align) || + layout.align > mem::size_of::<*mut ()>()) + { let layout = if self.comp.packed() { Layout::new(padding_bytes, 1) } else if self.last_field_was_bitfield || - layout.align > mem::size_of::<*mut ()>() { + layout.align > mem::size_of::<*mut ()>() + { // We've already given up on alignment here. Layout::for_size(padding_bytes) } else { @@ -268,12 +293,15 @@ impl<'a, 'ctx> StructLayoutTracker<'a, 'ctx> { pub fn align_struct(&self, layout: Layout) -> Option { if self.max_field_align < layout.align && - layout.align <= mem::size_of::<*mut ()>() { + layout.align <= mem::size_of::<*mut ()>() + { let ty = BlobTyBuilder::new(Layout::new(0, layout.align)).build(); - Some(StructFieldBuilder::named("__bindgen_align") - .pub_() - .build_ty(ty)) + Some( + StructFieldBuilder::named("__bindgen_align") + .pub_() + .build_ty(ty), + ) } else { None } @@ -293,7 +321,9 @@ impl<'a, 'ctx> StructLayoutTracker<'a, 'ctx> { self.max_field_align = cmp::max(self.max_field_align, layout.align); - StructFieldBuilder::named(padding_field_name).pub_().build_ty(ty) + StructFieldBuilder::named(padding_field_name) + .pub_() + .build_ty(ty) } /// Returns whether the new field is known to merge with a bitfield. @@ -312,14 +342,17 @@ impl<'a, 'ctx> StructLayoutTracker<'a, 'ctx> { // If it was, we may or may not need to align, depending on what the // current field alignment and the bitfield size and alignment are. - debug!("align_to_bitfield? {}: {:?} {:?}", - self.last_field_was_bitfield, - layout, - new_field_layout); + debug!( + "align_to_bitfield? {}: {:?} {:?}", + self.last_field_was_bitfield, + layout, + new_field_layout + ); if self.last_field_was_bitfield && - new_field_layout.align <= layout.size % layout.align && - new_field_layout.size <= layout.size % layout.align { + new_field_layout.align <= layout.size % layout.align && + new_field_layout.size <= layout.size % layout.align + { // The new field will be coalesced into some of the remaining bits. // // FIXME(emilio): I think this may not catch everything? diff --git a/src/features.rs b/src/features.rs index 3f59c6b9df..29e60ab735 100644 --- a/src/features.rs +++ b/src/features.rs @@ -167,7 +167,7 @@ impl Default for RustFeatures { #[cfg(test)] mod test { - #![allow(unused_imports)] +#![allow(unused_imports)] use super::*; fn test_target(target_str: &str, target: RustTarget) { diff --git a/src/ir/analysis/derive_copy.rs b/src/ir/analysis/derive_copy.rs index 91acad6853..de06f81cb7 100644 --- a/src/ir/analysis/derive_copy.rs +++ b/src/ir/analysis/derive_copy.rs @@ -1,17 +1,17 @@ //! Determining which types for which we can emit `#[derive(Copy)]`. use super::{ConstrainResult, MonotoneFramework, generate_dependencies}; -use std::collections::HashSet; -use std::collections::HashMap; -use ir::context::{BindgenContext, ItemId}; -use ir::item::IsOpaque; -use ir::traversal::EdgeKind; -use ir::ty::TypeKind; +use ir::comp::CompKind; use ir::comp::Field; use ir::comp::FieldMethods; +use ir::context::{BindgenContext, ItemId}; use ir::derive::CanTriviallyDeriveCopy; -use ir::comp::CompKind; +use ir::item::IsOpaque; use ir::template::TemplateParameters; +use ir::traversal::EdgeKind; +use ir::ty::TypeKind; +use std::collections::HashMap; +use std::collections::HashSet; /// An analysis that finds for each IR item whether copy cannot be derived. /// @@ -32,7 +32,8 @@ use ir::template::TemplateParameters; /// cannot derive copy. #[derive(Debug, Clone)] pub struct CannotDeriveCopy<'ctx, 'gen> - where 'gen: 'ctx +where + 'gen: 'ctx, { ctx: &'ctx BindgenContext<'gen>, @@ -150,7 +151,7 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDeriveCopy<'ctx, 'gen> { TypeKind::Function(..) | TypeKind::Enum(..) | TypeKind::Reference(..) | - TypeKind::Named | + TypeKind::TypeParam | TypeKind::BlockPointer | TypeKind::Pointer(..) | TypeKind::UnresolvedTypeRef(..) | @@ -163,9 +164,11 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDeriveCopy<'ctx, 'gen> { TypeKind::Array(t, len) => { let cant_derive_copy = self.cannot_derive_copy.contains(&t); - if cant_derive_copy { - trace!(" arrays of T for which we cannot derive Copy \ - also cannot derive Copy"); + if cant_derive_copy { + trace!( + " arrays of T for which we cannot derive Copy \ + also cannot derive Copy" + ); return self.insert(id); } @@ -182,13 +185,17 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDeriveCopy<'ctx, 'gen> { TypeKind::TemplateAlias(t, _) | TypeKind::Alias(t) => { let cant_derive_copy = self.cannot_derive_copy.contains(&t); - if cant_derive_copy { - trace!(" arrays of T for which we cannot derive Copy \ - also cannot derive Copy"); + if cant_derive_copy { + trace!( + " arrays of T for which we cannot derive Copy \ + also cannot derive Copy" + ); return self.insert(id); } - trace!(" aliases and type refs to T which can derive \ - Copy can also derive Copy"); + trace!( + " aliases and type refs to T which can derive \ + Copy can also derive Copy" + ); ConstrainResult::Same } @@ -202,7 +209,7 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDeriveCopy<'ctx, 'gen> { // default, the may have an explicit destructor in C++, so we can't // defer this check just for the union case. if info.has_destructor(self.ctx) { - trace!(" comp has destructor which cannot derive Copy"); + trace!(" comp has destructor which cannot derive copy"); return self.insert(id); } @@ -211,40 +218,44 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDeriveCopy<'ctx, 'gen> { // NOTE: If there's no template parameters we can derive copy // unconditionally, since arrays are magical for rustc, and // __BindgenUnionField always implements copy. - trace!(" comp can always derive Copy if it's a Union and no template parameters"); - return ConstrainResult::Same + trace!( + " comp can always derive debug if it's a Union and no template parameters" + ); + return ConstrainResult::Same; } // https://github.com/rust-lang/rust/issues/36640 if info.self_template_params(self.ctx).is_some() || - item.used_template_params(self.ctx).is_some() { - trace!(" comp cannot derive copy because issue 36640"); + item.used_template_params(self.ctx).is_some() + { + trace!( + " comp cannot derive copy because issue 36640" + ); return self.insert(id); } } - let bases_cannot_derive = info.base_members() - .iter() - .any(|base| self.cannot_derive_copy.contains(&base.ty)); + let bases_cannot_derive = + info.base_members().iter().any(|base| { + self.cannot_derive_copy.contains(&base.ty) + }); if bases_cannot_derive { - trace!(" base members cannot derive Copy, so we can't \ - either"); + trace!( + " base members cannot derive Copy, so we can't \ + either" + ); return self.insert(id); } - let fields_cannot_derive = info.fields() - .iter() - .any(|f| { - match *f { - Field::DataMember(ref data) => { - self.cannot_derive_copy.contains(&data.ty()) - } - Field::Bitfields(ref bfu) => { - bfu.bitfields() - .iter().any(|b| { - self.cannot_derive_copy.contains(&b.ty()) - }) - } + let fields_cannot_derive = + info.fields().iter().any(|f| match *f { + Field::DataMember(ref data) => { + self.cannot_derive_copy.contains(&data.ty()) + } + Field::Bitfields(ref bfu) => { + bfu.bitfields().iter().any(|b| { + self.cannot_derive_copy.contains(&b.ty()) + }) } }); if fields_cannot_derive { @@ -257,12 +268,15 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDeriveCopy<'ctx, 'gen> { } TypeKind::TemplateInstantiation(ref template) => { - let args_cannot_derive = template.template_arguments() - .iter() - .any(|arg| self.cannot_derive_copy.contains(&arg)); + let args_cannot_derive = + template.template_arguments().iter().any(|arg| { + self.cannot_derive_copy.contains(&arg) + }); if args_cannot_derive { - trace!(" template args cannot derive Copy, so \ - insantiation can't either"); + trace!( + " template args cannot derive Copy, so \ + insantiation can't either" + ); return self.insert(id); } @@ -270,11 +284,14 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDeriveCopy<'ctx, 'gen> { !template.template_definition().is_opaque(self.ctx, &()), "The early ty.is_opaque check should have handled this case" ); - let def_cannot_derive = self.cannot_derive_copy - .contains(&template.template_definition()); + let def_cannot_derive = self.cannot_derive_copy.contains( + &template.template_definition(), + ); if def_cannot_derive { - trace!(" template definition cannot derive Copy, so \ - insantiation can't either"); + trace!( + " template definition cannot derive Copy, so \ + insantiation can't either" + ); return self.insert(id); } @@ -291,7 +308,8 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDeriveCopy<'ctx, 'gen> { } fn each_depending_on(&self, id: ItemId, mut f: F) - where F: FnMut(ItemId), + where + F: FnMut(ItemId), { if let Some(edges) = self.dependencies.get(&id) { for item in edges { diff --git a/src/ir/analysis/derive_debug.rs b/src/ir/analysis/derive_debug.rs index 8f2be22ab9..146301559c 100644 --- a/src/ir/analysis/derive_debug.rs +++ b/src/ir/analysis/derive_debug.rs @@ -1,17 +1,17 @@ //! Determining which types for which we can emit `#[derive(Debug)]`. use super::{ConstrainResult, MonotoneFramework, generate_dependencies}; -use std::collections::HashSet; -use std::collections::HashMap; +use ir::comp::CompKind; +use ir::comp::Field; +use ir::comp::FieldMethods; use ir::context::{BindgenContext, ItemId}; +use ir::derive::CanTriviallyDeriveDebug; use ir::item::IsOpaque; use ir::traversal::EdgeKind; use ir::ty::RUST_DERIVE_IN_ARRAY_LIMIT; use ir::ty::TypeKind; -use ir::comp::Field; -use ir::comp::FieldMethods; -use ir::derive::CanTriviallyDeriveDebug; -use ir::comp::CompKind; +use std::collections::HashMap; +use std::collections::HashSet; /// An analysis that finds for each IR item whether debug cannot be derived. /// @@ -34,7 +34,8 @@ use ir::comp::CompKind; /// cannot derive debug. #[derive(Debug, Clone)] pub struct CannotDeriveDebug<'ctx, 'gen> - where 'gen: 'ctx +where + 'gen: 'ctx, { ctx: &'ctx BindgenContext<'gen>, @@ -141,7 +142,10 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDeriveDebug<'ctx, 'gen> { }; } - if ty.layout(self.ctx).map_or(false, |l| l.align > RUST_DERIVE_IN_ARRAY_LIMIT) { + if ty.layout(self.ctx).map_or(false, |l| { + l.align > RUST_DERIVE_IN_ARRAY_LIMIT + }) + { // We have to be conservative: the struct *could* have enough // padding that we emit an array that is longer than // `RUST_DERIVE_IN_ARRAY_LIMIT`. If we moved padding calculations @@ -162,7 +166,7 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDeriveDebug<'ctx, 'gen> { TypeKind::Enum(..) | TypeKind::Reference(..) | TypeKind::BlockPointer | - TypeKind::Named | + TypeKind::TypeParam | TypeKind::UnresolvedTypeRef(..) | TypeKind::ObjCInterface(..) | TypeKind::ObjCId | @@ -173,8 +177,10 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDeriveDebug<'ctx, 'gen> { TypeKind::Array(t, len) => { if self.cannot_derive_debug.contains(&t) { - trace!(" arrays of T for which we cannot derive Debug \ - also cannot derive Debug"); + trace!( + " arrays of T for which we cannot derive Debug \ + also cannot derive Debug" + ); return self.insert(id); } @@ -191,12 +197,16 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDeriveDebug<'ctx, 'gen> { TypeKind::TemplateAlias(t, _) | TypeKind::Alias(t) => { if self.cannot_derive_debug.contains(&t) { - trace!(" aliases and type refs to T which cannot derive \ - Debug also cannot derive Debug"); + trace!( + " aliases and type refs to T which cannot derive \ + Debug also cannot derive Debug" + ); self.insert(id) } else { - trace!(" aliases and type refs to T which can derive \ - Debug can also derive Debug"); + trace!( + " aliases and type refs to T which can derive \ + Debug can also derive Debug" + ); ConstrainResult::Same } } @@ -213,9 +223,10 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDeriveDebug<'ctx, 'gen> { return self.insert(id); } - if ty.layout(self.ctx) - .map_or(true, - |l| l.opaque().can_trivially_derive_debug()) { + if ty.layout(self.ctx).map_or(true, |l| { + l.opaque().can_trivially_derive_debug() + }) + { trace!(" union layout can trivially derive Debug"); return ConstrainResult::Same; } else { @@ -224,32 +235,33 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDeriveDebug<'ctx, 'gen> { } } - let bases_cannot_derive = info.base_members() - .iter() - .any(|base| self.cannot_derive_debug.contains(&base.ty)); + let bases_cannot_derive = + info.base_members().iter().any(|base| { + self.cannot_derive_debug.contains(&base.ty) + }); if bases_cannot_derive { - trace!(" base members cannot derive Debug, so we can't \ - either"); + trace!( + " base members cannot derive Debug, so we can't \ + either" + ); return self.insert(id); } - let fields_cannot_derive = info.fields() - .iter() - .any(|f| { - match *f { - Field::DataMember(ref data) => { - self.cannot_derive_debug.contains(&data.ty()) - } - Field::Bitfields(ref bfu) => { - bfu.bitfields() - .iter().any(|b| { - self.cannot_derive_debug.contains(&b.ty()) - }) - } + let fields_cannot_derive = + info.fields().iter().any(|f| match *f { + Field::DataMember(ref data) => { + self.cannot_derive_debug.contains(&data.ty()) + } + Field::Bitfields(ref bfu) => { + bfu.bitfields().iter().any(|b| { + self.cannot_derive_debug.contains(&b.ty()) + }) } }); if fields_cannot_derive { - trace!(" fields cannot derive Debug, so we can't either"); + trace!( + " fields cannot derive Debug, so we can't either" + ); return self.insert(id); } @@ -258,10 +270,13 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDeriveDebug<'ctx, 'gen> { } TypeKind::Pointer(inner) => { - let inner_type = self.ctx.resolve_type(inner).canonical_type(self.ctx); + let inner_type = + self.ctx.resolve_type(inner).canonical_type(self.ctx); if let TypeKind::Function(ref sig) = *inner_type.kind() { if !sig.can_trivially_derive_debug() { - trace!(" function pointer that can't trivially derive Debug"); + trace!( + " function pointer that can't trivially derive Debug" + ); return self.insert(id); } } @@ -270,12 +285,15 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDeriveDebug<'ctx, 'gen> { } TypeKind::TemplateInstantiation(ref template) => { - let args_cannot_derive = template.template_arguments() - .iter() - .any(|arg| self.cannot_derive_debug.contains(&arg)); + let args_cannot_derive = + template.template_arguments().iter().any(|arg| { + self.cannot_derive_debug.contains(&arg) + }); if args_cannot_derive { - trace!(" template args cannot derive Debug, so \ - insantiation can't either"); + trace!( + " template args cannot derive Debug, so \ + insantiation can't either" + ); return self.insert(id); } @@ -283,11 +301,14 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDeriveDebug<'ctx, 'gen> { !template.template_definition().is_opaque(self.ctx, &()), "The early ty.is_opaque check should have handled this case" ); - let def_cannot_derive = self.cannot_derive_debug - .contains(&template.template_definition()); + let def_cannot_derive = self.cannot_derive_debug.contains( + &template.template_definition(), + ); if def_cannot_derive { - trace!(" template definition cannot derive Debug, so \ - insantiation can't either"); + trace!( + " template definition cannot derive Debug, so \ + insantiation can't either" + ); return self.insert(id); } @@ -304,7 +325,8 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDeriveDebug<'ctx, 'gen> { } fn each_depending_on(&self, id: ItemId, mut f: F) - where F: FnMut(ItemId), + where + F: FnMut(ItemId), { if let Some(edges) = self.dependencies.get(&id) { for item in edges { diff --git a/src/ir/analysis/derive_default.rs b/src/ir/analysis/derive_default.rs index dd837f8c35..74e05cd64b 100644 --- a/src/ir/analysis/derive_default.rs +++ b/src/ir/analysis/derive_default.rs @@ -1,19 +1,19 @@ //! Determining which types for which we can emit `#[derive(Default)]`. -use super::{ConstrainResult, MonotoneFramework, HasVtable}; -use std::collections::HashSet; -use std::collections::HashMap; +use super::{ConstrainResult, HasVtable, MonotoneFramework}; +use ir::comp::CompKind; +use ir::comp::Field; +use ir::comp::FieldMethods; use ir::context::{BindgenContext, ItemId}; +use ir::derive::CanTriviallyDeriveDefault; use ir::item::IsOpaque; +use ir::item::ItemSet; use ir::traversal::EdgeKind; +use ir::traversal::Trace; use ir::ty::RUST_DERIVE_IN_ARRAY_LIMIT; use ir::ty::TypeKind; -use ir::comp::Field; -use ir::comp::FieldMethods; -use ir::derive::CanTriviallyDeriveDefault; -use ir::comp::CompKind; -use ir::traversal::Trace; -use ir::item::ItemSet; +use std::collections::HashMap; +use std::collections::HashSet; /// An analysis that finds for each IR item whether default cannot be derived. /// @@ -31,7 +31,8 @@ use ir::item::ItemSet; /// or field cannot be derived default. #[derive(Debug, Clone)] pub struct CannotDeriveDefault<'ctx, 'gen> - where 'gen: 'ctx +where + 'gen: 'ctx, { ctx: &'ctx BindgenContext<'gen>, @@ -97,18 +98,15 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDeriveDefault<'ctx, 'gen> { let mut dependencies = HashMap::new(); let cannot_derive_default = HashSet::new(); - let whitelisted_items: HashSet<_> = ctx.whitelisted_items() - .iter() - .cloned() - .collect(); + let whitelisted_items: HashSet<_> = + ctx.whitelisted_items().iter().cloned().collect(); - let whitelisted_and_blacklisted_items: ItemSet = whitelisted_items.iter() + let whitelisted_and_blacklisted_items: ItemSet = whitelisted_items + .iter() .cloned() .flat_map(|i| { let mut reachable = vec![i]; - i.trace(ctx, &mut |s, _| { - reachable.push(s); - }, &()); + i.trace(ctx, &mut |s, _| { reachable.push(s); }, &()); reachable }) .collect(); @@ -119,14 +117,20 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDeriveDefault<'ctx, 'gen> { { // We reverse our natural IR graph edges to find dependencies // between nodes. - item.trace(ctx, &mut |sub_item: ItemId, edge_kind| { - if ctx.whitelisted_items().contains(&sub_item) && - Self::consider_edge(edge_kind) { - dependencies.entry(sub_item) + item.trace( + ctx, + &mut |sub_item: ItemId, edge_kind| { + if ctx.whitelisted_items().contains(&sub_item) && + Self::consider_edge(edge_kind) + { + dependencies + .entry(sub_item) .or_insert(vec![]) .push(item); } - }, &()); + }, + &(), + ); } } @@ -171,7 +175,10 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDeriveDefault<'ctx, 'gen> { }; } - if ty.layout(self.ctx).map_or(false, |l| l.align > RUST_DERIVE_IN_ARRAY_LIMIT) { + if ty.layout(self.ctx).map_or(false, |l| { + l.align > RUST_DERIVE_IN_ARRAY_LIMIT + }) + { // We have to be conservative: the struct *could* have enough // padding that we emit an array that is longer than // `RUST_DERIVE_IN_ARRAY_LIMIT`. If we moved padding calculations @@ -192,7 +199,7 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDeriveDefault<'ctx, 'gen> { } TypeKind::Void | - TypeKind::Named | + TypeKind::TypeParam | TypeKind::Reference(..) | TypeKind::NullPtr | TypeKind::Pointer(..) | @@ -207,8 +214,10 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDeriveDefault<'ctx, 'gen> { TypeKind::Array(t, len) => { if self.cannot_derive_default.contains(&t) { - trace!(" arrays of T for which we cannot derive Default \ - also cannot derive Default"); + trace!( + " arrays of T for which we cannot derive Default \ + also cannot derive Default" + ); return self.insert(id); } @@ -225,12 +234,16 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDeriveDefault<'ctx, 'gen> { TypeKind::TemplateAlias(t, _) | TypeKind::Alias(t) => { if self.cannot_derive_default.contains(&t) { - trace!(" aliases and type refs to T which cannot derive \ - Default also cannot derive Default"); + trace!( + " aliases and type refs to T which cannot derive \ + Default also cannot derive Default" + ); self.insert(id) } else { - trace!(" aliases and type refs to T which can derive \ - Default can also derive Default"); + trace!( + " aliases and type refs to T which can derive \ + Default can also derive Default" + ); ConstrainResult::Same } } @@ -247,9 +260,10 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDeriveDefault<'ctx, 'gen> { return self.insert(id); } - if ty.layout(self.ctx) - .map_or(true, - |l| l.opaque().can_trivially_derive_default()) { + if ty.layout(self.ctx).map_or(true, |l| { + l.opaque().can_trivially_derive_default() + }) + { trace!(" union layout can trivially derive Default"); return ConstrainResult::Same; } else { @@ -263,35 +277,40 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDeriveDefault<'ctx, 'gen> { return self.insert(id); } - let bases_cannot_derive = info.base_members() - .iter() - .any(|base| !self.ctx.whitelisted_items().contains(&base.ty) || - self.cannot_derive_default.contains(&base.ty)); + let bases_cannot_derive = + info.base_members().iter().any(|base| { + !self.ctx.whitelisted_items().contains(&base.ty) || + self.cannot_derive_default.contains(&base.ty) + }); if bases_cannot_derive { - trace!(" base members cannot derive Default, so we can't \ - either"); + trace!( + " base members cannot derive Default, so we can't \ + either" + ); return self.insert(id); } - let fields_cannot_derive = info.fields() - .iter() - .any(|f| { - match *f { - Field::DataMember(ref data) => { - !self.ctx.whitelisted_items().contains(&data.ty()) || - self.cannot_derive_default.contains(&data.ty()) - } - Field::Bitfields(ref bfu) => { - bfu.bitfields() - .iter().any(|b| { - !self.ctx.whitelisted_items().contains(&b.ty()) || - self.cannot_derive_default.contains(&b.ty()) - }) - } + let fields_cannot_derive = + info.fields().iter().any(|f| match *f { + Field::DataMember(ref data) => { + !self.ctx.whitelisted_items().contains( + &data.ty(), + ) || + self.cannot_derive_default.contains(&data.ty()) + } + Field::Bitfields(ref bfu) => { + bfu.bitfields().iter().any(|b| { + !self.ctx.whitelisted_items().contains( + &b.ty(), + ) || + self.cannot_derive_default.contains(&b.ty()) + }) } }); if fields_cannot_derive { - trace!(" fields cannot derive Default, so we can't either"); + trace!( + " fields cannot derive Default, so we can't either" + ); return self.insert(id); } @@ -300,13 +319,19 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDeriveDefault<'ctx, 'gen> { } TypeKind::TemplateInstantiation(ref template) => { - if self.ctx.whitelisted_items().contains(&template.template_definition()) { - let args_cannot_derive = template.template_arguments() - .iter() - .any(|arg| self.cannot_derive_default.contains(&arg)); + if self.ctx.whitelisted_items().contains( + &template.template_definition(), + ) + { + let args_cannot_derive = + template.template_arguments().iter().any(|arg| { + self.cannot_derive_default.contains(&arg) + }); if args_cannot_derive { - trace!(" template args cannot derive Default, so \ - insantiation can't either"); + trace!( + " template args cannot derive Default, so \ + insantiation can't either" + ); return self.insert(id); } @@ -314,18 +339,23 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDeriveDefault<'ctx, 'gen> { !template.template_definition().is_opaque(self.ctx, &()), "The early ty.is_opaque check should have handled this case" ); - let def_cannot_derive = self.cannot_derive_default - .contains(&template.template_definition()); + let def_cannot_derive = + self.cannot_derive_default.contains(&template + .template_definition()); if def_cannot_derive { - trace!(" template definition cannot derive Default, so \ - insantiation can't either"); + trace!( + " template definition cannot derive Default, so \ + insantiation can't either" + ); return self.insert(id); } trace!(" template instantiation can derive Default"); ConstrainResult::Same } else { - trace!(" blacklisted template instantiation cannot derive default"); + trace!( + " blacklisted template instantiation cannot derive default" + ); return self.insert(id); } } @@ -345,7 +375,8 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDeriveDefault<'ctx, 'gen> { } fn each_depending_on(&self, id: ItemId, mut f: F) - where F: FnMut(ItemId), + where + F: FnMut(ItemId), { if let Some(edges) = self.dependencies.get(&id) { for item in edges { diff --git a/src/ir/analysis/derive_hash.rs b/src/ir/analysis/derive_hash.rs index e879bd2225..d0ab376235 100644 --- a/src/ir/analysis/derive_hash.rs +++ b/src/ir/analysis/derive_hash.rs @@ -1,17 +1,17 @@ //! Determining which types for which we can emit `#[derive(Hash)]`. use super::{ConstrainResult, MonotoneFramework, generate_dependencies}; -use std::collections::HashSet; -use std::collections::HashMap; +use ir::comp::CompKind; +use ir::comp::Field; +use ir::comp::FieldMethods; use ir::context::{BindgenContext, ItemId}; +use ir::derive::CanTriviallyDeriveHash; use ir::item::IsOpaque; use ir::traversal::EdgeKind; use ir::ty::RUST_DERIVE_IN_ARRAY_LIMIT; use ir::ty::TypeKind; -use ir::comp::Field; -use ir::comp::FieldMethods; -use ir::derive::CanTriviallyDeriveHash; -use ir::comp::CompKind; +use std::collections::HashMap; +use std::collections::HashSet; /// An analysis that finds for each IR item whether hash cannot be derived. /// @@ -34,7 +34,8 @@ use ir::comp::CompKind; /// cannot derive hash. #[derive(Debug, Clone)] pub struct CannotDeriveHash<'ctx, 'gen> - where 'gen: 'ctx +where + 'gen: 'ctx, { ctx: &'ctx BindgenContext<'gen>, @@ -141,7 +142,10 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDeriveHash<'ctx, 'gen> { }; } - if ty.layout(self.ctx).map_or(false, |l| l.align > RUST_DERIVE_IN_ARRAY_LIMIT) { + if ty.layout(self.ctx).map_or(false, |l| { + l.align > RUST_DERIVE_IN_ARRAY_LIMIT + }) + { // We have to be conservative: the struct *could* have enough // padding that we emit an array that is longer than // `RUST_DERIVE_IN_ARRAY_LIMIT`. If we moved padding calculations @@ -157,7 +161,7 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDeriveHash<'ctx, 'gen> { TypeKind::NullPtr | TypeKind::Int(..) | TypeKind::Enum(..) | - TypeKind::Named | + TypeKind::TypeParam | TypeKind::UnresolvedTypeRef(..) | TypeKind::BlockPointer | TypeKind::Reference(..) | @@ -176,8 +180,10 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDeriveHash<'ctx, 'gen> { TypeKind::Array(t, len) => { if self.cannot_derive_hash.contains(&t) { - trace!(" arrays of T for which we cannot derive Hash \ - also cannot derive Hash"); + trace!( + " arrays of T for which we cannot derive Hash \ + also cannot derive Hash" + ); return self.insert(id); } @@ -191,10 +197,13 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDeriveHash<'ctx, 'gen> { } TypeKind::Pointer(inner) => { - let inner_type = self.ctx.resolve_type(inner).canonical_type(self.ctx); + let inner_type = + self.ctx.resolve_type(inner).canonical_type(self.ctx); if let TypeKind::Function(ref sig) = *inner_type.kind() { if !sig.can_trivially_derive_hash() { - trace!(" function pointer that can't trivially derive Hash"); + trace!( + " function pointer that can't trivially derive Hash" + ); return self.insert(id); } } @@ -215,12 +224,16 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDeriveHash<'ctx, 'gen> { TypeKind::TemplateAlias(t, _) | TypeKind::Alias(t) => { if self.cannot_derive_hash.contains(&t) { - trace!(" aliases and type refs to T which cannot derive \ - Hash also cannot derive Hash"); + trace!( + " aliases and type refs to T which cannot derive \ + Hash also cannot derive Hash" + ); self.insert(id) } else { - trace!(" aliases and type refs to T which can derive \ - Hash can also derive Hash"); + trace!( + " aliases and type refs to T which can derive \ + Hash can also derive Hash" + ); ConstrainResult::Same } } @@ -237,9 +250,10 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDeriveHash<'ctx, 'gen> { return self.insert(id); } - if ty.layout(self.ctx) - .map_or(true, - |l| l.opaque().can_trivially_derive_hash()) { + if ty.layout(self.ctx).map_or(true, |l| { + l.opaque().can_trivially_derive_hash() + }) + { trace!(" union layout can trivially derive Hash"); return ConstrainResult::Same; } else { @@ -248,31 +262,34 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDeriveHash<'ctx, 'gen> { } } - let bases_cannot_derive = info.base_members() - .iter() - .any(|base| !self.ctx.whitelisted_items().contains(&base.ty) || - self.cannot_derive_hash.contains(&base.ty)); + let bases_cannot_derive = + info.base_members().iter().any(|base| { + !self.ctx.whitelisted_items().contains(&base.ty) || + self.cannot_derive_hash.contains(&base.ty) + }); if bases_cannot_derive { - trace!(" base members cannot derive Hash, so we can't \ - either"); + trace!( + " base members cannot derive Hash, so we can't \ + either" + ); return self.insert(id); } - let fields_cannot_derive = info.fields() - .iter() - .any(|f| { - match *f { - Field::DataMember(ref data) => { - !self.ctx.whitelisted_items().contains(&data.ty()) || - self.cannot_derive_hash.contains(&data.ty()) - } - Field::Bitfields(ref bfu) => { - bfu.bitfields() - .iter().any(|b| { - !self.ctx.whitelisted_items().contains(&b.ty()) || - self.cannot_derive_hash.contains(&b.ty()) - }) - } + let fields_cannot_derive = + info.fields().iter().any(|f| match *f { + Field::DataMember(ref data) => { + !self.ctx.whitelisted_items().contains( + &data.ty(), + ) || + self.cannot_derive_hash.contains(&data.ty()) + } + Field::Bitfields(ref bfu) => { + bfu.bitfields().iter().any(|b| { + !self.ctx.whitelisted_items().contains( + &b.ty(), + ) || + self.cannot_derive_hash.contains(&b.ty()) + }) } }); if fields_cannot_derive { @@ -285,12 +302,15 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDeriveHash<'ctx, 'gen> { } TypeKind::TemplateInstantiation(ref template) => { - let args_cannot_derive = template.template_arguments() - .iter() - .any(|arg| self.cannot_derive_hash.contains(&arg)); + let args_cannot_derive = + template.template_arguments().iter().any(|arg| { + self.cannot_derive_hash.contains(&arg) + }); if args_cannot_derive { - trace!(" template args cannot derive Hash, so \ - insantiation can't either"); + trace!( + " template args cannot derive Hash, so \ + insantiation can't either" + ); return self.insert(id); } @@ -298,11 +318,14 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDeriveHash<'ctx, 'gen> { !template.template_definition().is_opaque(self.ctx, &()), "The early ty.is_opaque check should have handled this case" ); - let def_cannot_derive = self.cannot_derive_hash - .contains(&template.template_definition()); + let def_cannot_derive = self.cannot_derive_hash.contains( + &template.template_definition(), + ); if def_cannot_derive { - trace!(" template definition cannot derive Hash, so \ - insantiation can't either"); + trace!( + " template definition cannot derive Hash, so \ + insantiation can't either" + ); return self.insert(id); } @@ -319,7 +342,8 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDeriveHash<'ctx, 'gen> { } fn each_depending_on(&self, id: ItemId, mut f: F) - where F: FnMut(ItemId), + where + F: FnMut(ItemId), { if let Some(edges) = self.dependencies.get(&id) { for item in edges { diff --git a/src/ir/analysis/derive_partial_eq.rs b/src/ir/analysis/derive_partial_eq.rs index f8624d1f0f..030c4c4821 100644 --- a/src/ir/analysis/derive_partial_eq.rs +++ b/src/ir/analysis/derive_partial_eq.rs @@ -1,17 +1,17 @@ //! Determining which types for which we can emit `#[derive(PartialEq)]`. use super::{ConstrainResult, MonotoneFramework, generate_dependencies}; -use std::collections::HashSet; -use std::collections::HashMap; +use ir::comp::CompKind; +use ir::comp::Field; +use ir::comp::FieldMethods; use ir::context::{BindgenContext, ItemId}; +use ir::derive::CanTriviallyDerivePartialEq; use ir::item::IsOpaque; use ir::traversal::EdgeKind; use ir::ty::RUST_DERIVE_IN_ARRAY_LIMIT; use ir::ty::TypeKind; -use ir::comp::Field; -use ir::comp::FieldMethods; -use ir::derive::CanTriviallyDerivePartialEq; -use ir::comp::CompKind; +use std::collections::HashMap; +use std::collections::HashSet; /// An analysis that finds for each IR item whether partialeq cannot be derived. /// @@ -34,7 +34,8 @@ use ir::comp::CompKind; /// cannot derive partialeq. #[derive(Debug, Clone)] pub struct CannotDerivePartialEq<'ctx, 'gen> - where 'gen: 'ctx +where + 'gen: 'ctx, { ctx: &'ctx BindgenContext<'gen>, @@ -96,7 +97,9 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDerivePartialEq<'ctx, 'gen> { type Extra = &'ctx BindgenContext<'gen>; type Output = HashSet; - fn new(ctx: &'ctx BindgenContext<'gen>) -> CannotDerivePartialEq<'ctx, 'gen> { + fn new( + ctx: &'ctx BindgenContext<'gen>, + ) -> CannotDerivePartialEq<'ctx, 'gen> { let cannot_derive_partialeq = HashSet::new(); let dependencies = generate_dependencies(ctx, Self::consider_edge); @@ -142,7 +145,10 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDerivePartialEq<'ctx, 'gen> { }; } - if ty.layout(self.ctx).map_or(false, |l| l.align > RUST_DERIVE_IN_ARRAY_LIMIT) { + if ty.layout(self.ctx).map_or(false, |l| { + l.align > RUST_DERIVE_IN_ARRAY_LIMIT + }) + { // We have to be conservative: the struct *could* have enough // padding that we emit an array that is longer than // `RUST_DERIVE_IN_ARRAY_LIMIT`. If we moved padding calculations @@ -160,7 +166,7 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDerivePartialEq<'ctx, 'gen> { TypeKind::Complex(..) | TypeKind::Float(..) | TypeKind::Enum(..) | - TypeKind::Named | + TypeKind::TypeParam | TypeKind::UnresolvedTypeRef(..) | TypeKind::BlockPointer | TypeKind::Reference(..) | @@ -173,8 +179,10 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDerivePartialEq<'ctx, 'gen> { TypeKind::Array(t, len) => { if self.cannot_derive_partialeq.contains(&t) { - trace!(" arrays of T for which we cannot derive PartialEq \ - also cannot derive PartialEq"); + trace!( + " arrays of T for which we cannot derive PartialEq \ + also cannot derive PartialEq" + ); return self.insert(id); } @@ -188,10 +196,13 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDerivePartialEq<'ctx, 'gen> { } TypeKind::Pointer(inner) => { - let inner_type = self.ctx.resolve_type(inner).canonical_type(self.ctx); + let inner_type = + self.ctx.resolve_type(inner).canonical_type(self.ctx); if let TypeKind::Function(ref sig) = *inner_type.kind() { if !sig.can_trivially_derive_partialeq() { - trace!(" function pointer that can't trivially derive PartialEq"); + trace!( + " function pointer that can't trivially derive PartialEq" + ); return self.insert(id); } } @@ -201,7 +212,9 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDerivePartialEq<'ctx, 'gen> { TypeKind::Function(ref sig) => { if !sig.can_trivially_derive_partialeq() { - trace!(" function that can't trivially derive PartialEq"); + trace!( + " function that can't trivially derive PartialEq" + ); return self.insert(id); } trace!(" function can derive PartialEq"); @@ -212,12 +225,16 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDerivePartialEq<'ctx, 'gen> { TypeKind::TemplateAlias(t, _) | TypeKind::Alias(t) => { if self.cannot_derive_partialeq.contains(&t) { - trace!(" aliases and type refs to T which cannot derive \ - PartialEq also cannot derive PartialEq"); + trace!( + " aliases and type refs to T which cannot derive \ + PartialEq also cannot derive PartialEq" + ); self.insert(id) } else { - trace!(" aliases and type refs to T which can derive \ - PartialEq can also derive PartialEq"); + trace!( + " aliases and type refs to T which can derive \ + PartialEq can also derive PartialEq" + ); ConstrainResult::Same } } @@ -234,10 +251,13 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDerivePartialEq<'ctx, 'gen> { return self.insert(id); } - if ty.layout(self.ctx) - .map_or(true, - |l| l.opaque().can_trivially_derive_partialeq()) { - trace!(" union layout can trivially derive PartialEq"); + if ty.layout(self.ctx).map_or(true, |l| { + l.opaque().can_trivially_derive_partialeq() + }) + { + trace!( + " union layout can trivially derive PartialEq" + ); return ConstrainResult::Same; } else { trace!(" union layout cannot derive PartialEq"); @@ -245,35 +265,44 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDerivePartialEq<'ctx, 'gen> { } } - let bases_cannot_derive = info.base_members() - .iter() - .any(|base| !self.ctx.whitelisted_items().contains(&base.ty) || - self.cannot_derive_partialeq.contains(&base.ty)); + let bases_cannot_derive = + info.base_members().iter().any(|base| { + !self.ctx.whitelisted_items().contains(&base.ty) || + self.cannot_derive_partialeq.contains(&base.ty) + }); if bases_cannot_derive { - trace!(" base members cannot derive PartialEq, so we can't \ - either"); + trace!( + " base members cannot derive PartialEq, so we can't \ + either" + ); return self.insert(id); } - let fields_cannot_derive = info.fields() - .iter() - .any(|f| { - match *f { - Field::DataMember(ref data) => { - !self.ctx.whitelisted_items().contains(&data.ty()) || - self.cannot_derive_partialeq.contains(&data.ty()) - } - Field::Bitfields(ref bfu) => { - bfu.bitfields() - .iter().any(|b| { - !self.ctx.whitelisted_items().contains(&b.ty()) || - self.cannot_derive_partialeq.contains(&b.ty()) - }) - } + let fields_cannot_derive = + info.fields().iter().any(|f| match *f { + Field::DataMember(ref data) => { + !self.ctx.whitelisted_items().contains( + &data.ty(), + ) || + self.cannot_derive_partialeq.contains( + &data.ty(), + ) + } + Field::Bitfields(ref bfu) => { + bfu.bitfields().iter().any(|b| { + !self.ctx.whitelisted_items().contains( + &b.ty(), + ) || + self.cannot_derive_partialeq.contains( + &b.ty(), + ) + }) } }); if fields_cannot_derive { - trace!(" fields cannot derive PartialEq, so we can't either"); + trace!( + " fields cannot derive PartialEq, so we can't either" + ); return self.insert(id); } @@ -282,12 +311,15 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDerivePartialEq<'ctx, 'gen> { } TypeKind::TemplateInstantiation(ref template) => { - let args_cannot_derive = template.template_arguments() - .iter() - .any(|arg| self.cannot_derive_partialeq.contains(&arg)); + let args_cannot_derive = + template.template_arguments().iter().any(|arg| { + self.cannot_derive_partialeq.contains(&arg) + }); if args_cannot_derive { - trace!(" template args cannot derive PartialEq, so \ - insantiation can't either"); + trace!( + " template args cannot derive PartialEq, so \ + insantiation can't either" + ); return self.insert(id); } @@ -295,11 +327,14 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDerivePartialEq<'ctx, 'gen> { !template.template_definition().is_opaque(self.ctx, &()), "The early ty.is_opaque check should have handled this case" ); - let def_cannot_derive = self.cannot_derive_partialeq - .contains(&template.template_definition()); + let def_cannot_derive = self.cannot_derive_partialeq.contains( + &template.template_definition(), + ); if def_cannot_derive { - trace!(" template definition cannot derive PartialEq, so \ - insantiation can't either"); + trace!( + " template definition cannot derive PartialEq, so \ + insantiation can't either" + ); return self.insert(id); } @@ -316,7 +351,8 @@ impl<'ctx, 'gen> MonotoneFramework for CannotDerivePartialEq<'ctx, 'gen> { } fn each_depending_on(&self, id: ItemId, mut f: F) - where F: FnMut(ItemId), + where + F: FnMut(ItemId), { if let Some(edges) = self.dependencies.get(&id) { for item in edges { diff --git a/src/ir/analysis/has_type_param_in_array.rs b/src/ir/analysis/has_type_param_in_array.rs index 3537949fb1..c361e9d9da 100644 --- a/src/ir/analysis/has_type_param_in_array.rs +++ b/src/ir/analysis/has_type_param_in_array.rs @@ -1,13 +1,13 @@ //! Determining which types has typed parameters in array. use super::{ConstrainResult, MonotoneFramework, generate_dependencies}; -use std::collections::HashSet; -use std::collections::HashMap; +use ir::comp::Field; +use ir::comp::FieldMethods; use ir::context::{BindgenContext, ItemId}; use ir::traversal::EdgeKind; use ir::ty::TypeKind; -use ir::comp::Field; -use ir::comp::FieldMethods; +use std::collections::HashMap; +use std::collections::HashSet; /// An analysis that finds for each IR item whether it has array or not. /// @@ -24,7 +24,8 @@ use ir::comp::FieldMethods; /// has. #[derive(Debug, Clone)] pub struct HasTypeParameterInArray<'ctx, 'gen> - where 'gen: 'ctx +where + 'gen: 'ctx, { ctx: &'ctx BindgenContext<'gen>, @@ -67,9 +68,13 @@ impl<'ctx, 'gen> HasTypeParameterInArray<'ctx, 'gen> { } fn insert(&mut self, id: ItemId) -> ConstrainResult { - trace!("inserting {:?} into the has_type_parameter_in_array set", id); + trace!( + "inserting {:?} into the has_type_parameter_in_array set", + id + ); - let was_not_already_in_set = self.has_type_parameter_in_array.insert(id); + let was_not_already_in_set = + self.has_type_parameter_in_array.insert(id); assert!( was_not_already_in_set, "We shouldn't try and insert {:?} twice because if it was \ @@ -86,7 +91,9 @@ impl<'ctx, 'gen> MonotoneFramework for HasTypeParameterInArray<'ctx, 'gen> { type Extra = &'ctx BindgenContext<'gen>; type Output = HashSet; - fn new(ctx: &'ctx BindgenContext<'gen>) -> HasTypeParameterInArray<'ctx, 'gen> { + fn new( + ctx: &'ctx BindgenContext<'gen>, + ) -> HasTypeParameterInArray<'ctx, 'gen> { let has_type_parameter_in_array = HashSet::new(); let dependencies = generate_dependencies(ctx, Self::consider_edge); @@ -130,7 +137,7 @@ impl<'ctx, 'gen> MonotoneFramework for HasTypeParameterInArray<'ctx, 'gen> { TypeKind::Enum(..) | TypeKind::Reference(..) | TypeKind::BlockPointer | - TypeKind::Named | + TypeKind::TypeParam | TypeKind::Opaque | TypeKind::Pointer(..) | TypeKind::UnresolvedTypeRef(..) | @@ -142,14 +149,17 @@ impl<'ctx, 'gen> MonotoneFramework for HasTypeParameterInArray<'ctx, 'gen> { } TypeKind::Array(t, _) => { - let inner_ty = self.ctx.resolve_type(t).canonical_type(self.ctx); + let inner_ty = + self.ctx.resolve_type(t).canonical_type(self.ctx); match *inner_ty.kind() { - TypeKind::Named => { + TypeKind::TypeParam => { trace!(" Array with Named type has type parameter"); self.insert(id) } _ => { - trace!(" Array without Named type does have type parameter"); + trace!( + " Array without Named type does have type parameter" + ); ConstrainResult::Same } } @@ -159,34 +169,34 @@ impl<'ctx, 'gen> MonotoneFramework for HasTypeParameterInArray<'ctx, 'gen> { TypeKind::TemplateAlias(t, _) | TypeKind::Alias(t) => { if self.has_type_parameter_in_array.contains(&t) { - trace!(" aliases and type refs to T which have array \ - also have array"); + trace!( + " aliases and type refs to T which have array \ + also have array" + ); self.insert(id) } else { - trace!(" aliases and type refs to T which do not have array \ - also do not have array"); + trace!( + " aliases and type refs to T which do not have array \ + also do not have array" + ); ConstrainResult::Same } } TypeKind::Comp(ref info) => { - let bases_have = info.base_members() - .iter() - .any(|base| self.has_type_parameter_in_array.contains(&base.ty)); + let bases_have = info.base_members().iter().any(|base| { + self.has_type_parameter_in_array.contains(&base.ty) + }); if bases_have { trace!(" bases have array, so we also have"); return self.insert(id); } - let fields_have = info.fields() - .iter() - .any(|f| { - match *f { - Field::DataMember(ref data) => { - self.has_type_parameter_in_array.contains(&data.ty()) - } - Field::Bitfields(..) => false, - } - }); + let fields_have = info.fields().iter().any(|f| match *f { + Field::DataMember(ref data) => { + self.has_type_parameter_in_array.contains(&data.ty()) + } + Field::Bitfields(..) => false, + }); if fields_have { trace!(" fields have array, so we also have"); return self.insert(id); @@ -197,20 +207,26 @@ impl<'ctx, 'gen> MonotoneFramework for HasTypeParameterInArray<'ctx, 'gen> { } TypeKind::TemplateInstantiation(ref template) => { - let args_have = template.template_arguments() - .iter() - .any(|arg| self.has_type_parameter_in_array.contains(&arg)); + let args_have = + template.template_arguments().iter().any(|arg| { + self.has_type_parameter_in_array.contains(&arg) + }); if args_have { - trace!(" template args have array, so \ - insantiation also has array"); + trace!( + " template args have array, so \ + insantiation also has array" + ); return self.insert(id); } - let def_has = self.has_type_parameter_in_array - .contains(&template.template_definition()); + let def_has = self.has_type_parameter_in_array.contains( + &template.template_definition(), + ); if def_has { - trace!(" template definition has array, so \ - insantiation also has"); + trace!( + " template definition has array, so \ + insantiation also has" + ); return self.insert(id); } @@ -221,7 +237,8 @@ impl<'ctx, 'gen> MonotoneFramework for HasTypeParameterInArray<'ctx, 'gen> { } fn each_depending_on(&self, id: ItemId, mut f: F) - where F: FnMut(ItemId), + where + F: FnMut(ItemId), { if let Some(edges) = self.dependencies.get(&id) { for item in edges { diff --git a/src/ir/analysis/has_vtable.rs b/src/ir/analysis/has_vtable.rs index a15730776b..bb85d0c96e 100644 --- a/src/ir/analysis/has_vtable.rs +++ b/src/ir/analysis/has_vtable.rs @@ -1,10 +1,11 @@ //! Determining which types has vtable + use super::{ConstrainResult, MonotoneFramework, generate_dependencies}; -use std::collections::HashSet; -use std::collections::HashMap; use ir::context::{BindgenContext, ItemId}; use ir::traversal::EdgeKind; use ir::ty::TypeKind; +use std::collections::HashMap; +use std::collections::HashSet; /// An analysis that finds for each IR item whether it has vtable or not /// @@ -18,7 +19,8 @@ use ir::ty::TypeKind; /// vtable if template definition has vtable #[derive(Debug, Clone)] pub struct HasVtableAnalysis<'ctx, 'gen> - where 'gen: 'ctx +where + 'gen: 'ctx, { ctx: &'ctx BindgenContext<'gen>, @@ -90,7 +92,7 @@ impl<'ctx, 'gen> MonotoneFramework for HasVtableAnalysis<'ctx, 'gen> { let item = self.ctx.resolve_item(id); let ty = match item.as_type() { None => return ConstrainResult::Same, - Some(ty) => ty + Some(ty) => ty, }; // TODO #851: figure out a way to handle deriving from template type parameters. @@ -104,7 +106,7 @@ impl<'ctx, 'gen> MonotoneFramework for HasVtableAnalysis<'ctx, 'gen> { } else { ConstrainResult::Same } - }, + } TypeKind::Comp(ref info) => { if info.has_own_virtual_method() { @@ -118,7 +120,7 @@ impl<'ctx, 'gen> MonotoneFramework for HasVtableAnalysis<'ctx, 'gen> { } else { ConstrainResult::Same } - }, + } TypeKind::TemplateInstantiation(ref inst) => { if self.have_vtable.contains(&inst.template_definition()) { @@ -126,14 +128,15 @@ impl<'ctx, 'gen> MonotoneFramework for HasVtableAnalysis<'ctx, 'gen> { } else { ConstrainResult::Same } - }, + } _ => ConstrainResult::Same, } } fn each_depending_on(&self, id: ItemId, mut f: F) - where F: FnMut(ItemId), + where + F: FnMut(ItemId), { if let Some(edges) = self.dependencies.get(&id) { for item in edges { diff --git a/src/ir/analysis/mod.rs b/src/ir/analysis/mod.rs index ef42e58dd0..cf4e3b4d36 100644 --- a/src/ir/analysis/mod.rs +++ b/src/ir/analysis/mod.rs @@ -43,8 +43,8 @@ pub use self::template_params::UsedTemplateParameters; mod derive_debug; pub use self::derive_debug::CannotDeriveDebug; mod has_vtable; -pub use self::has_vtable::HasVtableAnalysis; pub use self::has_vtable::HasVtable; +pub use self::has_vtable::HasVtableAnalysis; mod derive_default; pub use self::derive_default::CannotDeriveDefault; mod derive_copy; @@ -115,7 +115,8 @@ pub trait MonotoneFramework: Sized + fmt::Debug { /// queue up in the worklist when `constrain(node)` reports updated /// information. fn each_depending_on(&self, node: Self::Node, f: F) - where F: FnMut(Self::Node); + where + F: FnMut(Self::Node); } /// Whether an analysis's `constrain` function modified the incremental results @@ -131,16 +132,18 @@ pub enum ConstrainResult { /// Run an analysis in the monotone framework. pub fn analyze(extra: Analysis::Extra) -> Analysis::Output - where Analysis: MonotoneFramework, +where + Analysis: MonotoneFramework, { let mut analysis = Analysis::new(extra); let mut worklist = analysis.initial_worklist(); while let Some(node) = worklist.pop() { if let ConstrainResult::Changed = analysis.constrain(node) { - analysis.each_depending_on(node, |needs_work| { - worklist.push(needs_work); - }); + analysis.each_depending_on( + node, + |needs_work| { worklist.push(needs_work); }, + ); } } @@ -148,8 +151,13 @@ pub fn analyze(extra: Analysis::Extra) -> Analysis::Output } /// Generate the dependency map for analysis -pub fn generate_dependencies(ctx: &BindgenContext, consider_edge: F) -> HashMap> - where F: Fn(EdgeKind) -> bool { +pub fn generate_dependencies( + ctx: &BindgenContext, + consider_edge: F, +) -> HashMap> +where + F: Fn(EdgeKind) -> bool, +{ let mut dependencies = HashMap::new(); for &item in ctx.whitelisted_items() { @@ -158,14 +166,19 @@ pub fn generate_dependencies(ctx: &BindgenContext, consider_edge: F) -> HashM { // We reverse our natural IR graph edges to find dependencies // between nodes. - item.trace(ctx, &mut |sub_item: ItemId, edge_kind| { - if ctx.whitelisted_items().contains(&sub_item) && - consider_edge(edge_kind) { - dependencies.entry(sub_item) - .or_insert(vec![]) - .push(item); + item.trace( + ctx, + &mut |sub_item: ItemId, edge_kind| { + if ctx.whitelisted_items().contains(&sub_item) && + consider_edge(edge_kind) + { + dependencies.entry(sub_item).or_insert(vec![]).push( + item, + ); } - }, &()); + }, + &(), + ); } } dependencies @@ -313,7 +326,8 @@ mod tests { } fn each_depending_on(&self, node: Node, mut f: F) - where F: FnMut(Node), + where + F: FnMut(Node), { for dep in self.reversed.0[&node].iter() { f(*dep); @@ -334,7 +348,8 @@ mod tests { println!("reachable = {:#?}", reachable); fn nodes(nodes: A) -> HashSet - where A: AsRef<[usize]>, + where + A: AsRef<[usize]>, { nodes.as_ref().iter().cloned().map(Node).collect() } diff --git a/src/ir/analysis/template_params.rs b/src/ir/analysis/template_params.rs index 44878d9e16..caaa8f309f 100644 --- a/src/ir/analysis/template_params.rs +++ b/src/ir/analysis/template_params.rs @@ -147,7 +147,8 @@ use std::collections::{HashMap, HashSet}; /// documentation for details. #[derive(Debug, Clone)] pub struct UsedTemplateParameters<'ctx, 'gen> - where 'gen: 'ctx, +where + 'gen: 'ctx, { ctx: &'ctx BindgenContext<'gen>, @@ -208,11 +209,15 @@ impl<'ctx, 'gen> UsedTemplateParameters<'ctx, 'gen> { fn take_this_id_usage_set(&mut self, this_id: ItemId) -> ItemSet { self.used .get_mut(&this_id) - .expect("Should have a set of used template params for every item \ - id") + .expect( + "Should have a set of used template params for every item \ + id", + ) .take() - .expect("Should maintain the invariant that all used template param \ - sets are `Some` upon entry of `constrain`") + .expect( + "Should maintain the invariant that all used template param \ + sets are `Some` upon entry of `constrain`", + ) } /// We say that blacklisted items use all of their template parameters. The @@ -220,14 +225,19 @@ impl<'ctx, 'gen> UsedTemplateParameters<'ctx, 'gen> { /// since it won't be in the generated bindings, and we don't know exactly /// what they'll to with template parameters, but we can push the issue down /// the line to them. - fn constrain_instantiation_of_blacklisted_template(&self, - this_id: ItemId, - used_by_this_id: &mut ItemSet, - instantiation: &TemplateInstantiation) { - trace!(" instantiation of blacklisted template, uses all template \ - arguments"); - - let args = instantiation.template_arguments() + fn constrain_instantiation_of_blacklisted_template( + &self, + this_id: ItemId, + used_by_this_id: &mut ItemSet, + instantiation: &TemplateInstantiation, + ) { + trace!( + " instantiation of blacklisted template, uses all template \ + arguments" + ); + + let args = instantiation + .template_arguments() .into_iter() .map(|a| { a.into_resolver() @@ -238,12 +248,15 @@ impl<'ctx, 'gen> UsedTemplateParameters<'ctx, 'gen> { }) .filter(|a| *a != this_id) .flat_map(|a| { - self.used.get(&a) + self.used + .get(&a) .expect("Should have a used entry for the template arg") .as_ref() - .expect("Because a != this_id, and all used template \ + .expect( + "Because a != this_id, and all used template \ param sets other than this_id's are `Some`, \ - a's used template param set should be `Some`") + a's used template param set should be `Some`", + ) .iter() .cloned() }); @@ -253,17 +266,18 @@ impl<'ctx, 'gen> UsedTemplateParameters<'ctx, 'gen> { /// A template instantiation's concrete template argument is only used if /// the template definition uses the corresponding template parameter. - fn constrain_instantiation(&self, - this_id: ItemId, - used_by_this_id: &mut ItemSet, - instantiation: &TemplateInstantiation) { + fn constrain_instantiation( + &self, + this_id: ItemId, + used_by_this_id: &mut ItemSet, + instantiation: &TemplateInstantiation, + ) { trace!(" template instantiation"); let decl = self.ctx.resolve_type(instantiation.template_definition()); let args = instantiation.template_arguments(); - let params = decl.self_template_params(self.ctx) - .unwrap_or(vec![]); + let params = decl.self_template_params(self.ctx).unwrap_or(vec![]); debug_assert!(this_id != instantiation.template_definition()); let used_by_def = self.used @@ -275,10 +289,12 @@ impl<'ctx, 'gen> UsedTemplateParameters<'ctx, 'gen> { instantiation itself"); for (arg, param) in args.iter().zip(params.iter()) { - trace!(" instantiation's argument {:?} is used if definition's \ + trace!( + " instantiation's argument {:?} is used if definition's \ parameter {:?} is used", - arg, - param); + arg, + param + ); if used_by_def.contains(param) { trace!(" param is used by template definition"); @@ -297,10 +313,12 @@ impl<'ctx, 'gen> UsedTemplateParameters<'ctx, 'gen> { .get(&arg) .expect("Should have a used entry for the template arg") .as_ref() - .expect("Because arg != this_id, and all used template \ + .expect( + "Because arg != this_id, and all used template \ param sets other than this_id's are `Some`, \ arg's used template param set should be \ - `Some`") + `Some`", + ) .iter() .cloned(); used_by_this_id.extend(used_by_arg); @@ -313,31 +331,39 @@ impl<'ctx, 'gen> UsedTemplateParameters<'ctx, 'gen> { fn constrain_join(&self, used_by_this_id: &mut ItemSet, item: &Item) { trace!(" other item: join with successors' usage"); - item.trace(self.ctx, &mut |sub_id, edge_kind| { - // Ignore ourselves, since union with ourself is a - // no-op. Ignore edges that aren't relevant to the - // analysis. - if sub_id == item.id() || !Self::consider_edge(edge_kind) { - return; - } + item.trace( + self.ctx, + &mut |sub_id, edge_kind| { + // Ignore ourselves, since union with ourself is a + // no-op. Ignore edges that aren't relevant to the + // analysis. + if sub_id == item.id() || !Self::consider_edge(edge_kind) { + return; + } - let used_by_sub_id = self.used - .get(&sub_id) - .expect("Should have a used set for the sub_id successor") - .as_ref() - .expect("Because sub_id != id, and all used template \ + let used_by_sub_id = self.used + .get(&sub_id) + .expect("Should have a used set for the sub_id successor") + .as_ref() + .expect( + "Because sub_id != id, and all used template \ param sets other than id's are `Some`, \ sub_id's used template param set should be \ - `Some`") - .iter() - .cloned(); + `Some`", + ) + .iter() + .cloned(); - trace!(" union with {:?}'s usage: {:?}", - sub_id, - used_by_sub_id.clone().collect::>()); + trace!( + " union with {:?}'s usage: {:?}", + sub_id, + used_by_sub_id.clone().collect::>() + ); - used_by_this_id.extend(used_by_sub_id); - }, &()); + used_by_this_id.extend(used_by_sub_id); + }, + &(), + ); } } @@ -346,22 +372,20 @@ impl<'ctx, 'gen> MonotoneFramework for UsedTemplateParameters<'ctx, 'gen> { type Extra = &'ctx BindgenContext<'gen>; type Output = HashMap; - fn new(ctx: &'ctx BindgenContext<'gen>) - -> UsedTemplateParameters<'ctx, 'gen> { + fn new( + ctx: &'ctx BindgenContext<'gen>, + ) -> UsedTemplateParameters<'ctx, 'gen> { let mut used = HashMap::new(); let mut dependencies = HashMap::new(); - let whitelisted_items: HashSet<_> = ctx.whitelisted_items() - .iter() - .cloned() - .collect(); + let whitelisted_items: HashSet<_> = + ctx.whitelisted_items().iter().cloned().collect(); - let whitelisted_and_blacklisted_items: ItemSet = whitelisted_items.iter() + let whitelisted_and_blacklisted_items: ItemSet = whitelisted_items + .iter() .cloned() .flat_map(|i| { let mut reachable = vec![i]; - i.trace(ctx, &mut |s, _| { - reachable.push(s); - }, &()); + i.trace(ctx, &mut |s, _| { reachable.push(s); }, &()); reachable }) .collect(); @@ -373,53 +397,54 @@ impl<'ctx, 'gen> MonotoneFramework for UsedTemplateParameters<'ctx, 'gen> { { // We reverse our natural IR graph edges to find dependencies // between nodes. - item.trace(ctx, &mut |sub_item: ItemId, _| { - used.entry(sub_item).or_insert(Some(ItemSet::new())); - dependencies.entry(sub_item) - .or_insert(vec![]) - .push(item); - }, &()); + item.trace( + ctx, + &mut |sub_item: ItemId, _| { + used.entry(sub_item).or_insert(Some(ItemSet::new())); + dependencies.entry(sub_item).or_insert(vec![]).push( + item, + ); + }, + &(), + ); } // Additionally, whether a template instantiation's template // arguments are used depends on whether the template declaration's // generic template parameters are used. - ctx.resolve_item(item) - .as_type() - .map(|ty| match ty.kind() { - &TypeKind::TemplateInstantiation(ref inst) => { - let decl = ctx.resolve_type(inst.template_definition()); - let args = inst.template_arguments(); - - // Although template definitions should always have - // template parameters, there is a single exception: - // opaque templates. Hence the unwrap_or. - let params = decl.self_template_params(ctx) - .unwrap_or(vec![]); - - for (arg, param) in args.iter().zip(params.iter()) { - let arg = arg.into_resolver() - .through_type_aliases() - .through_type_refs() - .resolve(ctx) - .id(); - - let param = param.into_resolver() - .through_type_aliases() - .through_type_refs() - .resolve(ctx) - .id(); - - used.entry(arg).or_insert(Some(ItemSet::new())); - used.entry(param).or_insert(Some(ItemSet::new())); - - dependencies.entry(arg) - .or_insert(vec![]) - .push(param); - } + ctx.resolve_item(item).as_type().map(|ty| match ty.kind() { + &TypeKind::TemplateInstantiation(ref inst) => { + let decl = ctx.resolve_type(inst.template_definition()); + let args = inst.template_arguments(); + + // Although template definitions should always have + // template parameters, there is a single exception: + // opaque templates. Hence the unwrap_or. + let params = + decl.self_template_params(ctx).unwrap_or(vec![]); + + for (arg, param) in args.iter().zip(params.iter()) { + let arg = arg.into_resolver() + .through_type_aliases() + .through_type_refs() + .resolve(ctx) + .id(); + + let param = param + .into_resolver() + .through_type_aliases() + .through_type_refs() + .resolve(ctx) + .id(); + + used.entry(arg).or_insert(Some(ItemSet::new())); + used.entry(param).or_insert(Some(ItemSet::new())); + + dependencies.entry(arg).or_insert(vec![]).push(param); } - _ => {} - }); + } + _ => {} + }); } if cfg!(feature = "testing_only_extra_assertions") { @@ -436,10 +461,14 @@ impl<'ctx, 'gen> MonotoneFramework for UsedTemplateParameters<'ctx, 'gen> { for item in whitelisted_items.iter() { extra_assert!(used.contains_key(item)); extra_assert!(dependencies.contains_key(item)); - item.trace(ctx, &mut |sub_item, _| { - extra_assert!(used.contains_key(&sub_item)); - extra_assert!(dependencies.contains_key(&sub_item)); - }, &()) + item.trace( + ctx, + &mut |sub_item, _| { + extra_assert!(used.contains_key(&sub_item)); + extra_assert!(dependencies.contains_key(&sub_item)); + }, + &(), + ) } } @@ -460,9 +489,7 @@ impl<'ctx, 'gen> MonotoneFramework for UsedTemplateParameters<'ctx, 'gen> { .cloned() .flat_map(|i| { let mut reachable = vec![i]; - i.trace(self.ctx, &mut |s, _| { - reachable.push(s); - }, &()); + i.trace(self.ctx, &mut |s, _| { reachable.push(s); }, &()); reachable }) .collect() @@ -488,19 +515,28 @@ impl<'ctx, 'gen> MonotoneFramework for UsedTemplateParameters<'ctx, 'gen> { let ty_kind = item.as_type().map(|ty| ty.kind()); match ty_kind { // Named template type parameters trivially use themselves. - Some(&TypeKind::Named) => { + Some(&TypeKind::TypeParam) => { trace!(" named type, trivially uses itself"); used_by_this_id.insert(id); } // Template instantiations only use their template arguments if the // template definition uses the corresponding template parameter. Some(&TypeKind::TemplateInstantiation(ref inst)) => { - if self.whitelisted_items.contains(&inst.template_definition()) { - self.constrain_instantiation(id, &mut used_by_this_id, inst); + if self.whitelisted_items.contains( + &inst.template_definition(), + ) + { + self.constrain_instantiation( + id, + &mut used_by_this_id, + inst, + ); } else { - self.constrain_instantiation_of_blacklisted_template(id, - &mut used_by_this_id, - inst); + self.constrain_instantiation_of_blacklisted_template( + id, + &mut used_by_this_id, + inst, + ); } } // Otherwise, add the union of each of its referent item's template @@ -511,9 +547,11 @@ impl<'ctx, 'gen> MonotoneFramework for UsedTemplateParameters<'ctx, 'gen> { trace!(" finally, used set is {:?}", used_by_this_id); let new_len = used_by_this_id.len(); - assert!(new_len >= original_len, - "This is the property that ensures this function is monotone -- \ - if it doesn't hold, the analysis might never terminate!"); + assert!( + new_len >= original_len, + "This is the property that ensures this function is monotone -- \ + if it doesn't hold, the analysis might never terminate!" + ); // Put the set back in the hash map and restore our invariant. debug_assert!(self.used[&id].is_none()); @@ -528,7 +566,8 @@ impl<'ctx, 'gen> MonotoneFramework for UsedTemplateParameters<'ctx, 'gen> { } fn each_depending_on(&self, item: ItemId, mut f: F) - where F: FnMut(ItemId), + where + F: FnMut(ItemId), { if let Some(edges) = self.dependencies.get(&item) { for item in edges { @@ -542,7 +581,8 @@ impl<'ctx, 'gen> MonotoneFramework for UsedTemplateParameters<'ctx, 'gen> { impl<'ctx, 'gen> From> for HashMap { fn from(used_templ_params: UsedTemplateParameters<'ctx, 'gen>) -> Self { - used_templ_params.used + used_templ_params + .used .into_iter() .map(|(k, v)| (k, v.unwrap())) .collect() diff --git a/src/ir/annotations.rs b/src/ir/annotations.rs index 98be0540f2..bc57b555ac 100644 --- a/src/ir/annotations.rs +++ b/src/ir/annotations.rs @@ -148,10 +148,11 @@ impl Annotations { fn parse(&mut self, comment: &clang::Comment, matched: &mut bool) { use clang_sys::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_name() == "div" && + 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() { @@ -159,10 +160,10 @@ impl Annotations { "hide" => self.hide = true, "nocopy" => self.disallow_copy = true, "replaces" => { - self.use_instead_of = Some(attr.value - .split("::") - .map(Into::into) - .collect()) + self.use_instead_of = + Some( + attr.value.split("::").map(Into::into).collect(), + ) } "private" => { self.private_fields = Some(attr.value != "false") diff --git a/src/ir/comment.rs b/src/ir/comment.rs index f772482e46..afa2a38589 100644 --- a/src/ir/comment.rs +++ b/src/ir/comment.rs @@ -47,7 +47,8 @@ fn preprocess_single_lines(comment: &str, indent: usize) -> String { let indent = make_indent(indent); let mut is_first = true; - let lines: Vec<_> = comment.lines() + let lines: Vec<_> = comment + .lines() .map(|l| l.trim_left_matches('/').trim()) .map(|l| { let indent = if is_first { "" } else { &*indent }; @@ -60,12 +61,13 @@ fn preprocess_single_lines(comment: &str, indent: usize) -> String { } fn preprocess_multi_line(comment: &str, indent: usize) -> String { - let comment = comment.trim_left_matches('/') - .trim_left_matches('*') - .trim_left_matches('!') - .trim_right_matches('/') - .trim_right_matches('*') - .trim(); + let comment = comment + .trim_left_matches('/') + .trim_left_matches('*') + .trim_left_matches('!') + .trim_right_matches('/') + .trim_right_matches('*') + .trim(); let indent = make_indent(indent); // Strip any potential `*` characters preceding each line. @@ -109,10 +111,14 @@ mod test { #[test] fn processes_multi_lines_correctly() { - assert_eq!(preprocess("/** hello \n * world \n * foo \n */", 0), - "/// hello\n/// world\n/// foo"); - - assert_eq!(preprocess("/**\nhello\n*world\n*foo\n*/", 0), - "/// hello\n/// world\n/// foo"); + assert_eq!( + preprocess("/** hello \n * world \n * foo \n */", 0), + "/// hello\n/// world\n/// foo" + ); + + assert_eq!( + preprocess("/**\nhello\n*world\n*foo\n*/", 0), + "/// hello\n/// world\n/// foo" + ); } } diff --git a/src/ir/comp.rs b/src/ir/comp.rs index 98002b68a7..1a02feb5d4 100644 --- a/src/ir/comp.rs +++ b/src/ir/comp.rs @@ -5,9 +5,9 @@ use super::context::{BindgenContext, ItemId}; use super::dot::DotAttributes; use super::item::{IsOpaque, Item}; use super::layout::Layout; -use super::traversal::{EdgeKind, Trace, Tracer}; // use super::ty::RUST_DERIVE_IN_ARRAY_LIMIT; use super::template::TemplateParameters; +use super::traversal::{EdgeKind, Trace, Tracer}; use clang; use codegen::struct_layout::{align_to, bytes_from_bits_pow2}; use ir::derive::CanDeriveCopy; @@ -75,7 +75,7 @@ impl Method { /// Is this a destructor method? pub fn is_destructor(&self) -> bool { self.kind == MethodKind::Destructor || - self.kind == MethodKind::VirtualDestructor + self.kind == MethodKind::VirtualDestructor } /// Is this a constructor? @@ -86,7 +86,7 @@ impl Method { /// Is this a virtual method? pub fn is_virtual(&self) -> bool { self.kind == MethodKind::Virtual || - self.kind == MethodKind::VirtualDestructor + self.kind == MethodKind::VirtualDestructor } /// Is this a static method? @@ -172,16 +172,22 @@ pub enum Field { impl Field { fn has_destructor(&self, ctx: &BindgenContext) -> bool { match *self { - Field::DataMember(ref data) => ctx.resolve_type(data.ty).has_destructor(ctx), + Field::DataMember(ref data) => { + ctx.resolve_type(data.ty).has_destructor(ctx) + } // Bitfields may not be of a type that has a destructor. - Field::Bitfields(BitfieldUnit { .. }) => false, + Field::Bitfields(BitfieldUnit { + .. + }) => false, } } /// Get this field's layout. pub fn layout(&self, ctx: &BindgenContext) -> Option { match *self { - Field::Bitfields(BitfieldUnit { layout, ..}) => Some(layout), + Field::Bitfields(BitfieldUnit { + layout, .. + }) => Some(layout), Field::DataMember(ref data) => { ctx.resolve_type(data.ty).layout(ctx) } @@ -193,13 +199,16 @@ impl Trace for Field { type Extra = (); fn trace(&self, _: &BindgenContext, tracer: &mut T, _: &()) - where T: Tracer, + where + T: Tracer, { match *self { Field::DataMember(ref data) => { tracer.visit_kind(data.ty, EdgeKind::Field); } - Field::Bitfields(BitfieldUnit { ref bitfields, .. }) => { + Field::Bitfields(BitfieldUnit { + ref bitfields, .. + }) => { for bf in bitfields { tracer.visit_kind(bf.ty(), EdgeKind::Field); } @@ -209,16 +218,24 @@ impl Trace for Field { } impl DotAttributes for Field { - fn dot_attributes(&self, ctx: &BindgenContext, out: &mut W) -> io::Result<()> - where W: io::Write + fn dot_attributes( + &self, + ctx: &BindgenContext, + out: &mut W, + ) -> io::Result<()> + where + W: io::Write, { match *self { - Field::DataMember(ref data) => { - data.dot_attributes(ctx, out) - } - Field::Bitfields(BitfieldUnit { layout, ref bitfields, .. }) => { - writeln!(out, - r#" + Field::DataMember(ref data) => data.dot_attributes(ctx, out), + Field::Bitfields(BitfieldUnit { + layout, + ref bitfields, + .. + }) => { + writeln!( + out, + r#" bitfield unit @@ -229,8 +246,9 @@ impl DotAttributes for Field { "#, - layout.size, - layout.align)?; + layout.size, + layout.align + )?; for bf in bitfields { bf.dot_attributes(ctx, out)?; } @@ -241,25 +259,39 @@ impl DotAttributes for Field { } impl DotAttributes for FieldData { - fn dot_attributes(&self, _ctx: &BindgenContext, out: &mut W) -> io::Result<()> - where W: io::Write + fn dot_attributes( + &self, + _ctx: &BindgenContext, + out: &mut W, + ) -> io::Result<()> + where + W: io::Write, { - writeln!(out, - "", - self.name().unwrap_or("(anonymous)"), - self.ty()) + writeln!( + out, + "", + self.name().unwrap_or("(anonymous)"), + self.ty() + ) } } impl DotAttributes for Bitfield { - fn dot_attributes(&self, _ctx: &BindgenContext, out: &mut W) -> io::Result<()> - where W: io::Write + fn dot_attributes( + &self, + _ctx: &BindgenContext, + out: &mut W, + ) -> io::Result<()> + where + W: io::Write, { - writeln!(out, - "", - self.name(), - self.width(), - self.ty()) + writeln!( + out, + "", + self.name(), + self.width(), + self.ty() + ) } } @@ -359,14 +391,15 @@ struct RawField(FieldData); impl RawField { /// Construct a new `RawField`. - fn new(name: Option, - ty: ItemId, - comment: Option, - annotations: Option, - bitfield: Option, - mutable: bool, - offset: Option) - -> RawField { + fn new( + name: Option, + ty: ItemId, + comment: Option, + annotations: Option, + bitfield: Option, + mutable: bool, + offset: Option, + ) -> RawField { RawField(FieldData { name: name, ty: ty, @@ -411,10 +444,12 @@ impl FieldMethods for RawField { /// Convert the given ordered set of raw fields into a list of either plain data /// members, and/or bitfield units containing multiple bitfields. -fn raw_fields_to_fields_and_bitfield_units(ctx: &BindgenContext, - raw_fields: I) - -> Vec - where I: IntoIterator +fn raw_fields_to_fields_and_bitfield_units( + ctx: &BindgenContext, + raw_fields: I, +) -> Vec +where + I: IntoIterator, { let mut raw_fields = raw_fields.into_iter().fuse().peekable(); let mut fields = vec![]; @@ -444,26 +479,32 @@ fn raw_fields_to_fields_and_bitfield_units(ctx: &BindgenContext, break; } - bitfields_to_allocation_units(ctx, - &mut bitfield_unit_count, - &mut fields, - bitfields); + bitfields_to_allocation_units( + ctx, + &mut bitfield_unit_count, + &mut fields, + bitfields, + ); } - assert!(raw_fields.next().is_none(), - "The above loop should consume all items in `raw_fields`"); + assert!( + raw_fields.next().is_none(), + "The above loop should consume all items in `raw_fields`" + ); fields } /// Given a set of contiguous raw bitfields, group and allocate them into /// (potentially multiple) bitfield units. -fn bitfields_to_allocation_units(ctx: &BindgenContext, - bitfield_unit_count: &mut usize, - fields: &mut E, - raw_bitfields: I) - where E: Extend, - I: IntoIterator +fn bitfields_to_allocation_units( + ctx: &BindgenContext, + bitfield_unit_count: &mut usize, + fields: &mut E, + raw_bitfields: I, +) where + E: Extend, + I: IntoIterator, { assert!(ctx.collected_typerefs()); @@ -478,12 +519,14 @@ fn bitfields_to_allocation_units(ctx: &BindgenContext, // TODO(emilio): Take into account C++'s wide bitfields, and // packing, sigh. - fn flush_allocation_unit(fields: &mut E, - bitfield_unit_count: &mut usize, - unit_size_in_bits: usize, - unit_align_in_bits: usize, - bitfields: Vec) - where E: Extend + fn flush_allocation_unit( + fields: &mut E, + bitfield_unit_count: &mut usize, + unit_size_in_bits: usize, + unit_align_in_bits: usize, + bitfields: Vec, + ) where + E: Extend, { *bitfield_unit_count += 1; let align = bytes_from_bits_pow2(unit_align_in_bits); @@ -508,26 +551,28 @@ fn bitfields_to_allocation_units(ctx: &BindgenContext, for bitfield in raw_bitfields { let bitfield_width = bitfield.bitfield().unwrap() as usize; - let bitfield_layout = - ctx.resolve_type(bitfield.ty()) - .layout(ctx) - .expect("Bitfield without layout? Gah!"); + let bitfield_layout = ctx.resolve_type(bitfield.ty()) + .layout(ctx) + .expect("Bitfield without layout? Gah!"); let bitfield_size = bitfield_layout.size; let bitfield_align = bitfield_layout.align; let mut offset = unit_size_in_bits; if is_ms_struct { if unit_size_in_bits != 0 && - (bitfield_width == 0 || - bitfield_width > unfilled_bits_in_unit) { + (bitfield_width == 0 || + bitfield_width > unfilled_bits_in_unit) + { // We've reached the end of this allocation unit, so flush it // and its bitfields. unit_size_in_bits = align_to(unit_size_in_bits, unit_align * 8); - flush_allocation_unit(fields, - bitfield_unit_count, - unit_size_in_bits, - unit_align, - mem::replace(&mut bitfields_in_unit, vec![])); + flush_allocation_unit( + fields, + bitfield_unit_count, + unit_size_in_bits, + unit_align, + mem::replace(&mut bitfields_in_unit, vec![]), + ); // Now we're working on a fresh bitfield allocation unit, so reset // the current unit size and alignment. @@ -541,7 +586,9 @@ fn bitfields_to_allocation_units(ctx: &BindgenContext, } else { if offset != 0 && (bitfield_width == 0 || - (offset & (bitfield_align * 8 - 1)) + bitfield_width > bitfield_size * 8) { + (offset & (bitfield_align * 8 - 1)) + bitfield_width > + bitfield_size * 8) + { offset = align_to(offset, bitfield_align * 8); } } @@ -572,11 +619,13 @@ fn bitfields_to_allocation_units(ctx: &BindgenContext, if unit_size_in_bits != 0 { // Flush the last allocation unit and its bitfields. - flush_allocation_unit(fields, - bitfield_unit_count, - unit_size_in_bits, - unit_align, - bitfields_in_unit); + flush_allocation_unit( + fields, + bitfield_unit_count, + unit_size_in_bits, + unit_align, + bitfields_in_unit, + ); } } @@ -606,7 +655,9 @@ impl CompFields { raws.push(raw); } CompFields::AfterComputingBitfieldUnits(_) => { - panic!("Must not append new fields after computing bitfield allocation units"); + panic!( + "Must not append new fields after computing bitfield allocation units" + ); } } } @@ -621,8 +672,12 @@ impl CompFields { } }; - let fields_and_units = raw_fields_to_fields_and_bitfield_units(ctx, raws); - mem::replace(self, CompFields::AfterComputingBitfieldUnits(fields_and_units)); + let fields_and_units = + raw_fields_to_fields_and_bitfield_units(ctx, raws); + mem::replace( + self, + CompFields::AfterComputingBitfieldUnits(fields_and_units), + ); } } @@ -630,7 +685,8 @@ impl Trace for CompFields { type Extra = (); fn trace(&self, context: &BindgenContext, tracer: &mut T, _: &()) - where T: Tracer, + where + T: Tracer, { match *self { CompFields::BeforeComputingBitfieldUnits(ref fields) => { @@ -750,7 +806,7 @@ pub struct CompInfo { /// The abstract template parameters of this class. Note that these are NOT /// concrete template arguments, and should always be a - /// `Type(TypeKind::Named(name))`. For concrete template arguments, see + /// `Type(TypeKind::TypeParam(name))`. For concrete template arguments, see /// `TypeKind::TemplateInstantiation`. template_params: Vec, @@ -845,9 +901,12 @@ impl CompInfo { /// Is this compound type unsized? pub fn is_unsized(&self, ctx: &BindgenContext, itemid: &ItemId) -> bool { !ctx.lookup_item_id_has_vtable(itemid) && self.fields().is_empty() && - self.base_members.iter().all(|base| { - ctx.resolve_type(base.ty).canonical_type(ctx).is_unsized(ctx, &base.ty) - }) + self.base_members.iter().all(|base| { + ctx.resolve_type(base.ty).canonical_type(ctx).is_unsized( + ctx, + &base.ty, + ) + }) } /// Does this compound type have a destructor? @@ -861,17 +920,17 @@ impl CompInfo { self.detect_has_destructor_cycle.set(true); let has_destructor = self.has_destructor || - match self.kind { - CompKind::Union => false, - CompKind::Struct => { - self.base_members.iter().any(|base| { - ctx.resolve_type(base.ty).has_destructor(ctx) - }) || - self.fields().iter().any(|field| { - field.has_destructor(ctx) - }) - } - }; + match self.kind { + CompKind::Union => false, + CompKind::Struct => { + self.base_members.iter().any(|base| { + ctx.resolve_type(base.ty).has_destructor(ctx) + }) || + self.fields().iter().any( + |field| field.has_destructor(ctx), + ) + } + }; self.detect_has_destructor_cycle.set(false); @@ -961,14 +1020,17 @@ impl CompInfo { } /// Construct a new compound type from a Clang type. - pub fn from_ty(potential_id: ItemId, - ty: &clang::Type, - location: Option, - ctx: &mut BindgenContext) - -> Result { + pub fn from_ty( + potential_id: ItemId, + ty: &clang::Type, + location: Option, + ctx: &mut BindgenContext, + ) -> Result { use clang_sys::*; - assert!(ty.template_args().is_none(), - "We handle template instantiations elsewhere"); + assert!( + ty.template_args().is_none(), + "We handle template instantiations elsewhere" + ); let mut cursor = ty.declaration(); let mut kind = Self::kind_from_cursor(&cursor); @@ -1119,8 +1181,8 @@ impl CompInfo { ci.packed = true; } CXCursor_TemplateTypeParameter => { - let param = Item::named_type(None, cur, ctx) - .expect("Item::named_type should't fail when pointing \ + let param = Item::type_param(None, cur, ctx) + .expect("Item::type_param should't fail when pointing \ at a TemplateTypeParameter"); ci.template_params.push(param); } @@ -1246,8 +1308,9 @@ impl CompInfo { Ok(ci) } - fn kind_from_cursor(cursor: &clang::Cursor) - -> Result { + fn kind_from_cursor( + cursor: &clang::Cursor, + ) -> Result { use clang_sys::*; Ok(match cursor.kind() { CXCursor_UnionDecl => CompKind::Union, @@ -1292,7 +1355,11 @@ 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, item: &Item) -> bool { + pub fn needs_explicit_vtable( + &self, + ctx: &BindgenContext, + item: &Item, + ) -> bool { ctx.lookup_item_id_has_vtable(&item.id()) && !self.base_members.iter().any(|base| { // NB: Ideally, we could rely in all these types being `comp`, and @@ -1325,19 +1392,23 @@ impl CompInfo { /// 2. Each field can derive `Copy` pub fn can_be_rust_union(&self, ctx: &BindgenContext) -> bool { ctx.options().rust_features().untagged_union() && - self.fields().iter().all(|f| - match *f { - Field::DataMember(ref field_data) => field_data.ty().can_derive_copy(ctx), - Field::Bitfields(_) => false, + self.fields().iter().all(|f| match *f { + Field::DataMember(ref field_data) => { + field_data.ty().can_derive_copy(ctx) } - ) + Field::Bitfields(_) => false, + }) } - } impl DotAttributes for CompInfo { - fn dot_attributes(&self, ctx: &BindgenContext, out: &mut W) -> io::Result<()> - where W: io::Write + fn dot_attributes( + &self, + ctx: &BindgenContext, + out: &mut W, + ) -> io::Result<()> + where + W: io::Write, { writeln!(out, "", self.kind)?; @@ -1354,7 +1425,10 @@ impl DotAttributes for CompInfo { } if self.has_non_type_template_params { - writeln!(out, "")?; + writeln!( + out, + "" + )?; } if self.packed { @@ -1362,7 +1436,10 @@ impl DotAttributes for CompInfo { } if self.is_forward_declaration { - writeln!(out, "")?; + writeln!( + out, + "" + )?; } if !self.fields().is_empty() { @@ -1386,9 +1463,10 @@ impl IsOpaque for CompInfo { } impl TemplateParameters for CompInfo { - fn self_template_params(&self, - _ctx: &BindgenContext) - -> Option> { + fn self_template_params( + &self, + _ctx: &BindgenContext, + ) -> Option> { if self.template_params.is_empty() { None } else { @@ -1401,7 +1479,8 @@ impl Trace for CompInfo { type Extra = Item; fn trace(&self, context: &BindgenContext, tracer: &mut T, item: &Item) - where T: Tracer, + where + T: Tracer, { let params = item.all_template_params(context).unwrap_or(vec![]); for p in params { diff --git a/src/ir/context.rs b/src/ir/context.rs index e0a2a806a0..eb599dd0ac 100644 --- a/src/ir/context.rs +++ b/src/ir/context.rs @@ -1,25 +1,28 @@ //! Common context that is passed around during parsing and codegen. -use super::derive::{CanDeriveCopy, CanDeriveDebug, CanDeriveDefault, CanDeriveHash, CanDerivePartialEq}; +use super::analysis::{CannotDeriveCopy, CannotDeriveDebug, + CannotDeriveDefault, CannotDeriveHash, + CannotDerivePartialEq, HasTypeParameterInArray, + HasVtableAnalysis, UsedTemplateParameters, analyze}; +use super::derive::{CanDeriveCopy, CanDeriveDebug, CanDeriveDefault, + CanDeriveHash, CanDerivePartialEq}; use super::int::IntKind; -use super::item::{IsOpaque, HasTypeParamInArray, Item, ItemAncestors, ItemCanonicalPath, ItemSet}; +use super::item::{HasTypeParamInArray, IsOpaque, Item, ItemAncestors, + ItemCanonicalPath, ItemSet}; use super::item_kind::ItemKind; use super::module::{Module, ModuleKind}; -use super::analysis::{analyze, UsedTemplateParameters, CannotDeriveDebug, HasVtableAnalysis, - CannotDeriveDefault, CannotDeriveCopy, HasTypeParameterInArray, - CannotDeriveHash, CannotDerivePartialEq}; use super::template::{TemplateInstantiation, TemplateParameters}; use super::traversal::{self, Edge, ItemTraversal}; use super::ty::{FloatKind, Type, TypeKind}; use BindgenOptions; -use cexpr; use callbacks::ParseCallbacks; +use cexpr; use clang::{self, Cursor}; use clang_sys; use parse::ClangItemParser; use std::borrow::Cow; use std::cell::Cell; -use std::collections::{HashMap, hash_map, HashSet}; +use std::collections::{HashMap, HashSet, hash_map}; use std::collections::btree_map::{self, BTreeMap}; use std::fmt; use std::iter::IntoIterator; @@ -49,7 +52,8 @@ impl CanDeriveDebug for ItemId { impl CanDeriveDefault for ItemId { fn can_derive_default(&self, ctx: &BindgenContext) -> bool { - ctx.options().derive_default && ctx.lookup_item_id_can_derive_default(*self) + ctx.options().derive_default && + ctx.lookup_item_id_can_derive_default(*self) } } @@ -67,7 +71,8 @@ impl CanDeriveHash for ItemId { impl CanDerivePartialEq for ItemId { fn can_derive_partialeq(&self, ctx: &BindgenContext) -> bool { - ctx.options().derive_partialeq && ctx.lookup_item_id_can_derive_partialeq(*self) + ctx.options().derive_partialeq && + ctx.lookup_item_id_can_derive_partialeq(*self) } } @@ -111,7 +116,7 @@ pub struct BindgenContext<'ctx> { /// Maps from a cursor to the item id of the named template type parameter /// for that cursor. - named_types: HashMap, + type_params: HashMap, /// A cursor to module map. Similar reason than above. modules: HashMap, @@ -234,18 +239,22 @@ pub struct BindgenContext<'ctx> { /// A traversal of whitelisted items. struct WhitelistedItemsTraversal<'ctx, 'gen> - where 'gen: 'ctx +where + 'gen: 'ctx, { ctx: &'ctx BindgenContext<'gen>, - traversal: ItemTraversal<'ctx, - 'gen, - ItemSet, - Vec, - for<'a> fn(&'a BindgenContext, Edge) -> bool>, + traversal: ItemTraversal< + 'ctx, + 'gen, + ItemSet, + Vec, + for<'a> fn(&'a BindgenContext, Edge) -> bool, + >, } impl<'ctx, 'gen> Iterator for WhitelistedItemsTraversal<'ctx, 'gen> - where 'gen: 'ctx +where + 'gen: 'ctx, { type Item = ItemId; @@ -253,7 +262,9 @@ impl<'ctx, 'gen> Iterator for WhitelistedItemsTraversal<'ctx, 'gen> loop { match self.traversal.next() { None => return None, - Some(id) if self.ctx.resolve_item(id).is_hidden(self.ctx) => continue, + Some(id) if self.ctx.resolve_item(id).is_hidden(self.ctx) => { + continue + } Some(id) => return Some(id), } } @@ -261,18 +272,21 @@ impl<'ctx, 'gen> Iterator for WhitelistedItemsTraversal<'ctx, 'gen> } impl<'ctx, 'gen> WhitelistedItemsTraversal<'ctx, 'gen> - where 'gen: 'ctx +where + 'gen: 'ctx, { /// Construct a new whitelisted items traversal. - pub fn new(ctx: &'ctx BindgenContext<'gen>, - roots: R, - predicate: for<'a> fn(&'a BindgenContext, Edge) -> bool) - -> Self - where R: IntoIterator, + pub fn new( + ctx: &'ctx BindgenContext<'gen>, + roots: R, + predicate: for<'a> fn(&'a BindgenContext, Edge) -> bool, + ) -> Self + where + R: IntoIterator, { WhitelistedItemsTraversal { ctx: ctx, - traversal: ItemTraversal::new(ctx, roots, predicate) + traversal: ItemTraversal::new(ctx, roots, predicate), } } } @@ -286,13 +300,13 @@ impl<'ctx> BindgenContext<'ctx> { let parse_options = clang_sys::CXTranslationUnit_DetailedPreprocessingRecord; - let translation_unit = - clang::TranslationUnit::parse(&index, - "", - &options.clang_args, - &options.input_unsaved_files, - parse_options) - .expect("TranslationUnit::parse failed"); + let translation_unit = clang::TranslationUnit::parse( + &index, + "", + &options.clang_args, + &options.input_unsaved_files, + parse_options, + ).expect("TranslationUnit::parse failed"); // TODO(emilio): Use the CXTargetInfo here when available. // @@ -326,8 +340,7 @@ impl<'ctx> BindgenContext<'ctx> { // We need to make sure that we don't include __ because rust will turn into // ___. let effective_target = effective_target.unwrap(); - let needs_mangling_hack = - effective_target.contains("darwin") || + let needs_mangling_hack = effective_target.contains("darwin") || effective_target.contains("ios") || effective_target == "i686-pc-win32"; @@ -335,7 +348,7 @@ impl<'ctx> BindgenContext<'ctx> { let mut me = BindgenContext { items: Default::default(), types: Default::default(), - named_types: Default::default(), + type_params: Default::default(), modules: Default::default(), next_item_id: ItemId(1), root_module: root_module.id(), @@ -386,8 +399,9 @@ impl<'ctx> BindgenContext<'ctx> { /// Finish parsing the current partial type, pop it off the /// `currently_parsed_types` stack, and return it. pub fn finish_parsing(&mut self) -> PartialType { - self.currently_parsed_types.pop() - .expect("should have been parsing a type, if we finished parsing a type") + self.currently_parsed_types.pop().expect( + "should have been parsing a type, if we finished parsing a type", + ) } /// Get the user-provided callbacks by reference, if any. @@ -399,24 +413,30 @@ impl<'ctx> BindgenContext<'ctx> { /// /// This inserts it into the internal items set, and its type into the /// internal types set. - pub fn add_item(&mut self, - item: Item, - declaration: Option, - location: Option) { - 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() || - item.kind().expect_type().is_opaque(self, &item), - "Adding a type without declaration?"); + pub fn add_item( + &mut self, + item: Item, + declaration: Option, + location: Option, + ) { + 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_type_param() || + item.kind().expect_type().is_opaque(self, &item), + "Adding a type without declaration?" + ); let id = item.id(); let is_type = item.kind().is_type(); let is_unnamed = is_type && item.expect_type().name().is_none(); - let is_template_instantiation = - is_type && item.expect_type().is_template_instantiation(); + let is_template_instantiation = is_type && + item.expect_type().is_template_instantiation(); if item.id() != self.root_module { self.add_item_to_module(&item); @@ -427,8 +447,10 @@ impl<'ctx> BindgenContext<'ctx> { } let old_item = self.items.insert(id, item); - assert!(old_item.is_none(), - "should not have already associated an item with the given id"); + assert!( + old_item.is_none(), + "should not have already associated an item with the given id" + ); // Unnamed items can have an USR, but they can't be referenced from // other sites explicitly and the USR can match if the unnamed items are @@ -449,9 +471,11 @@ 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()); + debug!( + "Invalid declaration {:?} found for type {:?}", + declaration, + self.items.get(&id).unwrap().kind().expect_type() + ); return; } @@ -460,9 +484,11 @@ impl<'ctx> BindgenContext<'ctx> { } else if let Some(usr) = declaration.usr() { TypeKey::USR(usr) } else { - warn!("Valid declaration with no USR: {:?}, {:?}", - declaration, - location); + warn!( + "Valid declaration with no USR: {:?}, {:?}", + declaration, + location + ); TypeKey::Declaration(declaration) }; @@ -481,18 +507,22 @@ impl<'ctx> BindgenContext<'ctx> { if let Some(parent) = self.items.get_mut(&item.parent_id()) { if let Some(module) = parent.as_module_mut() { - debug!("add_item_to_module: adding {:?} as child of parent module {:?}", - item.id(), - item.parent_id()); + debug!( + "add_item_to_module: adding {:?} as child of parent module {:?}", + item.id(), + item.parent_id() + ); module.children_mut().insert(item.id()); return; } } - debug!("add_item_to_module: adding {:?} as child of current module {:?}", - item.id(), - self.current_module); + debug!( + "add_item_to_module: adding {:?} as child of current module {:?}", + item.id(), + self.current_module + ); self.items .get_mut(&self.current_module) @@ -504,34 +534,46 @@ impl<'ctx> BindgenContext<'ctx> { } /// Add a new named template type parameter to this context's item set. - pub fn add_named_type(&mut self, item: Item, definition: clang::Cursor) { - debug!("BindgenContext::add_named_type: item = {:?}; definition = {:?}", - item, - definition); - - assert!(item.expect_type().is_named(), - "Should directly be a named type, not a resolved reference or anything"); - assert_eq!(definition.kind(), - clang_sys::CXCursor_TemplateTypeParameter); + pub fn add_type_param(&mut self, item: Item, definition: clang::Cursor) { + debug!( + "BindgenContext::add_type_param: item = {:?}; definition = {:?}", + item, + definition + ); + + assert!( + item.expect_type().is_type_param(), + "Should directly be a named type, not a resolved reference or anything" + ); + assert_eq!( + definition.kind(), + clang_sys::CXCursor_TemplateTypeParameter + ); self.add_item_to_module(&item); let id = item.id(); let old_item = self.items.insert(id, item); - assert!(old_item.is_none(), - "should not have already associated an item with the given id"); + assert!( + old_item.is_none(), + "should not have already associated an item with the given id" + ); - let old_named_ty = self.named_types.insert(definition, id); - assert!(old_named_ty.is_none(), - "should not have already associated a named type with this id"); + let old_named_ty = self.type_params.insert(definition, id); + assert!( + old_named_ty.is_none(), + "should not have already associated a named type with this id" + ); } /// Get the named type defined at the given cursor location, if we've /// already added one. - pub fn get_named_type(&self, definition: &clang::Cursor) -> Option { - assert_eq!(definition.kind(), - clang_sys::CXCursor_TemplateTypeParameter); - self.named_types.get(definition).cloned() + pub fn get_type_param(&self, definition: &clang::Cursor) -> Option { + assert_eq!( + definition.kind(), + clang_sys::CXCursor_TemplateTypeParameter + ); + self.type_params.get(definition).cloned() } // TODO: Move all this syntax crap to other part of the code. @@ -552,8 +594,9 @@ impl<'ctx> BindgenContext<'ctx> { 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 { + name.contains("?") || name.contains("$") || + "bool" == name + { let mut s = name.to_owned(); s = s.replace("@", "_"); s = s.replace("?", "_"); @@ -585,9 +628,9 @@ impl<'ctx> BindgenContext<'ctx> { } /// Gather all the unresolved type references. - fn collect_typerefs - (&mut self) - -> Vec<(ItemId, clang::Type, clang::Cursor, Option)> { + fn collect_typerefs( + &mut self, + ) -> Vec<(ItemId, clang::Type, clang::Cursor, Option)> { debug_assert!(!self.collected_typerefs); self.collected_typerefs = true; let mut typerefs = vec![]; @@ -613,19 +656,20 @@ impl<'ctx> BindgenContext<'ctx> { let typerefs = self.collect_typerefs(); for (id, ty, loc, parent_id) in typerefs { - let _resolved = { - let resolved = Item::from_ty(&ty, loc, parent_id, self) + let _resolved = + { + let resolved = Item::from_ty(&ty, loc, parent_id, self) .unwrap_or_else(|_| { warn!("Could not resolve type reference, falling back \ to opaque blob"); Item::new_opaque_type(self.next_item_id(), &ty, self) }); - let item = self.items.get_mut(&id).unwrap(); + let item = self.items.get_mut(&id).unwrap(); - *item.kind_mut().as_type_mut().unwrap().kind_mut() = - TypeKind::ResolvedTypeRef(resolved); - resolved - }; + *item.kind_mut().as_type_mut().unwrap().kind_mut() = + TypeKind::ResolvedTypeRef(resolved); + resolved + }; // Something in the STL is trolling me. I don't need this assertion // right now, but worth investigating properly once this lands. @@ -639,7 +683,8 @@ impl<'ctx> BindgenContext<'ctx> { fn compute_bitfield_units(&mut self) { assert!(self.collected_typerefs()); - let need_bitfield_allocation = mem::replace(&mut self.need_bitfield_allocation, vec![]); + let need_bitfield_allocation = + mem::replace(&mut self.need_bitfield_allocation, vec![]); for id in need_bitfield_allocation { // To appease the borrow checker, we temporarily remove this item // from the context, and then replace it once we are done computing @@ -740,14 +785,19 @@ impl<'ctx> BindgenContext<'ctx> { let old_module = { let immut_self = &*self; - old_parent.ancestors(immut_self) + old_parent + .ancestors(immut_self) .chain(Some(immut_self.root_module)) .find(|id| { let item = immut_self.resolve_item(*id); - item.as_module().map_or(false, |m| m.children().contains(&replacement)) + item.as_module().map_or(false, |m| { + m.children().contains(&replacement) + }) }) }; - let old_module = old_module.expect("Every replacement item should be in a module"); + let old_module = old_module.expect( + "Every replacement item should be in a module", + ); let new_module = { let immut_self = &*self; @@ -783,7 +833,8 @@ impl<'ctx> BindgenContext<'ctx> { /// Enter the code generation phase, invoke the given callback `cb`, and /// leave the code generation phase. pub fn gen(&mut self, cb: F) -> Out - where F: FnOnce(&Self) -> Out, + where + F: FnOnce(&Self) -> Out, { use aster::symbol::ToSymbol; use syntax::ext::expand::ExpansionConfig; @@ -858,16 +909,18 @@ impl<'ctx> BindgenContext<'ctx> { } } - fn assert_no_dangling_item_traversal<'me> - (&'me self) - -> traversal::AssertNoDanglingItemsTraversal<'me, 'ctx> { + fn assert_no_dangling_item_traversal<'me>( + &'me self, + ) -> traversal::AssertNoDanglingItemsTraversal<'me, 'ctx> { assert!(self.in_codegen_phase()); assert!(self.current_module == self.root_module); let roots = self.items().map(|(&id, _)| id); - traversal::AssertNoDanglingItemsTraversal::new(self, - roots, - traversal::all_edges) + traversal::AssertNoDanglingItemsTraversal::new( + self, + roots, + traversal::all_edges, + ) } /// When the `testing_only_extra_assertions` feature is enabled, walk over @@ -890,14 +943,21 @@ impl<'ctx> BindgenContext<'ctx> { .through_type_aliases() .resolve(self) .id(); - id.ancestors(self) - .chain(Some(self.root_module)) - .any(|ancestor| { - debug!("Checking if {:?} is a child of {:?}", id, ancestor); - self.resolve_item(ancestor) - .as_module() - .map_or(false, |m| m.children().contains(&id)) - }) + id.ancestors(self).chain(Some(self.root_module)).any( + |ancestor| { + debug!( + "Checking if {:?} is a child of {:?}", + id, + ancestor + ); + self.resolve_item(ancestor).as_module().map_or( + false, + |m| { + m.children().contains(&id) + }, + ) + }, + ) }, "{:?} should be in some ancestor module's children set", id @@ -914,8 +974,10 @@ impl<'ctx> BindgenContext<'ctx> { /// Look up whether the item with `id` has vtable or not. pub fn lookup_item_id_has_vtable(&self, id: &ItemId) -> bool { - assert!(self.in_codegen_phase(), - "We only compute vtables when we enter codegen"); + assert!( + self.in_codegen_phase(), + "We only compute vtables when we enter codegen" + ); // Look up the computed value for whether the item with `id` has a // vtable or not. @@ -931,10 +993,12 @@ impl<'ctx> BindgenContext<'ctx> { // any sense of template parameter usage, and you're on your own. let mut used_params = HashMap::new(); for &id in self.whitelisted_items() { - used_params.entry(id) - .or_insert(id.self_template_params(self) - .map_or(Default::default(), - |params| params.into_iter().collect())); + used_params.entry(id).or_insert( + id.self_template_params(self).map_or( + Default::default(), + |params| params.into_iter().collect(), + ), + ); } self.used_template_parameters = Some(used_params); } @@ -954,18 +1018,22 @@ impl<'ctx> BindgenContext<'ctx> { /// manually provide a definition for them. To give them the most /// flexibility when doing that, we assume that they use every template /// parameter and always pass template arguments through in instantiations. - pub fn uses_template_parameter(&self, - item: ItemId, - template_param: ItemId) - -> bool { - assert!(self.in_codegen_phase(), - "We only compute template parameter usage as we enter codegen"); + pub fn uses_template_parameter( + &self, + item: ItemId, + template_param: ItemId, + ) -> bool { + assert!( + self.in_codegen_phase(), + "We only compute template parameter usage as we enter codegen" + ); if self.resolve_item(item).is_hidden(self) { return true; } - let template_param = template_param.into_resolver() + let template_param = template_param + .into_resolver() .through_type_refs() .through_type_aliases() .resolve(self) @@ -983,12 +1051,16 @@ impl<'ctx> BindgenContext<'ctx> { /// /// Has the same restrictions that `uses_template_parameter` has. pub fn uses_any_template_parameters(&self, item: ItemId) -> bool { - assert!(self.in_codegen_phase(), - "We only compute template parameter usage as we enter codegen"); + assert!( + self.in_codegen_phase(), + "We only compute template parameter usage as we enter codegen" + ); self.used_template_parameters .as_ref() - .expect("should have template parameter usage info in codegen phase") + .expect( + "should have template parameter usage info in codegen phase", + ) .get(&item) .map_or(false, |used| !used.is_empty()) } @@ -1069,22 +1141,27 @@ impl<'ctx> BindgenContext<'ctx> { /// Note that `declaration_id` is not guaranteed to be in the context's item /// set! It is possible that it is a partial type that we are still in the /// middle of parsign. - fn get_declaration_info_for_template_instantiation - (&self, - instantiation: &Cursor) - -> Option<(Cursor, ItemId, usize)> { - instantiation.cur_type() + fn get_declaration_info_for_template_instantiation( + &self, + instantiation: &Cursor, + ) -> Option<(Cursor, ItemId, usize)> { + instantiation + .cur_type() .canonical_declaration(Some(instantiation)) .and_then(|canon_decl| { - self.get_resolved_type(&canon_decl) - .and_then(|template_decl_id| { - template_decl_id.num_self_template_params(self) - .map(|num_params| { - (*canon_decl.cursor(), - template_decl_id, - num_params) - }) - }) + self.get_resolved_type(&canon_decl).and_then( + |template_decl_id| { + template_decl_id.num_self_template_params(self).map( + |num_params| { + ( + *canon_decl.cursor(), + template_decl_id, + num_params, + ) + }, + ) + }, + ) }) .or_else(|| { // If we haven't already parsed the declaration of @@ -1094,7 +1171,8 @@ impl<'ctx> BindgenContext<'ctx> { // already errored out before we started // constructing our IR because you can't instantiate // a template until it is fully defined. - instantiation.referenced() + instantiation + .referenced() .and_then(|referenced| { self.currently_parsed_types() .iter() @@ -1102,12 +1180,15 @@ impl<'ctx> BindgenContext<'ctx> { .cloned() }) .and_then(|template_decl| { - template_decl.num_self_template_params(self) - .map(|num_template_params| { - (*template_decl.decl(), - template_decl.id(), - num_template_params) - }) + template_decl.num_self_template_params(self).map( + |num_template_params| { + ( + *template_decl.decl(), + template_decl.id(), + num_template_params, + ) + }, + ) }) }) } @@ -1145,20 +1226,23 @@ impl<'ctx> BindgenContext<'ctx> { /// module. They use their template's definition for their name, so the /// parent is only useful for ensuring that their layout tests get /// codegen'd. - fn instantiate_template(&mut self, - with_id: ItemId, - template: ItemId, - ty: &clang::Type, - location: clang::Cursor) - -> Option { + fn instantiate_template( + &mut self, + with_id: ItemId, + template: ItemId, + ty: &clang::Type, + location: clang::Cursor, + ) -> Option { use clang_sys; let num_expected_args = match self.resolve_type(template) .num_self_template_params(self) { Some(n) => n, None => { - warn!("Tried to instantiate a template for which we could not \ - determine any template parameters"); + warn!( + "Tried to instantiate a template for which we could not \ + determine any template parameters" + ); return None; } }; @@ -1178,12 +1262,14 @@ impl<'ctx> BindgenContext<'ctx> { // being specialized via the `location`'s type, and if we do not // filter it out, we'll add an extra layer of template instantiation // on accident. - let idx = children.iter() - .position(|c| c.kind() == clang_sys::CXCursor_TemplateRef); + let idx = children.iter().position(|c| { + c.kind() == clang_sys::CXCursor_TemplateRef + }); if let Some(idx) = idx { - if children.iter() - .take(idx) - .all(|c| c.kind() == clang_sys::CXCursor_NamespaceRef) { + if children.iter().take(idx).all(|c| { + c.kind() == clang_sys::CXCursor_NamespaceRef + }) + { children = children.into_iter().skip(idx + 1).collect(); } } @@ -1200,10 +1286,12 @@ impl<'ctx> BindgenContext<'ctx> { // potentially a dangling reference. Instead, use the canonical // template declaration as the parent. It is already parsed and // has a known-resolvable `ItemId`. - let ty = Item::from_ty_or_ref(child.cur_type(), - *child, - Some(template), - self); + let ty = Item::from_ty_or_ref( + child.cur_type(), + *child, + Some(template), + self, + ); args.push(ty); } clang_sys::CXCursor_TemplateRef => { @@ -1214,13 +1302,18 @@ impl<'ctx> BindgenContext<'ctx> { }; if num_expected_template_args == 0 || - child.has_at_least_num_children(num_expected_template_args) { + child.has_at_least_num_children( + num_expected_template_args, + ) + { // Do a happy little parse. See comment in the TypeRef // match arm about parent IDs. - let ty = Item::from_ty_or_ref(child.cur_type(), - *child, - Some(template), - self); + let ty = Item::from_ty_or_ref( + child.cur_type(), + *child, + Some(template), + self, + ); args.push(ty); } else { // This is the case mentioned in the doc comment where @@ -1229,37 +1322,49 @@ impl<'ctx> BindgenContext<'ctx> { // instantiation :( let args_len = args.len(); if args_len < num_expected_template_args { - warn!("Found a template instantiation without \ - enough template arguments"); + warn!( + "Found a template instantiation without \ + enough template arguments" + ); return None; } - let mut sub_args: Vec<_> = - args.drain(args_len - num_expected_template_args..) - .collect(); + let mut sub_args: Vec<_> = args.drain( + args_len - num_expected_template_args.., + ).collect(); sub_args.reverse(); let sub_name = Some(template_decl_cursor.spelling()); - let sub_inst = TemplateInstantiation::new(template_decl_id, sub_args); + let sub_inst = TemplateInstantiation::new( + template_decl_id, + sub_args, + ); let sub_kind = TypeKind::TemplateInstantiation(sub_inst); - let sub_ty = Type::new(sub_name, - template_decl_cursor.cur_type() - .fallible_layout() - .ok(), - sub_kind, - false); + let sub_ty = Type::new( + sub_name, + template_decl_cursor + .cur_type() + .fallible_layout() + .ok(), + sub_kind, + false, + ); let sub_id = self.next_item_id(); - let sub_item = Item::new(sub_id, - None, - None, - self.current_module, - ItemKind::Type(sub_ty)); + let sub_item = Item::new( + sub_id, + None, + None, + self.current_module, + ItemKind::Type(sub_ty), + ); // Bypass all the validations in add_item explicitly. - debug!("instantiate_template: inserting nested \ + debug!( + "instantiate_template: inserting nested \ instantiation item: {:?}", - sub_item); + sub_item + ); self.add_item_to_module(&sub_item); debug_assert!(sub_id == sub_item.id()); self.items.insert(sub_id, sub_item); @@ -1267,8 +1372,10 @@ impl<'ctx> BindgenContext<'ctx> { } } _ => { - warn!("Found template arg cursor we can't handle: {:?}", - child); + warn!( + "Found template arg cursor we can't handle: {:?}", + child + ); found_const_arg = true; } } @@ -1281,28 +1388,40 @@ impl<'ctx> BindgenContext<'ctx> { // arguments. For example, `Foo` versus `Bar`. // We can't handle these instantiations, so just punt in this // situation... - warn!("Found template instantiated with a const value; \ - bindgen can't handle this kind of template instantiation!"); + warn!( + "Found template instantiated with a const value; \ + bindgen can't handle this kind of template instantiation!" + ); return None; } if args.len() != num_expected_args { - warn!("Found a template with an unexpected number of template \ - arguments"); + warn!( + "Found a template with an unexpected number of template \ + arguments" + ); return None; } args.reverse(); let type_kind = TypeKind::TemplateInstantiation( - TemplateInstantiation::new(template, args)); + TemplateInstantiation::new(template, 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 item = - Item::new(with_id, None, None, self.current_module, ItemKind::Type(ty)); + let ty = Type::new( + name, + ty.fallible_layout().ok(), + type_kind, + ty.is_const(), + ); + let item = Item::new( + with_id, + None, + None, + self.current_module, + ItemKind::Type(ty), + ); // Bypass all the validations in add_item explicitly. debug!("instantiate_template: inserting item: {:?}", item); @@ -1314,40 +1433,46 @@ impl<'ctx> BindgenContext<'ctx> { /// If we have already resolved the type for the given type declaration, /// return its `ItemId`. Otherwise, return `None`. - pub fn get_resolved_type(&self, - decl: &clang::CanonicalTypeDeclaration) - -> Option { + pub fn get_resolved_type( + &self, + decl: &clang::CanonicalTypeDeclaration, + ) -> Option { self.types .get(&TypeKey::Declaration(*decl.cursor())) .or_else(|| { - decl.cursor() - .usr() - .and_then(|usr| self.types.get(&TypeKey::USR(usr))) + decl.cursor().usr().and_then( + |usr| self.types.get(&TypeKey::USR(usr)), + ) }) .cloned() } /// Looks up for an already resolved type, either because it's builtin, or /// because we already have it in the map. - pub fn builtin_or_resolved_ty(&mut self, - with_id: ItemId, - parent_id: Option, - ty: &clang::Type, - location: Option) - -> Option { + pub fn builtin_or_resolved_ty( + &mut self, + with_id: ItemId, + parent_id: Option, + ty: &clang::Type, + location: Option, + ) -> Option { use clang_sys::{CXCursor_TypeAliasTemplateDecl, CXCursor_TypeRef}; - debug!("builtin_or_resolved_ty: {:?}, {:?}, {:?}", - ty, - location, - parent_id); + debug!( + "builtin_or_resolved_ty: {:?}, {:?}, {:?}", + ty, + location, + parent_id + ); if let Some(decl) = ty.canonical_declaration(location.as_ref()) { if let Some(id) = self.get_resolved_type(&decl) { - debug!("Already resolved ty {:?}, {:?}, {:?} {:?}", - id, - decl, - ty, - location); + debug!( + "Already resolved ty {:?}, {:?}, {:?} {:?}", + id, + decl, + ty, + location + ); // If the declaration already exists, then either: // // * the declaration is a template declaration of some sort, @@ -1356,8 +1481,9 @@ impl<'ctx> BindgenContext<'ctx> { // * we have already parsed and resolved this type, and // there's nothing left to do. if decl.cursor().is_template_like() && - *ty != decl.cursor().cur_type() && - location.is_some() { + *ty != decl.cursor().cur_type() && + location.is_some() + { let location = location.unwrap(); // For specialized type aliases, there's no way to get the @@ -1371,15 +1497,13 @@ impl<'ctx> BindgenContext<'ctx> { // // This is _tricky_, I know :( if decl.cursor().kind() == CXCursor_TypeAliasTemplateDecl && - !location.contains_cursor(CXCursor_TypeRef) && - ty.canonical_type().is_valid_and_exposed() { + !location.contains_cursor(CXCursor_TypeRef) && + ty.canonical_type().is_valid_and_exposed() + { return None; } - return self.instantiate_template(with_id, - id, - ty, - location) + return self.instantiate_template(with_id, id, ty, location) .or_else(|| Some(id)); } @@ -1399,22 +1523,25 @@ impl<'ctx> BindgenContext<'ctx> { /// We should probably make the constness tracking separate, so it doesn't /// bloat that much, but hey, we already bloat the heck out of builtin /// types. - pub fn build_ty_wrapper(&mut self, - with_id: ItemId, - wrapped_id: ItemId, - parent_id: Option, - ty: &clang::Type) - -> ItemId { + pub fn build_ty_wrapper( + &mut self, + with_id: ItemId, + wrapped_id: ItemId, + parent_id: Option, + 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 } @@ -1434,8 +1561,12 @@ impl<'ctx> BindgenContext<'ctx> { CXType_Bool => TypeKind::Int(IntKind::Bool), CXType_Int => TypeKind::Int(IntKind::Int), CXType_UInt => TypeKind::Int(IntKind::UInt), - CXType_Char_S => TypeKind::Int(IntKind::Char { is_signed: true }), - CXType_Char_U => TypeKind::Int(IntKind::Char { is_signed: false }), + CXType_Char_S => TypeKind::Int(IntKind::Char { + is_signed: true, + }), + CXType_Char_U => TypeKind::Int(IntKind::Char { + is_signed: false, + }), CXType_SChar => TypeKind::Int(IntKind::SChar), CXType_UChar => TypeKind::Int(IntKind::UChar), CXType_Short => TypeKind::Int(IntKind::Short), @@ -1453,8 +1584,8 @@ impl<'ctx> BindgenContext<'ctx> { CXType_LongDouble => TypeKind::Float(FloatKind::LongDouble), CXType_Float128 => TypeKind::Float(FloatKind::Float128), CXType_Complex => { - let float_type = ty.elem_type() - .expect("Not able to resolve complex type?"); + let float_type = + ty.elem_type().expect("Not able to resolve complex type?"); let float_kind = match float_type.kind() { CXType_Float => FloatKind::Float, CXType_Double => FloatKind::Double, @@ -1494,9 +1625,11 @@ impl<'ctx> BindgenContext<'ctx> { } /// Mark the macro named `macro_name` as parsed. - pub fn note_parsed_macro(&mut self, - id: Vec, - value: cexpr::expr::EvalResult) { + pub fn note_parsed_macro( + &mut self, + id: Vec, + value: cexpr::expr::EvalResult, + ) { self.parsed_macros.insert(id, value); } @@ -1513,17 +1646,21 @@ impl<'ctx> BindgenContext<'ctx> { pub fn replace(&mut self, name: &[String], potential_ty: ItemId) { match self.replacements.entry(name.into()) { hash_map::Entry::Vacant(entry) => { - debug!("Defining replacement for {:?} as {:?}", - name, - potential_ty); + debug!( + "Defining replacement for {:?} as {:?}", + name, + potential_ty + ); entry.insert(potential_ty); } hash_map::Entry::Occupied(occupied) => { - warn!("Replacement for {:?} already defined as {:?}; \ + warn!( + "Replacement for {:?} already defined as {:?}; \ ignoring duplicate replacement definition as {:?}", - name, - occupied.get(), - potential_ty); + name, + occupied.get(), + potential_ty + ); } } } @@ -1531,10 +1668,12 @@ impl<'ctx> BindgenContext<'ctx> { /// Is the item with the given `name` hidden? Or is the item with the given /// `name` and `id` replaced by another type, and effectively hidden? pub fn hidden_by_name(&self, path: &[String], id: ItemId) -> bool { - debug_assert!(self.in_codegen_phase(), - "You're not supposed to call this yet"); + debug_assert!( + self.in_codegen_phase(), + "You're not supposed to call this yet" + ); self.options.hidden_types.matches(&path[1..].join("::")) || - self.is_replaced_type(path, id) + self.is_replaced_type(path, id) } /// Has the item with the given `name` and `id` been replaced by another @@ -1548,8 +1687,10 @@ impl<'ctx> BindgenContext<'ctx> { /// Is the type with the given `name` marked as opaque? pub fn opaque_by_name(&self, path: &[String]) -> bool { - debug_assert!(self.in_codegen_phase(), - "You're not supposed to call this yet"); + debug_assert!( + self.in_codegen_phase(), + "You're not supposed to call this yet" + ); self.options.opaque_types.matches(&path[1..].join("::")) } @@ -1560,12 +1701,15 @@ impl<'ctx> BindgenContext<'ctx> { /// Tokenizes a namespace cursor in order to get the name and kind of the /// namespace. - fn tokenize_namespace(&self, - cursor: &clang::Cursor) - -> (Option, ModuleKind) { - assert_eq!(cursor.kind(), - ::clang_sys::CXCursor_Namespace, - "Be a nice person"); + fn tokenize_namespace( + &self, + cursor: &clang::Cursor, + ) -> (Option, ModuleKind) { + assert_eq!( + cursor.kind(), + ::clang_sys::CXCursor_Namespace, + "Be a nice person" + ); let tokens = match self.translation_unit.tokens(&cursor) { Some(tokens) => tokens, None => return (None, ModuleKind::Normal), @@ -1605,8 +1749,10 @@ impl<'ctx> BindgenContext<'ctx> { break; } _ => { - panic!("Unknown token while processing namespace: {:?}", - token); + panic!( + "Unknown token while processing namespace: {:?}", + token + ); } } } @@ -1628,11 +1774,13 @@ impl<'ctx> BindgenContext<'ctx> { let module_id = self.next_item_id(); let module = Module::new(module_name, kind); - let module = Item::new(module_id, - None, - None, - self.current_module, - ItemKind::Module(module)); + let module = Item::new( + module_id, + None, + None, + self.current_module, + ItemKind::Module(module), + ); self.modules.insert(cursor, module.id()); @@ -1644,7 +1792,8 @@ 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(&mut self, module_id: ItemId, cb: F) - where F: FnOnce(&mut Self), + where + F: FnOnce(&mut Self), { debug_assert!(self.resolve_item(module_id).kind().is_module(), "Wat"); @@ -1759,23 +1908,21 @@ impl<'ctx> BindgenContext<'ctx> { traversal::no_edges }; - let whitelisted = + let whitelisted = WhitelistedItemsTraversal::new( + self, + roots.clone(), + whitelisted_items_predicate, + ).collect::(); + + let codegen_items = if self.options().whitelist_recursively { WhitelistedItemsTraversal::new( self, roots.clone(), - whitelisted_items_predicate, - ).collect::(); - - let codegen_items = - if self.options().whitelist_recursively { - WhitelistedItemsTraversal::new( - self, - roots.clone(), - traversal::codegen_edges, - ).collect::() - } else { - whitelisted.clone() - }; + traversal::codegen_edges, + ).collect::() + } else { + whitelisted.clone() + }; self.whitelisted = Some(whitelisted); self.codegen_items = Some(codegen_items); @@ -1812,8 +1959,10 @@ impl<'ctx> BindgenContext<'ctx> { /// Look up whether the item with `id` can /// derive debug or not. pub fn lookup_item_id_can_derive_debug(&self, id: ItemId) -> bool { - assert!(self.in_codegen_phase(), - "We only compute can_derive_debug when we enter codegen"); + assert!( + self.in_codegen_phase(), + "We only compute can_derive_debug when we enter codegen" + ); // Look up the computed value for whether the item with `id` can // derive debug or not. @@ -1824,15 +1973,18 @@ impl<'ctx> BindgenContext<'ctx> { fn compute_cannot_derive_default(&mut self) { assert!(self.cannot_derive_default.is_none()); if self.options.derive_default { - self.cannot_derive_default = Some(analyze::(self)); + self.cannot_derive_default = + Some(analyze::(self)); } } /// Look up whether the item with `id` can /// derive default or not. pub fn lookup_item_id_can_derive_default(&self, id: ItemId) -> bool { - assert!(self.in_codegen_phase(), - "We only compute can_derive_default when we enter codegen"); + assert!( + self.in_codegen_phase(), + "We only compute can_derive_default when we enter codegen" + ); // Look up the computed value for whether the item with `id` can // derive default or not. @@ -1856,8 +2008,10 @@ impl<'ctx> BindgenContext<'ctx> { /// Look up whether the item with `id` can /// derive hash or not. pub fn lookup_item_id_can_derive_hash(&self, id: ItemId) -> bool { - assert!(self.in_codegen_phase(), - "We only compute can_derive_debug when we enter codegen"); + assert!( + self.in_codegen_phase(), + "We only compute can_derive_debug when we enter codegen" + ); // Look up the computed value for whether the item with `id` can // derive hash or not. @@ -1868,15 +2022,18 @@ impl<'ctx> BindgenContext<'ctx> { fn compute_cannot_derive_partialeq(&mut self) { assert!(self.cannot_derive_partialeq.is_none()); if self.options.derive_partialeq { - self.cannot_derive_partialeq = Some(analyze::(self)); + self.cannot_derive_partialeq = + Some(analyze::(self)); } } /// Look up whether the item with `id` can /// derive partialeq or not. pub fn lookup_item_id_can_derive_partialeq(&self, id: ItemId) -> bool { - assert!(self.in_codegen_phase(), - "We only compute can_derive_debug when we enter codegen"); + assert!( + self.in_codegen_phase(), + "We only compute can_derive_debug when we enter codegen" + ); // Look up the computed value for whether the item with `id` can // derive partialeq or not. @@ -1886,8 +2043,10 @@ impl<'ctx> BindgenContext<'ctx> { /// Look up whether the item with `id` can /// derive copy or not. pub fn lookup_item_id_can_derive_copy(&self, id: ItemId) -> bool { - assert!(self.in_codegen_phase(), - "We only compute can_derive_debug when we enter codegen"); + assert!( + self.in_codegen_phase(), + "We only compute can_derive_debug when we enter codegen" + ); // Look up the computed value for whether the item with `id` can // derive `Copy` or not. @@ -1898,13 +2057,16 @@ impl<'ctx> BindgenContext<'ctx> { /// Compute whether the type has type parameter in array. fn compute_has_type_param_in_array(&mut self) { assert!(self.has_type_param_in_array.is_none()); - self.has_type_param_in_array = Some(analyze::(self)); + self.has_type_param_in_array = + Some(analyze::(self)); } /// Look up whether the item with `id` has type parameter in array or not. pub fn lookup_item_id_has_type_param_in_array(&self, id: &ItemId) -> bool { - assert!(self.in_codegen_phase(), - "We only compute has array when we enter codegen"); + assert!( + self.in_codegen_phase(), + "We only compute has array when we enter codegen" + ); // Look up the computed value for whether the item with `id` has // type parameter in array or not. @@ -1964,13 +2126,15 @@ impl ItemResolver { let item = ctx.resolve_item(id); let ty_kind = item.as_type().map(|t| t.kind()); match ty_kind { - Some(&TypeKind::ResolvedTypeRef(next_id)) if self.through_type_refs => { + Some(&TypeKind::ResolvedTypeRef(next_id)) + if self.through_type_refs => { id = next_id; } // We intentionally ignore template aliases here, as they are // more complicated, and don't represent a simple renaming of // some type. - Some(&TypeKind::Alias(next_id)) if self.through_type_aliases => { + Some(&TypeKind::Alias(next_id)) + if self.through_type_aliases => { id = next_id; } _ => return item, @@ -2009,9 +2173,10 @@ impl PartialType { } impl TemplateParameters for PartialType { - fn self_template_params(&self, - _ctx: &BindgenContext) - -> Option> { + fn self_template_params( + &self, + _ctx: &BindgenContext, + ) -> Option> { // Maybe at some point we will eagerly parse named types, but for now we // don't and this information is unavailable. None diff --git a/src/ir/derive.rs b/src/ir/derive.rs index acbe20fdf2..ef5116941e 100644 --- a/src/ir/derive.rs +++ b/src/ir/derive.rs @@ -30,9 +30,7 @@ pub trait CanTriviallyDeriveDebug { pub trait CanDeriveCopy<'a> { /// Return `true` if `Copy` can be derived for this thing, `false` /// otherwise. - fn can_derive_copy(&'a self, - ctx: &'a BindgenContext) - -> bool; + fn can_derive_copy(&'a self, ctx: &'a BindgenContext) -> bool; } /// A trait that encapsulates the logic for whether or not we can derive `Copy`. @@ -53,12 +51,9 @@ pub trait CanTriviallyDeriveCopy { /// derive default or not, because of the limit rust has on 32 items as max in the /// array. pub trait CanDeriveDefault { - /// Return `true` if `Default` can be derived for this thing, `false` /// otherwise. - fn can_derive_default(&self, - ctx: &BindgenContext) - -> bool; + fn can_derive_default(&self, ctx: &BindgenContext) -> bool; } /// A trait that encapsulates the logic for whether or not we can derive `Default`. @@ -66,7 +61,6 @@ pub trait CanDeriveDefault { /// implementing this trait cannot use recursion or lookup result from fix point /// analysis. It's a helper trait for fix point analysis. pub trait CanTriviallyDeriveDefault { - /// Return `true` if `Default` can be derived for this thing, `false` /// otherwise. fn can_trivially_derive_default(&self) -> bool; @@ -80,12 +74,9 @@ pub trait CanTriviallyDeriveDefault { /// derive default or not, because of the limit rust has on 32 items as max in the /// array. pub trait CanDeriveHash { - /// Return `true` if `Default` can be derived for this thing, `false` /// otherwise. - fn can_derive_hash(&self, - ctx: &BindgenContext) - -> bool; + fn can_derive_hash(&self, ctx: &BindgenContext) -> bool; } /// A trait that encapsulates the logic for whether or not we can derive `PartialEq` @@ -96,12 +87,9 @@ pub trait CanDeriveHash { /// derive default or not, because of the limit rust has on 32 items as max in the /// array. pub trait CanDerivePartialEq { - /// Return `true` if `Default` can be derived for this thing, `false` /// otherwise. - fn can_derive_partialeq(&self, - ctx: &BindgenContext) - -> bool; + fn can_derive_partialeq(&self, ctx: &BindgenContext) -> bool; } /// A trait that encapsulates the logic for whether or not we can derive `Hash`. @@ -109,7 +97,6 @@ pub trait CanDerivePartialEq { /// implementing this trait cannot use recursion or lookup result from fix point /// analysis. It's a helper trait for fix point analysis. pub trait CanTriviallyDeriveHash { - /// Return `true` if `Hash` can be derived for this thing, `false` /// otherwise. fn can_trivially_derive_hash(&self) -> bool; @@ -120,7 +107,6 @@ pub trait CanTriviallyDeriveHash { /// implementing this trait cannot use recursion or lookup result from fix point /// analysis. It's a helper trait for fix point analysis. pub trait CanTriviallyDerivePartialEq { - /// Return `true` if `PartialEq` can be derived for this thing, `false` /// otherwise. fn can_trivially_derive_partialeq(&self) -> bool; diff --git a/src/ir/dot.rs b/src/ir/dot.rs index 61954c44c2..6d666f092d 100644 --- a/src/ir/dot.rs +++ b/src/ir/dot.rs @@ -11,16 +11,19 @@ use std::path::Path; pub trait DotAttributes { /// Write this thing's attributes to the given output. Each attribute must /// be its own `...`. - fn dot_attributes(&self, - ctx: &BindgenContext, - out: &mut W) - -> io::Result<()> - where W: io::Write; + fn dot_attributes( + &self, + ctx: &BindgenContext, + out: &mut W, + ) -> io::Result<()> + where + W: io::Write; } /// Write a graphviz dot file containing our IR. pub fn write_dot_file

(ctx: &BindgenContext, path: P) -> io::Result<()> - where P: AsRef, +where + P: AsRef, { let file = try!(File::create(path)); let mut dot_file = io::BufWriter::new(file); @@ -29,28 +32,34 @@ pub fn write_dot_file

(ctx: &BindgenContext, path: P) -> io::Result<()> let mut err: Option> = None; for (id, item) in ctx.items() { - try!(writeln!(&mut dot_file, - r#"{} [fontname="courier", label=<

unit.align{}
{}{:?}
{}{:?}
{} : {}{:?}
{} : {}{:?}
CompKind{:?}
has_non_type_template_paramstrue
has_non_type_template_paramstrue
is_forward_declarationtrue
is_forward_declarationtrue
"#, - id.as_usize())); + try!(writeln!( + &mut dot_file, + r#"{} [fontname="courier", label=<
"#, + id.as_usize() + )); try!(item.dot_attributes(ctx, &mut dot_file)); try!(writeln!(&mut dot_file, r#"
>];"#)); - item.trace(ctx, - &mut |sub_id: ItemId, edge_kind| { - if err.is_some() { - return; - } + item.trace( + ctx, + &mut |sub_id: ItemId, edge_kind| { + if err.is_some() { + return; + } - match writeln!(&mut dot_file, - "{} -> {} [label={:?}];", - id.as_usize(), - sub_id.as_usize(), - edge_kind) { - Ok(_) => {} - Err(e) => err = Some(Err(e)), - } - }, - &()); + match writeln!( + &mut dot_file, + "{} -> {} [label={:?}];", + id.as_usize(), + sub_id.as_usize(), + edge_kind + ) { + Ok(_) => {} + Err(e) => err = Some(Err(e)), + } + }, + &(), + ); if let Some(err) = err { return err; @@ -58,10 +67,12 @@ pub fn write_dot_file

(ctx: &BindgenContext, path: P) -> io::Result<()> if let Some(module) = item.as_module() { for child in module.children() { - try!(writeln!(&mut dot_file, - "{} -> {} [style=dotted]", - item.id().as_usize(), - child.as_usize())); + try!(writeln!( + &mut dot_file, + "{} -> {} [style=dotted]", + item.id().as_usize(), + child.as_usize() + )); } } } diff --git a/src/ir/enum_ty.rs b/src/ir/enum_ty.rs index 38de01d9c8..bcd56974ed 100644 --- a/src/ir/enum_ty.rs +++ b/src/ir/enum_ty.rs @@ -53,9 +53,10 @@ impl Enum { } /// Construct an enumeration from the given Clang type. - pub fn from_ty(ty: &clang::Type, - ctx: &mut BindgenContext) - -> Result { + pub fn from_ty( + ty: &clang::Type, + ctx: &mut BindgenContext, + ) -> Result { use clang_sys::*; debug!("Enum::from_ty {:?}", ty); @@ -64,20 +65,20 @@ impl Enum { } let declaration = ty.declaration().canonical(); - let repr = declaration.enum_type() - .and_then(|et| Item::from_ty(&et, declaration, None, ctx).ok()); + let repr = declaration.enum_type().and_then(|et| { + Item::from_ty(&et, declaration, None, ctx).ok() + }); let mut variants = vec![]; // Assume signedness since the default type by the C standard is an int. - let is_signed = - repr.and_then(|r| ctx.resolve_type(r).safe_canonical_type(ctx)) - .map_or(true, |ty| match *ty.kind() { - TypeKind::Int(ref int_kind) => int_kind.is_signed(), - ref other => { - panic!("Since when enums can be non-integers? {:?}", - other) - } - }); + let is_signed = repr.and_then( + |r| ctx.resolve_type(r).safe_canonical_type(ctx), + ).map_or(true, |ty| match *ty.kind() { + TypeKind::Int(ref int_kind) => int_kind.is_signed(), + ref other => { + panic!("Since when enums can be non-integers? {:?}", other) + } + }); let type_name = ty.spelling(); let type_name = if type_name.is_empty() { @@ -98,26 +99,28 @@ impl Enum { if let Some(val) = value { let name = cursor.spelling(); let custom_behavior = ctx.parse_callbacks() - .and_then(|t| { - t.enum_variant_behavior(type_name, &name, val) - }) + .and_then( + |t| t.enum_variant_behavior(type_name, &name, val), + ) .or_else(|| { - Annotations::new(&cursor) - .and_then(|anno| if anno.hide() { + Annotations::new(&cursor).and_then( + |anno| if anno.hide() { Some(EnumVariantCustomBehavior::Hide) - } else if - anno.constify_enum_variant() { + } else if anno.constify_enum_variant() { Some(EnumVariantCustomBehavior::Constify) } else { None - }) + }, + ) }); let comment = cursor.raw_comment(); - variants.push(EnumVariant::new(name, - comment, - val, - custom_behavior)); + variants.push(EnumVariant::new( + name, + comment, + val, + custom_behavior, + )); } } CXChildVisit_Continue @@ -126,15 +129,19 @@ impl Enum { } /// Whether the enum should be an constified enum module - pub fn is_constified_enum_module(&self, ctx: &BindgenContext, item: &Item) -> bool { + pub fn is_constified_enum_module( + &self, + ctx: &BindgenContext, + item: &Item, + ) -> bool { let name = item.canonical_name(ctx); let enum_ty = item.expect_type(); ctx.options().constified_enum_modules.matches(&name) || - (enum_ty.name().is_none() && - self.variants() - .iter() - .any(|v| ctx.options().constified_enum_modules.matches(&v.name()))) + (enum_ty.name().is_none() && + self.variants().iter().any(|v| { + ctx.options().constified_enum_modules.matches(&v.name()) + })) } } @@ -166,11 +173,12 @@ pub enum EnumVariantValue { impl EnumVariant { /// Construct a new enumeration variant from the given parts. - pub fn new(name: String, - comment: Option, - val: EnumVariantValue, - custom_behavior: Option) - -> Self { + pub fn new( + name: String, + comment: Option, + val: EnumVariantValue, + custom_behavior: Option, + ) -> Self { EnumVariant { name: name, comment: comment, @@ -192,14 +200,16 @@ impl EnumVariant { /// Returns whether this variant should be enforced to be a constant by code /// generation. pub fn force_constification(&self) -> bool { - self.custom_behavior - .map_or(false, |b| b == EnumVariantCustomBehavior::Constify) + self.custom_behavior.map_or(false, |b| { + b == EnumVariantCustomBehavior::Constify + }) } /// Returns whether the current variant should be hidden completely from the /// resulting rust enum. pub fn hidden(&self) -> bool { - self.custom_behavior - .map_or(false, |b| b == EnumVariantCustomBehavior::Hide) + self.custom_behavior.map_or(false, |b| { + b == EnumVariantCustomBehavior::Hide + }) } } diff --git a/src/ir/function.rs b/src/ir/function.rs index 241dcefe14..3cf48db7c6 100644 --- a/src/ir/function.rs +++ b/src/ir/function.rs @@ -8,7 +8,8 @@ use super::traversal::{EdgeKind, Trace, Tracer}; use super::ty::TypeKind; use clang; use clang_sys::{self, CXCallingConv}; -use ir::derive::{CanTriviallyDeriveDebug, CanTriviallyDeriveHash, CanTriviallyDerivePartialEq}; +use ir::derive::{CanTriviallyDeriveDebug, CanTriviallyDeriveHash, + CanTriviallyDerivePartialEq}; use parse::{ClangItemParser, ClangSubItemParser, ParseError, ParseResult}; use std::io; use syntax::abi; @@ -28,8 +29,12 @@ impl FunctionKind { fn from_cursor(cursor: &clang::Cursor) -> Option { Some(match cursor.kind() { clang_sys::CXCursor_FunctionDecl => FunctionKind::Function, - clang_sys::CXCursor_Constructor => FunctionKind::Method(MethodKind::Constructor), - clang_sys::CXCursor_Destructor => FunctionKind::Method(MethodKind::Destructor), + clang_sys::CXCursor_Constructor => FunctionKind::Method( + MethodKind::Constructor, + ), + clang_sys::CXCursor_Destructor => FunctionKind::Method( + MethodKind::Destructor, + ), clang_sys::CXCursor_CXXMethod => { if cursor.method_is_virtual() { FunctionKind::Method(MethodKind::Virtual) @@ -68,12 +73,13 @@ pub struct Function { impl Function { /// Construct a new function. - pub fn new(name: String, - mangled_name: Option, - sig: ItemId, - comment: Option, - kind: FunctionKind) - -> Self { + pub fn new( + name: String, + mangled_name: Option, + sig: ItemId, + comment: Option, + kind: FunctionKind, + ) -> Self { Function { name: name, mangled_name: mangled_name, @@ -105,17 +111,22 @@ impl Function { } impl DotAttributes for Function { - fn dot_attributes(&self, - _ctx: &BindgenContext, - out: &mut W) - -> io::Result<()> - where W: io::Write, + fn dot_attributes( + &self, + _ctx: &BindgenContext, + out: &mut W, + ) -> io::Result<()> + where + W: io::Write, { if let Some(ref mangled) = self.mangled_name { - let mangled: String = mangled.chars().flat_map(|c| c.escape_default()).collect(); - try!(writeln!(out, - "mangled name{}", - mangled)); + let mangled: String = + mangled.chars().flat_map(|c| c.escape_default()).collect(); + try!(writeln!( + out, + "mangled name{}", + mangled + )); } Ok(()) @@ -176,18 +187,23 @@ fn mangling_hack_if_needed(ctx: &BindgenContext, symbol: &mut String) { match symbol.chars().next().unwrap() { // Stripping leading underscore for all names on Darwin and // C linkage functions on Win32. - '_' => { symbol.remove(0); } + '_' => { + symbol.remove(0); + } // Stop Rust from prepending underscore for variables on Win32. - '?' => { symbol.insert(0, '\x01'); } + '?' => { + symbol.insert(0, '\x01'); + } _ => {} } } } /// Get the mangled name for the cursor's referent. -pub fn cursor_mangling(ctx: &BindgenContext, - cursor: &clang::Cursor) - -> Option { +pub fn cursor_mangling( + ctx: &BindgenContext, + cursor: &clang::Cursor, +) -> Option { use clang_sys; if !ctx.options().enable_mangling { return None; @@ -246,11 +262,12 @@ pub fn cursor_mangling(ctx: &BindgenContext, impl FunctionSig { /// Construct a new function signature. - pub fn new(return_type: ItemId, - arguments: Vec<(Option, ItemId)>, - is_variadic: bool, - abi: Abi) - -> Self { + pub fn new( + return_type: ItemId, + arguments: Vec<(Option, ItemId)>, + is_variadic: bool, + abi: Abi, + ) -> Self { FunctionSig { return_type: return_type, argument_types: arguments, @@ -260,10 +277,11 @@ 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 { + pub fn from_ty( + ty: &clang::Type, + cursor: &clang::Cursor, + ctx: &mut BindgenContext, + ) -> Result { use clang_sys::*; debug!("FunctionSig::from_ty {:?} {:?}", ty, cursor); @@ -292,7 +310,8 @@ impl FunctionSig { CXCursor_ObjCClassMethodDecl => { // For CXCursor_FunctionDecl, cursor.args() is the reliable way // to get parameter names and types. - cursor.args() + cursor + .args() .unwrap() .iter() .map(|arg| { @@ -328,7 +347,8 @@ impl FunctionSig { let is_constructor = cursor.kind() == CXCursor_Constructor; let is_destructor = cursor.kind() == CXCursor_Destructor; if (is_constructor || is_destructor || is_method) && - cursor.lexical_parent() != cursor.semantic_parent() { + cursor.lexical_parent() != cursor.semantic_parent() + { // Only parse constructors once. return Err(ParseError::Continue); } @@ -352,10 +372,11 @@ impl FunctionSig { } let ty_ret_type = if cursor.kind() == CXCursor_ObjCInstanceMethodDecl || - cursor.kind() == CXCursor_ObjCClassMethodDecl { - try!(ty.ret_type() - .or_else(|| cursor.ret_type()) - .ok_or(ParseError::Continue)) + cursor.kind() == CXCursor_ObjCClassMethodDecl + { + try!(ty.ret_type().or_else(|| cursor.ret_type()).ok_or( + ParseError::Continue, + )) } else { try!(ty.ret_type().ok_or(ParseError::Continue)) }; @@ -395,9 +416,10 @@ impl FunctionSig { } impl ClangSubItemParser for Function { - fn parse(cursor: clang::Cursor, - context: &mut BindgenContext) - -> Result, ParseError> { + fn parse( + cursor: clang::Cursor, + context: &mut BindgenContext, + ) -> Result, ParseError> { use clang_sys::*; let kind = match FunctionKind::from_cursor(&cursor) { @@ -417,13 +439,15 @@ impl ClangSubItemParser for Function { } if !context.options().generate_inline_functions && - cursor.is_inlined_function() { + cursor.is_inlined_function() + { return Err(ParseError::Continue); } let linkage = cursor.linkage(); if linkage != CXLinkage_External && - linkage != CXLinkage_UniqueExternal { + linkage != CXLinkage_UniqueExternal + { return Err(ParseError::Continue); } @@ -464,7 +488,8 @@ impl Trace for FunctionSig { type Extra = (); fn trace(&self, _: &BindgenContext, tracer: &mut T, _: &()) - where T: Tracer, + where + T: Tracer, { tracer.visit_kind(self.return_type(), EdgeKind::FunctionReturn); diff --git a/src/ir/int.rs b/src/ir/int.rs index a4cb8bc77d..b7f0f0c54d 100644 --- a/src/ir/int.rs +++ b/src/ir/int.rs @@ -93,9 +93,13 @@ impl IntKind { SChar | Short | Int | Long | LongLong | I8 | I16 | I32 | I64 | I128 => true, - Char { is_signed } => is_signed, + Char { + is_signed, + } => is_signed, - Custom { is_signed, .. } => is_signed, + Custom { + is_signed, .. + } => is_signed, } } @@ -105,7 +109,14 @@ impl IntKind { pub fn known_size(&self) -> Option { use self::IntKind::*; Some(match *self { - Bool | UChar | SChar | U8 | I8 | Char { .. } => 1, + Bool | + UChar | + SChar | + U8 | + I8 | + Char { + .. + } => 1, U16 | I16 => 2, U32 | I32 => 4, U64 | I64 => 8, diff --git a/src/ir/item.rs b/src/ir/item.rs index 4109b5e879..dfb2697ddb 100644 --- a/src/ir/item.rs +++ b/src/ir/item.rs @@ -1,30 +1,30 @@ //! Bindgen's core intermediate representation type. -use super::super::codegen::CONSTIFIED_ENUM_MODULE_REPR_NAME; +use super::analysis::HasVtable; use super::annotations::Annotations; use super::comment; use super::comp::MethodKind; use super::context::{BindgenContext, ItemId, PartialType}; -use super::derive::{CanDeriveCopy, CanDeriveDebug, CanDeriveDefault, CanDeriveHash, - CanDerivePartialEq}; +use super::derive::{CanDeriveCopy, CanDeriveDebug, CanDeriveDefault, + CanDeriveHash, CanDerivePartialEq}; use super::dot::DotAttributes; use super::function::{Function, FunctionKind}; use super::item_kind::ItemKind; use super::layout::Opaque; use super::module::Module; +use super::super::codegen::CONSTIFIED_ENUM_MODULE_REPR_NAME; use super::template::{AsTemplateParam, TemplateParameters}; use super::traversal::{EdgeKind, Trace, Tracer}; use super::ty::{Type, TypeKind}; -use super::analysis::HasVtable; use clang; use clang_sys; use parse::{ClangItemParser, ClangSubItemParser, ParseError, ParseResult}; +use regex; use std::cell::{Cell, RefCell}; use std::collections::BTreeSet; use std::fmt::Write; use std::io; use std::iter; -use regex; /// A trait to get the canonical name from an item. /// @@ -57,9 +57,10 @@ pub trait ItemCanonicalPath { /// Get the namespace-aware canonical path for this item. This means that if /// namespaces are disabled, you'll get a single item, and otherwise you get /// the whole path. - fn namespace_aware_canonical_path(&self, - ctx: &BindgenContext) - -> Vec; + fn namespace_aware_canonical_path( + &self, + ctx: &BindgenContext, + ) -> Vec; /// Get the canonical path for this item. fn canonical_path(&self, ctx: &BindgenContext) -> Vec; @@ -86,9 +87,10 @@ pub trait HasTypeParamInArray { /// up to (but not including) the implicit root module. pub trait ItemAncestors { /// Get an iterable over this item's ancestors. - fn ancestors<'a, 'b>(&self, - ctx: &'a BindgenContext<'b>) - -> ItemAncestorsIter<'a, 'b>; + fn ancestors<'a, 'b>( + &self, + ctx: &'a BindgenContext<'b>, + ) -> ItemAncestorsIter<'a, 'b>; } cfg_if! { @@ -113,7 +115,8 @@ cfg_if! { /// An iterator over an item and its ancestors. pub struct ItemAncestorsIter<'a, 'b> - where 'b: 'a, +where + 'b: 'a, { item: ItemId, ctx: &'a BindgenContext<'b>, @@ -121,7 +124,8 @@ pub struct ItemAncestorsIter<'a, 'b> } impl<'a, 'b> ItemAncestorsIter<'a, 'b> - where 'b: 'a, +where + 'b: 'a, { fn new(ctx: &'a BindgenContext<'b>, item: ItemId) -> Self { ItemAncestorsIter { @@ -133,7 +137,8 @@ impl<'a, 'b> ItemAncestorsIter<'a, 'b> } impl<'a, 'b> Iterator for ItemAncestorsIter<'a, 'b> - where 'b: 'a, +where + 'b: 'a, { type Item = ItemId; @@ -156,7 +161,11 @@ impl<'a, 'b> Iterator for ItemAncestorsIter<'a, 'b> impl AsTemplateParam for ItemId { type Extra = (); - fn as_template_param(&self, ctx: &BindgenContext, _: &()) -> Option { + fn as_template_param( + &self, + ctx: &BindgenContext, + _: &(), + ) -> Option { ctx.resolve_item(*self).as_template_param(ctx, &()) } } @@ -164,7 +173,11 @@ impl AsTemplateParam for ItemId { impl AsTemplateParam for Item { type Extra = (); - fn as_template_param(&self, ctx: &BindgenContext, _: &()) -> Option { + fn as_template_param( + &self, + ctx: &BindgenContext, + _: &(), + ) -> Option { self.kind.as_template_param(ctx, self) } } @@ -172,7 +185,11 @@ impl AsTemplateParam for Item { impl AsTemplateParam for ItemKind { type Extra = Item; - fn as_template_param(&self, ctx: &BindgenContext, item: &Item) -> Option { + fn as_template_param( + &self, + ctx: &BindgenContext, + item: &Item, + ) -> Option { match *self { ItemKind::Type(ref ty) => ty.as_template_param(ctx, item), ItemKind::Module(..) | @@ -185,40 +202,49 @@ impl AsTemplateParam for ItemKind { // Pure convenience impl ItemCanonicalName for ItemId { fn canonical_name(&self, ctx: &BindgenContext) -> String { - debug_assert!(ctx.in_codegen_phase(), - "You're not supposed to call this yet"); + debug_assert!( + ctx.in_codegen_phase(), + "You're not supposed to call this yet" + ); ctx.resolve_item(*self).canonical_name(ctx) } } impl ItemCanonicalPath for ItemId { - fn namespace_aware_canonical_path(&self, - ctx: &BindgenContext) - -> Vec { - debug_assert!(ctx.in_codegen_phase(), - "You're not supposed to call this yet"); + fn namespace_aware_canonical_path( + &self, + ctx: &BindgenContext, + ) -> Vec { + debug_assert!( + ctx.in_codegen_phase(), + "You're not supposed to call this yet" + ); ctx.resolve_item(*self).namespace_aware_canonical_path(ctx) } fn canonical_path(&self, ctx: &BindgenContext) -> Vec { - debug_assert!(ctx.in_codegen_phase(), - "You're not supposed to call this yet"); + debug_assert!( + ctx.in_codegen_phase(), + "You're not supposed to call this yet" + ); ctx.resolve_item(*self).canonical_path(ctx) } } impl ItemAncestors for ItemId { - fn ancestors<'a, 'b>(&self, - ctx: &'a BindgenContext<'b>) - -> ItemAncestorsIter<'a, 'b> { + fn ancestors<'a, 'b>( + &self, + ctx: &'a BindgenContext<'b>, + ) -> ItemAncestorsIter<'a, 'b> { ItemAncestorsIter::new(ctx, *self) } } impl ItemAncestors for Item { - fn ancestors<'a, 'b>(&self, - ctx: &'a BindgenContext<'b>) - -> ItemAncestorsIter<'a, 'b> { + fn ancestors<'a, 'b>( + &self, + ctx: &'a BindgenContext<'b>, + ) -> ItemAncestorsIter<'a, 'b> { self.id().ancestors(ctx) } } @@ -227,7 +253,8 @@ impl Trace for ItemId { type Extra = (); fn trace(&self, ctx: &BindgenContext, tracer: &mut T, extra: &()) - where T: Tracer, + where + T: Tracer, { ctx.resolve_item(*self).trace(ctx, tracer, extra); } @@ -237,7 +264,8 @@ impl Trace for Item { type Extra = (); fn trace(&self, ctx: &BindgenContext, tracer: &mut T, _extra: &()) - where T: Tracer, + where + T: Tracer, { // Even if this item is blacklisted/hidden, we want to trace it. It is // traversal iterators' consumers' responsibility to filter items as @@ -252,7 +280,8 @@ impl Trace for Item { // don't want to stop collecting types even though they may be // opaque. if ty.should_be_traced_unconditionally() || - !self.is_opaque(ctx, &()) { + !self.is_opaque(ctx, &()) + { ty.trace(ctx, tracer, self); } } @@ -279,13 +308,15 @@ impl Trace for Item { impl CanDeriveDebug for Item { fn can_derive_debug(&self, ctx: &BindgenContext) -> bool { - ctx.options().derive_debug && ctx.lookup_item_id_can_derive_debug(self.id()) + ctx.options().derive_debug && + ctx.lookup_item_id_can_derive_debug(self.id()) } } impl CanDeriveDefault for Item { fn can_derive_default(&self, ctx: &BindgenContext) -> bool { - ctx.options().derive_default && ctx.lookup_item_id_can_derive_default(self.id()) + ctx.options().derive_default && + ctx.lookup_item_id_can_derive_default(self.id()) } } @@ -297,13 +328,15 @@ impl<'a> CanDeriveCopy<'a> for Item { impl CanDeriveHash for Item { fn can_derive_hash(&self, ctx: &BindgenContext) -> bool { - ctx.options().derive_hash && ctx.lookup_item_id_can_derive_hash(self.id()) + ctx.options().derive_hash && + ctx.lookup_item_id_can_derive_hash(self.id()) } } impl CanDerivePartialEq for Item { fn can_derive_partialeq(&self, ctx: &BindgenContext) -> bool { - ctx.options().derive_partialeq && ctx.lookup_item_id_can_derive_partialeq(self.id()) + ctx.options().derive_partialeq && + ctx.lookup_item_id_can_derive_partialeq(self.id()) } } @@ -370,12 +403,13 @@ impl AsRef for Item { impl Item { /// Construct a new `Item`. - pub fn new(id: ItemId, - comment: Option, - annotations: Option, - parent_id: ItemId, - kind: ItemKind) - -> Self { + pub fn new( + id: ItemId, + comment: Option, + annotations: Option, + parent_id: ItemId, + kind: ItemKind, + ) -> Self { debug_assert!(id != parent_id || kind.is_module()); Item { id: id, @@ -390,10 +424,11 @@ impl Item { } /// Construct a new opaque item type. - pub fn new_opaque_type(with_id: ItemId, - ty: &clang::Type, - ctx: &mut BindgenContext) - -> ItemId { + pub fn new_opaque_type( + with_id: ItemId, + ty: &clang::Type, + ctx: &mut BindgenContext, + ) -> ItemId { let ty = Opaque::from_clang_ty(ty); let kind = ItemKind::Type(ty); let parent = ctx.root_module(); @@ -508,7 +543,8 @@ impl Item { // FIXME: Workaround for some types falling behind when parsing weird // stl classes, for example. if ctx.options().enable_cxx_namespaces && self.kind().is_module() && - self.id() != ctx.root_module() { + self.id() != ctx.root_module() + { return false; } @@ -522,7 +558,8 @@ impl Item { if parent_item.id() == ctx.root_module() { return true; } else if ctx.options().enable_cxx_namespaces || - !parent_item.kind().is_module() { + !parent_item.kind().is_module() + { return false; } @@ -565,10 +602,12 @@ impl Item { /// /// This may be due to either annotations or to other kind of configuration. pub fn is_hidden(&self, ctx: &BindgenContext) -> bool { - debug_assert!(ctx.in_codegen_phase(), - "You're not supposed to call this yet"); + debug_assert!( + ctx.in_codegen_phase(), + "You're not supposed to call this yet" + ); self.annotations.hide() || - ctx.hidden_by_name(&self.canonical_path(ctx), self.id) + ctx.hidden_by_name(&self.canonical_path(ctx), self.id) } /// Is this a reference to another type? @@ -585,9 +624,10 @@ impl Item { } /// Take out item NameOptions - pub fn name<'item, 'ctx>(&'item self, - ctx: &'item BindgenContext<'ctx>) - -> NameOptions<'item, 'ctx> { + pub fn name<'item, 'ctx>( + &'item self, + ctx: &'item BindgenContext<'ctx>, + ) -> NameOptions<'item, 'ctx> { NameOptions::new(self, ctx) } @@ -631,16 +671,21 @@ impl Item { } /// Helper function for full_disambiguated_name - fn push_disambiguated_name(&self, ctx: &BindgenContext, to: &mut String, level: u8) { + fn push_disambiguated_name( + &self, + ctx: &BindgenContext, + to: &mut String, + level: u8, + ) { to.push_str(&self.canonical_name(ctx)); if let ItemKind::Type(ref ty) = *self.kind() { if let TypeKind::TemplateInstantiation(ref inst) = *ty.kind() { to.push_str(&format!("_open{}_", level)); for arg in inst.template_arguments() { arg.into_resolver() - .through_type_refs() - .resolve(ctx) - .push_disambiguated_name(ctx, to, level + 1); + .through_type_refs() + .resolve(ctx) + .push_disambiguated_name(ctx, to, level + 1); to.push_str("_"); } to.push_str(&format!("close{}", level)); @@ -694,11 +739,9 @@ impl Item { match *self.kind() { ItemKind::Var(ref var) => var.name().to_owned(), ItemKind::Module(ref module) => { - module.name() - .map(ToOwned::to_owned) - .unwrap_or_else(|| { - format!("_bindgen_mod_{}", self.exposed_id(ctx)) - }) + module.name().map(ToOwned::to_owned).unwrap_or_else(|| { + format!("_bindgen_mod_{}", self.exposed_id(ctx)) + }) } ItemKind::Type(ref ty) => { ty.sanitized_name(ctx).map(Into::into).unwrap_or_else(|| { @@ -730,10 +773,11 @@ impl Item { /// /// This name should be derived from the immutable state contained in the /// type and the parent chain, since it should be consistent. - pub fn real_canonical_name(&self, - ctx: &BindgenContext, - opt: &NameOptions) - -> String { + pub fn real_canonical_name( + &self, + ctx: &BindgenContext, + opt: &NameOptions, + ) -> String { let target = ctx.resolve_item(self.name_target(ctx)); // Short-circuit if the target has an override, and just use that. @@ -753,7 +797,8 @@ impl Item { } // Concatenate this item's ancestors' names together. - let mut names: Vec<_> = target.parent_id() + let mut names: Vec<_> = target + .parent_id() .ancestors(ctx) .filter(|id| *id != ctx.root_module()) .take_while(|id| { @@ -763,7 +808,9 @@ impl Item { }) .filter(|id| { if !ctx.options().conservative_inline_namespaces { - if let ItemKind::Module(ref module) = *ctx.resolve_item(*id).kind() { + if let ItemKind::Module(ref module) = + *ctx.resolve_item(*id).kind() + { return !module.is_inline(); } } @@ -868,9 +915,13 @@ impl Item { ItemKind::Function(ref f) => { match f.kind() { FunctionKind::Function => cc.functions, - FunctionKind::Method(MethodKind::Constructor) => cc.constructors, + FunctionKind::Method(MethodKind::Constructor) => { + cc.constructors + } FunctionKind::Method(MethodKind::Destructor) | - FunctionKind::Method(MethodKind::VirtualDestructor) => cc.destructors, + FunctionKind::Method(MethodKind::VirtualDestructor) => { + cc.destructors + } FunctionKind::Method(MethodKind::Static) | FunctionKind::Method(MethodKind::Normal) | FunctionKind::Method(MethodKind::Virtual) => cc.methods, @@ -884,8 +935,10 @@ impl IsOpaque for ItemId { type Extra = (); fn is_opaque(&self, ctx: &BindgenContext, _: &()) -> bool { - debug_assert!(ctx.in_codegen_phase(), - "You're not supposed to call this yet"); + debug_assert!( + ctx.in_codegen_phase(), + "You're not supposed to call this yet" + ); ctx.resolve_item(*self).is_opaque(ctx, &()) } } @@ -894,8 +947,10 @@ impl IsOpaque for Item { type Extra = (); fn is_opaque(&self, ctx: &BindgenContext, _: &()) -> bool { - debug_assert!(ctx.in_codegen_phase(), - "You're not supposed to call this yet"); + debug_assert!( + ctx.in_codegen_phase(), + "You're not supposed to call this yet" + ); self.annotations.opaque() || self.as_type().map_or(false, |ty| ty.is_opaque(ctx, self)) || ctx.opaque_by_name(&self.canonical_path(ctx)) @@ -916,16 +971,20 @@ impl HasVtable for Item { impl HasTypeParamInArray for ItemId { fn has_type_param_in_array(&self, ctx: &BindgenContext) -> bool { - debug_assert!(ctx.in_codegen_phase(), - "You're not supposed to call this yet"); + debug_assert!( + ctx.in_codegen_phase(), + "You're not supposed to call this yet" + ); ctx.lookup_item_id_has_type_param_in_array(self) } } impl HasTypeParamInArray for Item { fn has_type_param_in_array(&self, ctx: &BindgenContext) -> bool { - debug_assert!(ctx.in_codegen_phase(), - "You're not supposed to call this yet"); + debug_assert!( + ctx.in_codegen_phase(), + "You're not supposed to call this yet" + ); ctx.lookup_item_id_has_type_param_in_array(&self.id()) } } @@ -934,17 +993,21 @@ impl HasTypeParamInArray for Item { pub type ItemSet = BTreeSet; impl DotAttributes for Item { - fn dot_attributes(&self, - ctx: &BindgenContext, - out: &mut W) - -> io::Result<()> - where W: io::Write, + fn dot_attributes( + &self, + ctx: &BindgenContext, + out: &mut W, + ) -> io::Result<()> + where + W: io::Write, { - try!(writeln!(out, - "{:?} + try!(writeln!( + out, + "{:?} name{}", - self.id, - self.name(ctx).get())); + self.id, + self.name(ctx).get() + )); if self.is_opaque(ctx, &()) { writeln!(out, "opaquetrue")?; @@ -955,26 +1018,30 @@ impl DotAttributes for Item { } impl TemplateParameters for ItemId { - fn self_template_params(&self, - ctx: &BindgenContext) - -> Option> { - ctx.resolve_item_fallible(*self) - .and_then(|item| item.self_template_params(ctx)) + fn self_template_params( + &self, + ctx: &BindgenContext, + ) -> Option> { + ctx.resolve_item_fallible(*self).and_then(|item| { + item.self_template_params(ctx) + }) } } impl TemplateParameters for Item { - fn self_template_params(&self, - ctx: &BindgenContext) - -> Option> { + fn self_template_params( + &self, + ctx: &BindgenContext, + ) -> Option> { self.kind.self_template_params(ctx) } } impl TemplateParameters for ItemKind { - fn self_template_params(&self, - ctx: &BindgenContext) - -> Option> { + fn self_template_params( + &self, + ctx: &BindgenContext, + ) -> Option> { match *self { ItemKind::Type(ref ty) => ty.self_template_params(ctx), // If we start emitting bindings to explicitly instantiated @@ -988,13 +1055,14 @@ impl TemplateParameters for ItemKind { } // An utility function to handle recursing inside nested types. -fn visit_child(cur: clang::Cursor, - id: ItemId, - ty: &clang::Type, - parent_id: Option, - ctx: &mut BindgenContext, - result: &mut Result) - -> clang_sys::CXChildVisitResult { +fn visit_child( + cur: clang::Cursor, + id: ItemId, + ty: &clang::Type, + parent_id: Option, + ctx: &mut BindgenContext, + result: &mut Result, +) -> clang_sys::CXChildVisitResult { use clang_sys::*; if result.is_ok() { return CXChildVisit_Break; @@ -1013,10 +1081,11 @@ fn visit_child(cur: clang::Cursor, } 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 | @@ -1029,17 +1098,20 @@ impl ClangItemParser for Item { let ty = Type::new(None, None, kind, is_const); let id = ctx.next_item_id(); let module = ctx.root_module(); - ctx.add_item(Item::new(id, None, None, module, ItemKind::Type(ty)), - None, - None); + ctx.add_item( + Item::new(id, None, None, module, ItemKind::Type(ty)), + None, + None, + ); id } - fn parse(cursor: clang::Cursor, - parent_id: Option, - ctx: &mut BindgenContext) - -> Result { + fn parse( + cursor: clang::Cursor, + parent_id: Option, + ctx: &mut BindgenContext, + ) -> Result { use ir::function::Function; use ir::module::Module; use ir::var::Var; @@ -1093,10 +1165,12 @@ impl ClangItemParser for Item { // twice, handle them separately. { let applicable_cursor = cursor.definition().unwrap_or(cursor); - match Item::from_ty(&applicable_cursor.cur_type(), - applicable_cursor, - parent_id, - ctx) { + match Item::from_ty( + &applicable_cursor.cur_type(), + applicable_cursor, + parent_id, + ctx, + ) { Ok(ty) => return Ok(ty), Err(ParseError::Recurse) => return Err(ParseError::Recurse), Err(ParseError::Continue) => {} @@ -1116,17 +1190,21 @@ impl ClangItemParser for Item { CXCursor_UsingDirective | CXCursor_StaticAssert | CXCursor_InclusionDirective => { - debug!("Unhandled cursor kind {:?}: {:?}", - cursor.kind(), - cursor); + debug!( + "Unhandled cursor kind {:?}: {:?}", + cursor.kind(), + cursor + ); } _ => { // ignore toplevel operator overloads let spelling = cursor.spelling(); if !spelling.starts_with("operator") { - error!("Unhandled cursor kind {:?}: {:?}", - cursor.kind(), - cursor); + error!( + "Unhandled cursor kind {:?}: {:?}", + cursor.kind(), + cursor + ); } } } @@ -1135,11 +1213,12 @@ impl ClangItemParser for Item { } } - fn from_ty_or_ref(ty: clang::Type, - location: clang::Cursor, - parent_id: Option, - ctx: &mut BindgenContext) - -> ItemId { + fn from_ty_or_ref( + ty: clang::Type, + location: clang::Cursor, + parent_id: Option, + ctx: &mut BindgenContext, + ) -> ItemId { let id = ctx.next_item_id(); Self::from_ty_or_ref_with_id(id, ty, location, parent_id, ctx) } @@ -1154,34 +1233,41 @@ impl ClangItemParser for Item { /// /// Typerefs are resolved once parsing is completely done, see /// `BindgenContext::resolve_typerefs`. - fn from_ty_or_ref_with_id(potential_id: ItemId, - ty: clang::Type, - location: clang::Cursor, - parent_id: Option, - ctx: &mut BindgenContext) - -> ItemId { - debug!("from_ty_or_ref_with_id: {:?} {:?}, {:?}, {:?}", - potential_id, - ty, - location, - parent_id); + fn from_ty_or_ref_with_id( + potential_id: ItemId, + ty: clang::Type, + location: clang::Cursor, + parent_id: Option, + ctx: &mut BindgenContext, + ) -> ItemId { + debug!( + "from_ty_or_ref_with_id: {:?} {:?}, {:?}, {:?}", + potential_id, + ty, + location, + parent_id + ); if ctx.collected_typerefs() { debug!("refs already collected, resolving directly"); - return Item::from_ty_with_id(potential_id, - &ty, - location, - parent_id, - ctx) - .unwrap_or_else(|_| { - Item::new_opaque_type(potential_id, &ty, ctx) - }); + return Item::from_ty_with_id( + potential_id, + &ty, + location, + parent_id, + ctx, + ).unwrap_or_else( + |_| Item::new_opaque_type(potential_id, &ty, ctx), + ); } - if let Some(ty) = ctx.builtin_or_resolved_ty(potential_id, - parent_id, - &ty, - Some(location)) { + if let Some(ty) = ctx.builtin_or_resolved_ty( + potential_id, + parent_id, + &ty, + Some(location), + ) + { debug!("{:?} already resolved: {:?}", ty, location); return ty; } @@ -1191,24 +1277,26 @@ impl ClangItemParser for Item { let is_const = ty.is_const(); let kind = TypeKind::UnresolvedTypeRef(ty, location, parent_id); let current_module = ctx.current_module(); - ctx.add_item(Item::new(potential_id, - None, - None, - parent_id.unwrap_or(current_module), - ItemKind::Type(Type::new(None, - None, - kind, - is_const))), - Some(clang::Cursor::null()), - None); + ctx.add_item( + Item::new( + potential_id, + None, + None, + parent_id.unwrap_or(current_module), + ItemKind::Type(Type::new(None, None, kind, is_const)), + ), + Some(clang::Cursor::null()), + None, + ); potential_id } - fn from_ty(ty: &clang::Type, - location: clang::Cursor, - parent_id: Option, - ctx: &mut BindgenContext) - -> Result { + fn from_ty( + ty: &clang::Type, + location: clang::Cursor, + parent_id: Option, + ctx: &mut BindgenContext, + ) -> Result { let id = ctx.next_item_id(); Item::from_ty_with_id(id, ty, location, parent_id, ctx) } @@ -1221,30 +1309,35 @@ impl ClangItemParser for Item { /// critical some times to obtain information, an optional parent item id, /// that will, if it's `None`, become the current module id, and the /// context. - fn from_ty_with_id(id: ItemId, - ty: &clang::Type, - location: clang::Cursor, - parent_id: Option, - ctx: &mut BindgenContext) - -> Result { + fn from_ty_with_id( + id: ItemId, + ty: &clang::Type, + location: clang::Cursor, + parent_id: Option, + ctx: &mut BindgenContext, + ) -> Result { use clang_sys::*; - debug!("Item::from_ty_with_id: {:?}\n\ + debug!( + "Item::from_ty_with_id: {:?}\n\ \tty = {:?},\n\ \tlocation = {:?}", - id, - ty, - location); + id, + ty, + location + ); if ty.kind() == clang_sys::CXType_Unexposed || - location.cur_type().kind() == clang_sys::CXType_Unexposed { + location.cur_type().kind() == clang_sys::CXType_Unexposed + { if ty.is_associated_type() || - location.cur_type().is_associated_type() { + location.cur_type().is_associated_type() + { return Ok(Item::new_opaque_type(id, ty, ctx)); } - if let Some(id) = Item::named_type(Some(id), location, ctx) { + if let Some(id) = Item::type_param(Some(id), location, ctx) { return Ok(id); } } @@ -1254,10 +1347,9 @@ impl ClangItemParser for Item { decl.definition().unwrap_or(decl) }; - let comment = decl.raw_comment() - .or_else(|| location.raw_comment()); - let annotations = Annotations::new(&decl) - .or_else(|| Annotations::new(&location)); + let comment = decl.raw_comment().or_else(|| location.raw_comment()); + let annotations = + Annotations::new(&decl).or_else(|| Annotations::new(&location)); if let Some(ref annotations) = annotations { if let Some(ref replaced) = annotations.use_instead_of() { @@ -1265,8 +1357,13 @@ impl ClangItemParser for Item { } } - if let Some(ty) = - ctx.builtin_or_resolved_ty(id, parent_id, ty, Some(location)) { + if let Some(ty) = ctx.builtin_or_resolved_ty( + id, + parent_id, + ty, + Some(location), + ) + { return Ok(ty); } @@ -1274,8 +1371,7 @@ 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.kind() == - CXCursor_ClassTemplate { + } else if location.kind() == CXCursor_ClassTemplate { valid_decl = true; location } else { @@ -1283,9 +1379,12 @@ impl ClangItemParser for Item { }; if valid_decl { - if let Some(partial) = ctx.currently_parsed_types() - .iter() - .find(|ty| *ty.decl() == declaration_to_look_for) { + if let Some(partial) = ctx.currently_parsed_types().iter().find( + |ty| { + *ty.decl() == declaration_to_look_for + }, + ) + { debug!("Avoiding recursion parsing type: {:?}", ty); return Ok(partial.id()); } @@ -1302,13 +1401,17 @@ impl ClangItemParser for Item { let ret = match result { Ok(ParseResult::AlreadyResolved(ty)) => Ok(ty), Ok(ParseResult::New(item, declaration)) => { - ctx.add_item(Item::new(id, - comment, - annotations, - relevant_parent_id, - ItemKind::Type(item)), - declaration, - Some(location)); + ctx.add_item( + Item::new( + id, + comment, + annotations, + relevant_parent_id, + ItemKind::Type(item), + ), + declaration, + Some(location), + ); Ok(id) } Err(ParseError::Continue) => Err(ParseError::Continue), @@ -1331,8 +1434,8 @@ impl ClangItemParser for Item { }); if valid_decl { - let partial_ty = PartialType::new(declaration_to_look_for, - id); + let partial_ty = + PartialType::new(declaration_to_look_for, id); ctx.begin_parsing(partial_ty); } @@ -1342,11 +1445,13 @@ impl ClangItemParser for Item { // // This is what happens with some template members, for example. if let Err(ParseError::Recurse) = result { - warn!("Unknown type, assuming named template type: \ + warn!( + "Unknown type, assuming named template type: \ id = {:?}; spelling = {}", - id, - ty.spelling()); - Item::named_type(Some(id), location, ctx) + id, + ty.spelling() + ); + Item::type_param(Some(id), location, ctx) .map(Ok) .unwrap_or(Err(ParseError::Recurse)) } else { @@ -1366,20 +1471,23 @@ impl ClangItemParser for Item { /// A named type is a template parameter, e.g., the "T" in Foo. They're /// always local so it's the only exception when there's no declaration for /// a type. - fn named_type(with_id: Option, - location: clang::Cursor, - ctx: &mut BindgenContext) - -> Option { + fn type_param( + with_id: Option, + location: clang::Cursor, + ctx: &mut BindgenContext, + ) -> Option { let ty = location.cur_type(); - debug!("Item::named_type:\n\ + debug!( + "Item::type_param:\n\ \twith_id = {:?},\n\ \tty = {} {:?},\n\ \tlocation: {:?}", - with_id, - ty.spelling(), - ty, - location); + with_id, + ty.spelling(), + ty, + location + ); if ty.kind() != clang_sys::CXType_Unexposed { // If the given cursor's type's kind is not Unexposed, then we @@ -1436,9 +1544,10 @@ impl ClangItemParser for Item { // but maintaining these scopes properly would require more changes to // the whole libclang -> IR parsing code. - fn is_template_with_spelling(refd: &clang::Cursor, - spelling: &str) - -> bool { + fn is_template_with_spelling( + refd: &clang::Cursor, + spelling: &str, + ) -> bool { lazy_static! { static ref ANON_TYPE_PARAM_RE: regex::Regex = regex::Regex::new(r"^type\-parameter\-\d+\-\d+$").unwrap(); @@ -1454,44 +1563,50 @@ impl ClangItemParser for Item { (refd_spelling.is_empty() && ANON_TYPE_PARAM_RE.is_match(spelling.as_ref())) } - let definition = if is_template_with_spelling(&location, - &ty_spelling) { - // Situation (1) - location - } else if location.kind() == - clang_sys::CXCursor_TypeRef { - // Situation (2) - match location.referenced() { - Some(refd) if is_template_with_spelling(&refd, - &ty_spelling) => refd, - _ => return None, - } - } else { - // Situation (3) - let mut definition = None; - - location.visit(|child| { - let child_ty = child.cur_type(); - if child_ty.kind() == clang_sys::CXCursor_TypeRef && - child_ty.spelling() == ty_spelling { - match child.referenced() { - Some(refd) if is_template_with_spelling(&refd, &ty_spelling) => { - definition = Some(refd); - return clang_sys::CXChildVisit_Break; - } - _ => {} + let definition = + if is_template_with_spelling(&location, &ty_spelling) { + // Situation (1) + location + } else if location.kind() == clang_sys::CXCursor_TypeRef { + // Situation (2) + match location.referenced() { + Some(refd) + if is_template_with_spelling(&refd, &ty_spelling) => { + refd } + _ => return None, } + } else { + // Situation (3) + let mut definition = None; + + location.visit(|child| { + let child_ty = child.cur_type(); + if child_ty.kind() == clang_sys::CXCursor_TypeRef && + child_ty.spelling() == ty_spelling + { + match child.referenced() { + Some(refd) + if is_template_with_spelling( + &refd, + &ty_spelling, + ) => { + definition = Some(refd); + return clang_sys::CXChildVisit_Break; + } + _ => {} + } + } - clang_sys::CXChildVisit_Continue - }); + clang_sys::CXChildVisit_Continue + }); - if let Some(def) = definition { - def - } else { - return None; - } - }; + if let Some(def) = definition { + def + } else { + return None; + } + }; assert!(is_template_with_spelling(&definition, &ty_spelling)); // Named types are always parented to the root module. They are never @@ -1500,9 +1615,11 @@ impl ClangItemParser for Item { // something we know will always exist. let parent = ctx.root_module(); - if let Some(id) = ctx.get_named_type(&definition) { + if let Some(id) = ctx.get_type_param(&definition) { if let Some(with_id) = with_id { - return Some(ctx.build_ty_wrapper(with_id, id, Some(parent), &ty)); + return Some( + ctx.build_ty_wrapper(with_id, id, Some(parent), &ty), + ); } else { return Some(id); } @@ -1510,27 +1627,30 @@ impl ClangItemParser for Item { // See tests/headers/const_tparam.hpp and // tests/headers/variadic_tname.hpp. - let name = ty_spelling.replace("const ", "") - .replace(".", ""); + let name = ty_spelling.replace("const ", "").replace(".", ""); let id = with_id.unwrap_or_else(|| ctx.next_item_id()); - let item = Item::new(id, - None, - None, - parent, - ItemKind::Type(Type::named(name))); - ctx.add_named_type(item, definition); + let item = Item::new( + id, + None, + None, + parent, + ItemKind::Type(Type::named(name)), + ); + ctx.add_type_param(item, definition); Some(id) } } impl ItemCanonicalName for Item { fn canonical_name(&self, ctx: &BindgenContext) -> String { - debug_assert!(ctx.in_codegen_phase(), - "You're not supposed to call this yet"); + debug_assert!( + ctx.in_codegen_phase(), + "You're not supposed to call this yet" + ); if self.canonical_name_cache.borrow().is_none() { let in_namespace = ctx.options().enable_cxx_namespaces || - ctx.options().disable_name_namespacing; + ctx.options().disable_name_namespacing; *self.canonical_name_cache.borrow_mut() = if in_namespace { Some(self.name(ctx).within_namespaces().get()) @@ -1543,9 +1663,10 @@ impl ItemCanonicalName for Item { } impl ItemCanonicalPath for Item { - fn namespace_aware_canonical_path(&self, - ctx: &BindgenContext) - -> Vec { + fn namespace_aware_canonical_path( + &self, + ctx: &BindgenContext, + ) -> Vec { let mut path = self.canonical_path(ctx); // ASSUMPTION: (disable_name_namespacing && cxx_namespaces) @@ -1576,15 +1697,16 @@ impl ItemCanonicalPath for Item { } let target = ctx.resolve_item(self.name_target(ctx)); - let mut path: Vec<_> = target.ancestors(ctx) + let mut path: Vec<_> = target + .ancestors(ctx) .chain(iter::once(ctx.root_module())) .map(|id| ctx.resolve_item(id)) .filter(|item| { item.id() == target.id() || - item.as_module().map_or(false, |module| { - !module.is_inline() || - ctx.options().conservative_inline_namespaces - }) + item.as_module().map_or(false, |module| { + !module.is_inline() || + ctx.options().conservative_inline_namespaces + }) }) .map(|item| { ctx.resolve_item(item.name_target(ctx)) @@ -1602,7 +1724,8 @@ impl ItemCanonicalPath for Item { /// flags for naming options. #[derive(Debug)] pub struct NameOptions<'item, 'ctx> - where 'ctx: 'item, +where + 'ctx: 'item, { item: &'item Item, ctx: &'item BindgenContext<'ctx>, diff --git a/src/ir/item_kind.rs b/src/ir/item_kind.rs index 419f9d4421..58f99d0cab 100644 --- a/src/ir/item_kind.rs +++ b/src/ir/item_kind.rs @@ -127,15 +127,19 @@ impl ItemKind { } impl DotAttributes for ItemKind { - fn dot_attributes(&self, - ctx: &BindgenContext, - out: &mut W) - -> io::Result<()> - where W: io::Write, + fn dot_attributes( + &self, + ctx: &BindgenContext, + out: &mut W, + ) -> io::Result<()> + where + W: io::Write, { - try!(writeln!(out, - "kind{}", - self.kind_name())); + try!(writeln!( + out, + "kind{}", + self.kind_name() + )); match *self { ItemKind::Module(ref module) => module.dot_attributes(ctx, out), diff --git a/src/ir/layout.rs b/src/ir/layout.rs index 60cf467859..4b0b17692e 100644 --- a/src/ir/layout.rs +++ b/src/ir/layout.rs @@ -1,8 +1,8 @@ //! Intermediate representation for the physical layout of some type. -use super::derive::{CanTriviallyDeriveDebug, - CanTriviallyDeriveDefault, CanTriviallyDeriveCopy, - CanTriviallyDeriveHash, CanTriviallyDerivePartialEq}; +use super::derive::{CanTriviallyDeriveCopy, CanTriviallyDeriveDebug, + CanTriviallyDeriveDefault, CanTriviallyDeriveHash, + CanTriviallyDerivePartialEq}; use super::ty::{RUST_DERIVE_IN_ARRAY_LIMIT, Type, TypeKind}; use clang; use std::{cmp, mem}; @@ -22,8 +22,10 @@ pub struct Layout { fn test_layout_for_size() { let ptr_size = mem::size_of::<*mut ()>(); assert_eq!(Layout::for_size(ptr_size), Layout::new(ptr_size, ptr_size)); - assert_eq!(Layout::for_size(3 * ptr_size), - Layout::new(3 * ptr_size, ptr_size)); + assert_eq!( + Layout::for_size(3 * ptr_size), + Layout::new(3 * ptr_size, ptr_size) + ); } impl Layout { @@ -42,7 +44,8 @@ impl Layout { pub fn for_size(size: usize) -> Self { let mut next_align = 2; while size % next_align == 0 && - next_align <= mem::size_of::<*mut ()>() { + next_align <= mem::size_of::<*mut ()>() + { next_align *= 2; } Layout { @@ -105,38 +108,40 @@ impl Opaque { impl CanTriviallyDeriveDebug for Opaque { fn can_trivially_derive_debug(&self) -> bool { - self.array_size() - .map_or(false, |size| size <= RUST_DERIVE_IN_ARRAY_LIMIT) + self.array_size().map_or(false, |size| { + size <= RUST_DERIVE_IN_ARRAY_LIMIT + }) } } impl CanTriviallyDeriveDefault for Opaque { - fn can_trivially_derive_default(&self) -> bool { - self.array_size() - .map_or(false, |size| size <= RUST_DERIVE_IN_ARRAY_LIMIT) + self.array_size().map_or(false, |size| { + size <= RUST_DERIVE_IN_ARRAY_LIMIT + }) } } impl CanTriviallyDeriveCopy for Opaque { fn can_trivially_derive_copy(&self) -> bool { - self.array_size() - .map_or(false, |size| size <= RUST_DERIVE_IN_ARRAY_LIMIT) + self.array_size().map_or(false, |size| { + size <= RUST_DERIVE_IN_ARRAY_LIMIT + }) } } impl CanTriviallyDeriveHash for Opaque { - fn can_trivially_derive_hash(&self) -> bool { - self.array_size() - .map_or(false, |size| size <= RUST_DERIVE_IN_ARRAY_LIMIT) + self.array_size().map_or(false, |size| { + size <= RUST_DERIVE_IN_ARRAY_LIMIT + }) } } impl CanTriviallyDerivePartialEq for Opaque { - fn can_trivially_derive_partialeq(&self) -> bool { - self.array_size() - .map_or(false, |size| size <= RUST_DERIVE_IN_ARRAY_LIMIT) + self.array_size().map_or(false, |size| { + size <= RUST_DERIVE_IN_ARRAY_LIMIT + }) } } diff --git a/src/ir/module.rs b/src/ir/module.rs index 09070247ab..c66623dd6b 100644 --- a/src/ir/module.rs +++ b/src/ir/module.rs @@ -60,28 +60,31 @@ impl Module { } impl DotAttributes for Module { - fn dot_attributes(&self, - _ctx: &BindgenContext, - out: &mut W) - -> io::Result<()> - where W: io::Write, + fn dot_attributes( + &self, + _ctx: &BindgenContext, + out: &mut W, + ) -> io::Result<()> + where + W: io::Write, { writeln!(out, "ModuleKind{:?}", self.kind) } } impl ClangSubItemParser for Module { - fn parse(cursor: clang::Cursor, - ctx: &mut BindgenContext) - -> Result, ParseError> { + fn parse( + cursor: clang::Cursor, + ctx: &mut BindgenContext, + ) -> Result, ParseError> { use clang_sys::*; match cursor.kind() { CXCursor_Namespace => { let module_id = ctx.module(cursor); ctx.with_module(module_id, |ctx| { - cursor.visit(|cursor| { - parse_one(ctx, cursor, Some(module_id)) - }) + cursor.visit( + |cursor| parse_one(ctx, cursor, Some(module_id)), + ) }); Ok(ParseResult::AlreadyResolved(module_id)) diff --git a/src/ir/objc.rs b/src/ir/objc.rs index 3a88eef8ab..843dd722c0 100644 --- a/src/ir/objc.rs +++ b/src/ir/objc.rs @@ -95,9 +95,10 @@ impl ObjCInterface { } /// Parses the Objective C interface from the cursor - pub fn from_ty(cursor: &clang::Cursor, - ctx: &mut BindgenContext) - -> Option { + pub fn from_ty( + cursor: &clang::Cursor, + ctx: &mut BindgenContext, + ) -> Option { let name = cursor.spelling(); let mut interface = Self::new(&name); @@ -170,10 +171,11 @@ impl ObjCInterface { } impl ObjCMethod { - fn new(name: &str, - signature: FunctionSig, - is_class_method: bool) - -> ObjCMethod { + fn new( + name: &str, + signature: FunctionSig, + is_class_method: bool, + ) -> ObjCMethod { let split_name: Vec<&str> = name.split(':').collect(); let rust_name = split_name.join("_"); @@ -220,12 +222,15 @@ impl ObjCMethod { // Check right amount of arguments if args.len() != split_name.len() { - panic!("Incorrect method name or arguments for objc method, {:?} vs {:?}", - args, - split_name); + panic!( + "Incorrect method name or arguments for objc method, {:?} vs {:?}", + args, + split_name + ); } - split_name.iter() + split_name + .iter() .zip(args.iter()) .map(|parts| format!("{}:{} ", parts.0, parts.1)) .collect::>() @@ -237,7 +242,8 @@ impl Trace for ObjCInterface { type Extra = (); fn trace(&self, context: &BindgenContext, tracer: &mut T, _: &()) - where T: Tracer, + where + T: Tracer, { for method in &self.methods { method.signature.trace(context, tracer, &()); diff --git a/src/ir/template.rs b/src/ir/template.rs index f18283278c..8fe4c7042c 100644 --- a/src/ir/template.rs +++ b/src/ir/template.rs @@ -108,9 +108,8 @@ pub trait TemplateParameters { /// parameters. Of course, Rust does not allow generic parameters to be /// anything but types, so we must treat them as opaque, and avoid /// instantiating them. - fn self_template_params(&self, - ctx: &BindgenContext) - -> Option>; + fn self_template_params(&self, ctx: &BindgenContext) + -> Option>; /// Get the number of free template parameters this template declaration /// has. @@ -138,7 +137,8 @@ pub trait TemplateParameters { /// `Foo::Inner`. `Foo` *must* be instantiated with template /// arguments before we can gain access to the `Inner` member type. fn all_template_params(&self, ctx: &BindgenContext) -> Option> - where Self: ItemAncestors, + where + Self: ItemAncestors, { let each_self_params: Vec> = self.ancestors(ctx) .filter_map(|id| id.self_template_params(ctx)) @@ -146,10 +146,13 @@ pub trait TemplateParameters { if each_self_params.is_empty() { None } else { - Some(each_self_params.into_iter() - .rev() - .flat_map(|params| params) - .collect()) + Some( + each_self_params + .into_iter() + .rev() + .flat_map(|params| params) + .collect(), + ) } } @@ -157,19 +160,23 @@ pub trait TemplateParameters { /// subset of `all_template_params` and does not necessarily contain any of /// `self_template_params`. fn used_template_params(&self, ctx: &BindgenContext) -> Option> - where Self: AsRef, + where + Self: AsRef, { - assert!(ctx.in_codegen_phase(), - "template parameter usage is not computed until codegen"); + assert!( + ctx.in_codegen_phase(), + "template parameter usage is not computed until codegen" + ); let id = *self.as_ref(); - ctx.resolve_item(id) - .all_template_params(ctx) - .map(|all_params| { - all_params.into_iter() + ctx.resolve_item(id).all_template_params(ctx).map( + |all_params| { + all_params + .into_iter() .filter(|p| ctx.uses_template_parameter(id, *p)) .collect() - }) + }, + ) } } @@ -179,13 +186,18 @@ pub trait AsTemplateParam { type Extra; /// Convert this thing to the item id of a named template type parameter. - fn as_template_param(&self, - ctx: &BindgenContext, - extra: &Self::Extra) - -> Option; + fn as_template_param( + &self, + ctx: &BindgenContext, + extra: &Self::Extra, + ) -> Option; /// Is this a named template type parameter? - fn is_template_param(&self, ctx: &BindgenContext, extra: &Self::Extra) -> bool { + fn is_template_param( + &self, + ctx: &BindgenContext, + extra: &Self::Extra, + ) -> bool { self.as_template_param(ctx, extra).is_some() } } @@ -202,10 +214,12 @@ pub struct TemplateInstantiation { impl TemplateInstantiation { /// Construct a new template instantiation from the given parts. - pub fn new(template_definition: ItemId, - template_args: I) - -> TemplateInstantiation - where I: IntoIterator, + pub fn new( + template_definition: ItemId, + template_args: I, + ) -> TemplateInstantiation + where + I: IntoIterator, { TemplateInstantiation { definition: template_definition, @@ -224,9 +238,10 @@ impl TemplateInstantiation { } /// Parse a `TemplateInstantiation` from a clang `Type`. - pub fn from_ty(ty: &clang::Type, - ctx: &mut BindgenContext) - -> Option { + pub fn from_ty( + ty: &clang::Type, + ctx: &mut BindgenContext, + ) -> Option { use clang_sys::*; let template_args = ty.template_args() @@ -250,51 +265,57 @@ impl TemplateInstantiation { }); let declaration = ty.declaration(); - let definition = if declaration.kind() == CXCursor_TypeAliasTemplateDecl { - Some(declaration) - } else { - declaration - .specialized() - .or_else(|| { + let definition = + if declaration.kind() == CXCursor_TypeAliasTemplateDecl { + Some(declaration) + } else { + declaration.specialized().or_else(|| { let mut template_ref = None; ty.declaration().visit(|child| { - if child.kind() == CXCursor_TemplateRef { - template_ref = Some(child); - return CXVisit_Break; - } + if child.kind() == CXCursor_TemplateRef { + template_ref = Some(child); + return CXVisit_Break; + } - // Instantiations of template aliases might have the - // TemplateRef to the template alias definition arbitrarily - // deep, so we need to recurse here and not only visit - // direct children. - CXChildVisit_Recurse - }); + // Instantiations of template aliases might have the + // TemplateRef to the template alias definition arbitrarily + // deep, so we need to recurse here and not only visit + // direct children. + CXChildVisit_Recurse + }); template_ref.and_then(|cur| cur.referenced()) }) - }; + }; let definition = match definition { Some(def) => def, None => { if !ty.declaration().is_builtin() { - warn!("Could not find template definition for template \ - instantiation"); + warn!( + "Could not find template definition for template \ + instantiation" + ); } - return None + return None; } }; let template_definition = Item::from_ty_or_ref(definition.cur_type(), definition, None, ctx); - Some(TemplateInstantiation::new(template_definition, template_args)) + Some(TemplateInstantiation::new( + template_definition, + template_args, + )) } /// Does this instantiation have a destructor? pub fn has_destructor(&self, ctx: &BindgenContext) -> bool { ctx.resolve_type(self.definition).has_destructor(ctx) || - self.args.iter().any(|arg| ctx.resolve_type(*arg).has_destructor(ctx)) + self.args.iter().any(|arg| { + ctx.resolve_type(*arg).has_destructor(ctx) + }) } } @@ -320,7 +341,8 @@ impl IsOpaque for TemplateInstantiation { .map(|arg| { let arg_path = arg.canonical_path(ctx); arg_path[1..].join("::") - }).collect(); + }) + .collect(); { let last = path.last_mut().unwrap(); last.push('<'); @@ -336,7 +358,8 @@ impl Trace for TemplateInstantiation { type Extra = (); fn trace(&self, _ctx: &BindgenContext, tracer: &mut T, _: &()) - where T: Tracer, + where + T: Tracer, { tracer.visit_kind(self.definition, EdgeKind::TemplateDeclaration); for &item in self.template_arguments() { diff --git a/src/ir/traversal.rs b/src/ir/traversal.rs index 762a3e2d51..e4ce946d9a 100644 --- a/src/ir/traversal.rs +++ b/src/ir/traversal.rs @@ -214,7 +214,9 @@ pub fn no_edges(_: &BindgenContext, _: Edge) -> bool { pub fn codegen_edges(ctx: &BindgenContext, edge: Edge) -> bool { let cc = &ctx.options().codegen_config; match edge.kind { - EdgeKind::Generic => ctx.resolve_item(edge.to).is_enabled_for_codegen(ctx), + EdgeKind::Generic => { + ctx.resolve_item(edge.to).is_enabled_for_codegen(ctx) + } // We statically know the kind of item that non-generic edges can point // to, so we don't need to actually resolve the item and check @@ -265,12 +267,16 @@ impl<'ctx, 'gen> TraversalStorage<'ctx, 'gen> for ItemSet { /// each item. This is useful for providing debug assertions with meaningful /// diagnostic messages about dangling items. #[derive(Debug)] -pub struct Paths<'ctx, 'gen>(BTreeMap, - &'ctx BindgenContext<'gen>) - where 'gen: 'ctx; +pub struct Paths<'ctx, 'gen>( + BTreeMap, + &'ctx BindgenContext<'gen> +) +where + 'gen: 'ctx; impl<'ctx, 'gen> TraversalStorage<'ctx, 'gen> for Paths<'ctx, 'gen> - where 'gen: 'ctx, +where + 'gen: 'ctx, { fn new(ctx: &'ctx BindgenContext<'gen>) -> Self { Paths(BTreeMap::new(), ctx) @@ -284,10 +290,10 @@ impl<'ctx, 'gen> TraversalStorage<'ctx, 'gen> for Paths<'ctx, 'gen> let mut path = vec![]; let mut current = item; loop { - let predecessor = *self.0 - .get(¤t) - .expect("We know we found this item id, so it must have a \ - predecessor"); + let predecessor = *self.0.get(¤t).expect( + "We know we found this item id, so it must have a \ + predecessor", + ); if predecessor == current { break; } @@ -295,9 +301,11 @@ impl<'ctx, 'gen> TraversalStorage<'ctx, 'gen> for Paths<'ctx, 'gen> current = predecessor; } path.reverse(); - panic!("Found reference to dangling id = {:?}\nvia path = {:?}", - item, - path); + panic!( + "Found reference to dangling id = {:?}\nvia path = {:?}", + item, + path + ); } newly_discovered @@ -349,7 +357,8 @@ pub trait Tracer { } impl Tracer for F - where F: FnMut(ItemId, EdgeKind), +where + F: FnMut(ItemId, EdgeKind), { fn visit_kind(&mut self, item: ItemId, kind: EdgeKind) { (*self)(item, kind) @@ -367,21 +376,24 @@ pub trait Trace { type Extra; /// Trace all of this item's outgoing edges to other items. - fn trace(&self, - context: &BindgenContext, - tracer: &mut T, - extra: &Self::Extra) - where T: Tracer; + fn trace( + &self, + context: &BindgenContext, + tracer: &mut T, + extra: &Self::Extra, + ) where + T: Tracer; } /// An graph traversal of the transitive closure of references between items. /// /// See `BindgenContext::whitelisted_items` for more information. pub struct ItemTraversal<'ctx, 'gen, Storage, Queue, Predicate> - where 'gen: 'ctx, - Storage: TraversalStorage<'ctx, 'gen>, - Queue: TraversalQueue, - Predicate: TraversalPredicate, +where + 'gen: 'ctx, + Storage: TraversalStorage<'ctx, 'gen>, + Queue: TraversalQueue, + Predicate: TraversalPredicate, { ctx: &'ctx BindgenContext<'gen>, @@ -398,22 +410,22 @@ pub struct ItemTraversal<'ctx, 'gen, Storage, Queue, Predicate> currently_traversing: Option, } -impl<'ctx, 'gen, Storage, Queue, Predicate> ItemTraversal<'ctx, - 'gen, - Storage, - Queue, - Predicate> - where 'gen: 'ctx, - Storage: TraversalStorage<'ctx, 'gen>, - Queue: TraversalQueue, - Predicate: TraversalPredicate, +impl<'ctx, 'gen, Storage, Queue, Predicate> + ItemTraversal<'ctx, 'gen, Storage, Queue, Predicate> +where + 'gen: 'ctx, + Storage: TraversalStorage<'ctx, 'gen>, + Queue: TraversalQueue, + Predicate: TraversalPredicate, { /// Begin a new traversal, starting from the given roots. - pub fn new(ctx: &'ctx BindgenContext<'gen>, - roots: R, - predicate: Predicate) - -> ItemTraversal<'ctx, 'gen, Storage, Queue, Predicate> - where R: IntoIterator, + pub fn new( + ctx: &'ctx BindgenContext<'gen>, + roots: R, + predicate: Predicate, + ) -> ItemTraversal<'ctx, 'gen, Storage, Queue, Predicate> + where + R: IntoIterator, { let mut seen = Storage::new(ctx); let mut queue = Queue::default(); @@ -435,10 +447,11 @@ impl<'ctx, 'gen, Storage, Queue, Predicate> ItemTraversal<'ctx, impl<'ctx, 'gen, Storage, Queue, Predicate> Tracer for ItemTraversal<'ctx, 'gen, Storage, Queue, Predicate> - where 'gen: 'ctx, - Storage: TraversalStorage<'ctx, 'gen>, - Queue: TraversalQueue, - Predicate: TraversalPredicate, +where + 'gen: 'ctx, + Storage: TraversalStorage<'ctx, 'gen>, + Queue: TraversalQueue, + Predicate: TraversalPredicate, { fn visit_kind(&mut self, item: ItemId, kind: EdgeKind) { let edge = Edge::new(item, kind); @@ -446,8 +459,8 @@ impl<'ctx, 'gen, Storage, Queue, Predicate> Tracer return; } - let is_newly_discovered = self.seen - .add(self.currently_traversing, item); + let is_newly_discovered = + self.seen.add(self.currently_traversing, item); if is_newly_discovered { self.queue.push(item) } @@ -456,10 +469,11 @@ impl<'ctx, 'gen, Storage, Queue, Predicate> Tracer impl<'ctx, 'gen, Storage, Queue, Predicate> Iterator for ItemTraversal<'ctx, 'gen, Storage, Queue, Predicate> - where 'gen: 'ctx, - Storage: TraversalStorage<'ctx, 'gen>, - Queue: TraversalQueue, - Predicate: TraversalPredicate, +where + 'gen: 'ctx, + Storage: TraversalStorage<'ctx, 'gen>, + Queue: TraversalQueue, + Predicate: TraversalPredicate, { type Item = ItemId; @@ -470,10 +484,14 @@ impl<'ctx, 'gen, Storage, Queue, Predicate> Iterator }; let newly_discovered = self.seen.add(None, id); - debug_assert!(!newly_discovered, - "should have already seen anything we get out of our queue"); - debug_assert!(self.ctx.resolve_item_fallible(id).is_some(), - "should only get IDs of actual items in our context during traversal"); + debug_assert!( + !newly_discovered, + "should have already seen anything we get out of our queue" + ); + debug_assert!( + self.ctx.resolve_item_fallible(id).is_some(), + "should only get IDs of actual items in our context during traversal" + ); self.currently_traversing = Some(id); id.trace(self.ctx, self, &()); @@ -488,11 +506,13 @@ impl<'ctx, 'gen, Storage, Queue, Predicate> Iterator /// See `BindgenContext::assert_no_dangling_item_traversal` for more /// information. pub type AssertNoDanglingItemsTraversal<'ctx, 'gen> = - ItemTraversal<'ctx, - 'gen, - Paths<'ctx, 'gen>, - VecDeque, - for<'a> fn(&'a BindgenContext, Edge) -> bool>; + ItemTraversal< + 'ctx, + 'gen, + Paths<'ctx, 'gen>, + VecDeque, + for<'a> fn(&'a BindgenContext, Edge) -> bool, + >; #[cfg(test)] mod tests { diff --git a/src/ir/ty.rs b/src/ir/ty.rs index d1d4f00dec..bd2a54ef9e 100644 --- a/src/ir/ty.rs +++ b/src/ir/ty.rs @@ -9,7 +9,8 @@ use super::int::IntKind; use super::item::{IsOpaque, Item}; use super::layout::{Layout, Opaque}; use super::objc::ObjCInterface; -use super::template::{AsTemplateParam, TemplateInstantiation, TemplateParameters}; +use super::template::{AsTemplateParam, TemplateInstantiation, + TemplateParameters}; use super::traversal::{EdgeKind, Trace, Tracer}; use clang::{self, Cursor}; use parse::{ClangItemParser, ParseError, ParseResult}; @@ -61,11 +62,12 @@ impl Type { } /// Construct a new `Type`. - pub fn new(name: Option, - layout: Option, - kind: TypeKind, - is_const: bool) - -> Self { + pub fn new( + name: Option, + layout: Option, + kind: TypeKind, + is_const: bool, + ) -> Self { Type { name: name, layout: layout, @@ -97,10 +99,10 @@ impl Type { } } - /// Is this type of kind `TypeKind::Named`? - pub fn is_named(&self) -> bool { + /// Is this type of kind `TypeKind::TypeParam`? + pub fn is_type_param(&self) -> bool { match self.kind { - TypeKind::Named => true, + TypeKind::TypeParam => true, _ => false, } } @@ -138,7 +140,7 @@ impl Type { } /// Is this either a builtin or named type? - pub fn is_builtin_or_named(&self) -> bool { + pub fn is_builtin_or_type_param(&self) -> bool { match self.kind { TypeKind::Void | TypeKind::NullPtr | @@ -149,19 +151,15 @@ impl Type { TypeKind::BlockPointer | TypeKind::Int(..) | TypeKind::Float(..) | - TypeKind::Named => true, + TypeKind::TypeParam => true, _ => false, } } /// Creates a new named type, with name `name`. pub fn named(name: String) -> Self { - let name = if name.is_empty() { - None - } else { - Some(name) - }; - Self::new(name, None, TypeKind::Named, false) + let name = if name.is_empty() { None } else { Some(name) }; + Self::new(name, None, TypeKind::TypeParam, false) } /// Is this a floating point type? @@ -226,8 +224,10 @@ impl Type { // Use the actual pointer size! TypeKind::Pointer(..) | TypeKind::BlockPointer => { - Some(Layout::new(mem::size_of::<*mut ()>(), - mem::align_of::<*mut ()>())) + Some(Layout::new( + mem::size_of::<*mut ()>(), + mem::align_of::<*mut ()>(), + )) } TypeKind::ResolvedTypeRef(inner) => { ctx.resolve_type(inner).layout(ctx) @@ -257,9 +257,9 @@ impl Type { /// avoid generating invalid code with some cases we can't handle, see: /// /// tests/headers/381-decltype-alias.hpp - pub fn is_invalid_named_type(&self) -> bool { + pub fn is_invalid_type_param(&self) -> bool { match self.kind { - TypeKind::Named => { + TypeKind::TypeParam => { let name = self.name().expect("Unnamed named type?"); !clang::is_valid_identifier(&name) } @@ -270,15 +270,18 @@ impl Type { /// Takes `name`, and returns a suitable identifier representation for it. fn sanitize_name<'a>(name: &'a str) -> Cow<'a, str> { if clang::is_valid_identifier(name) { - return Cow::Borrowed(name) + return Cow::Borrowed(name); } - let name = name.replace(|c| c == ' ' || c == ':' || c == '.' , "_"); + let name = name.replace(|c| c == ' ' || c == ':' || c == '.', "_"); Cow::Owned(name) } /// Get this type's santizied name. - pub fn sanitized_name<'a>(&'a self, ctx: &BindgenContext) -> Option> { + pub fn sanitized_name<'a>( + &'a self, + ctx: &BindgenContext, + ) -> Option> { let name_info = match *self.kind() { TypeKind::Pointer(inner) => Some((inner, Cow::Borrowed("ptr"))), TypeKind::Reference(inner) => Some((inner, Cow::Borrowed("ref"))), @@ -289,19 +292,22 @@ impl Type { }; if let Some((inner, prefix)) = name_info { ctx.resolve_item(inner) - .expect_type().sanitized_name(ctx) - .map(|name| format!("{}_{}", prefix, name).into()) + .expect_type() + .sanitized_name(ctx) + .map(|name| format!("{}_{}", prefix, name).into()) } else { self.name().map(Self::sanitize_name) } } /// 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". @@ -309,11 +315,12 @@ impl Type { /// For example, for a `typedef`, the canonical type would be the /// `typedef`ed type, for a template instantiation, 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::TypeParam | TypeKind::Array(..) | TypeKind::Comp(..) | TypeKind::Opaque | @@ -367,7 +374,9 @@ impl IsOpaque for Type { fn is_opaque(&self, ctx: &BindgenContext, item: &Item) -> bool { match self.kind { TypeKind::Opaque => true, - TypeKind::TemplateInstantiation(ref inst) => inst.is_opaque(ctx, item), + TypeKind::TemplateInstantiation(ref inst) => { + inst.is_opaque(ctx, item) + } TypeKind::Comp(ref comp) => comp.is_opaque(ctx, &()), TypeKind::ResolvedTypeRef(to) => to.is_opaque(ctx, &()), _ => false, @@ -378,7 +387,11 @@ impl IsOpaque for Type { impl AsTemplateParam for Type { type Extra = Item; - fn as_template_param(&self, ctx: &BindgenContext, item: &Item) -> Option { + fn as_template_param( + &self, + ctx: &BindgenContext, + item: &Item, + ) -> Option { self.kind.as_template_param(ctx, item) } } @@ -386,9 +399,13 @@ impl AsTemplateParam for Type { impl AsTemplateParam for TypeKind { type Extra = Item; - fn as_template_param(&self, ctx: &BindgenContext, item: &Item) -> Option { + fn as_template_param( + &self, + ctx: &BindgenContext, + item: &Item, + ) -> Option { match *self { - TypeKind::Named => Some(item.id()), + TypeKind::TypeParam => Some(item.id()), TypeKind::ResolvedTypeRef(id) => id.as_template_param(ctx, &()), _ => None, } @@ -396,18 +413,22 @@ impl AsTemplateParam for TypeKind { } impl DotAttributes for Type { - fn dot_attributes(&self, - ctx: &BindgenContext, - out: &mut W) - -> io::Result<()> - where W: io::Write, + fn dot_attributes( + &self, + ctx: &BindgenContext, + out: &mut W, + ) -> io::Result<()> + where + W: io::Write, { if let Some(ref layout) = self.layout { - try!(writeln!(out, - "size{} + try!(writeln!( + out, + "size{} align{}", - layout.size, - layout.align)); + layout.size, + layout.align + )); if layout.packed { try!(writeln!(out, "packedtrue")); } @@ -422,38 +443,14 @@ impl DotAttributes for Type { } impl DotAttributes for TypeKind { - fn dot_attributes(&self, - ctx: &BindgenContext, - out: &mut W) - -> io::Result<()> - where W: io::Write, + fn dot_attributes( + &self, + ctx: &BindgenContext, + out: &mut W, + ) -> io::Result<()> + where + W: io::Write, { - write!(out, - "TypeKind{}", - match *self { - TypeKind::Void => "Void", - TypeKind::NullPtr => "NullPtr", - TypeKind::Comp(..) => "Comp", - TypeKind::Opaque => "Opaque", - TypeKind::Int(..) => "Int", - TypeKind::Float(..) => "Float", - TypeKind::Complex(..) => "Complex", - TypeKind::Alias(..) => "Alias", - TypeKind::TemplateAlias(..) => "TemplateAlias", - TypeKind::Array(..) => "Array", - TypeKind::Function(..) => "Function", - TypeKind::Enum(..) => "Enum", - TypeKind::Pointer(..) => "Pointer", - TypeKind::BlockPointer => "BlockPointer", - TypeKind::Reference(..) => "Reference", - TypeKind::TemplateInstantiation(..) => "TemplateInstantiation", - TypeKind::ResolvedTypeRef(..) => "ResolvedTypeRef", - TypeKind::Named => "Named", - TypeKind::ObjCId => "ObjCId", - TypeKind::ObjCSel => "ObjCSel", - TypeKind::ObjCInterface(..) => "ObjCInterface", - TypeKind::UnresolvedTypeRef(..) => unreachable!("there shouldn't be any more of these anymore"), - })?; if let TypeKind::Comp(ref comp) = *self { comp.dot_attributes(ctx, out)?; } @@ -463,62 +460,67 @@ impl DotAttributes for TypeKind { } #[test] -fn is_invalid_named_type_valid() { - let ty = Type::new(Some("foo".into()), None, TypeKind::Named, false); - assert!(!ty.is_invalid_named_type()) +fn is_invalid_type_param_valid() { + let ty = Type::new(Some("foo".into()), None, TypeKind::TypeParam, false); + assert!(!ty.is_invalid_type_param()) } #[test] -fn is_invalid_named_type_valid_underscore_and_numbers() { - let ty = - Type::new(Some("_foo123456789_".into()), None, TypeKind::Named, false); - assert!(!ty.is_invalid_named_type()) +fn is_invalid_type_param_valid_underscore_and_numbers() { + let ty = Type::new( + Some("_foo123456789_".into()), + None, + TypeKind::TypeParam, + false, + ); + assert!(!ty.is_invalid_type_param()) } #[test] -fn is_invalid_named_type_valid_unnamed_kind() { +fn is_invalid_type_param_valid_unnamed_kind() { let ty = Type::new(Some("foo".into()), None, TypeKind::Void, false); - assert!(!ty.is_invalid_named_type()) + assert!(!ty.is_invalid_type_param()) } #[test] -fn is_invalid_named_type_invalid_start() { - let ty = Type::new(Some("1foo".into()), None, TypeKind::Named, false); - assert!(ty.is_invalid_named_type()) +fn is_invalid_type_param_invalid_start() { + let ty = Type::new(Some("1foo".into()), None, TypeKind::TypeParam, false); + assert!(ty.is_invalid_type_param()) } #[test] -fn is_invalid_named_type_invalid_remaing() { - let ty = Type::new(Some("foo-".into()), None, TypeKind::Named, false); - assert!(ty.is_invalid_named_type()) +fn is_invalid_type_param_invalid_remaing() { + let ty = Type::new(Some("foo-".into()), None, TypeKind::TypeParam, false); + assert!(ty.is_invalid_type_param()) } #[test] #[should_panic] -fn is_invalid_named_type_unnamed() { - let ty = Type::new(None, None, TypeKind::Named, false); - assert!(ty.is_invalid_named_type()) +fn is_invalid_type_param_unnamed() { + let ty = Type::new(None, None, TypeKind::TypeParam, false); + assert!(ty.is_invalid_type_param()) } #[test] -fn is_invalid_named_type_empty_name() { - let ty = Type::new(Some("".into()), None, TypeKind::Named, false); - assert!(ty.is_invalid_named_type()) +fn is_invalid_type_param_empty_name() { + let ty = Type::new(Some("".into()), None, TypeKind::TypeParam, false); + assert!(ty.is_invalid_type_param()) } - impl TemplateParameters for Type { - fn self_template_params(&self, - ctx: &BindgenContext) - -> Option> { + fn self_template_params( + &self, + ctx: &BindgenContext, + ) -> Option> { self.kind.self_template_params(ctx) } } impl TemplateParameters for TypeKind { - fn self_template_params(&self, - ctx: &BindgenContext) - -> Option> { + fn self_template_params( + &self, + ctx: &BindgenContext, + ) -> Option> { match *self { TypeKind::ResolvedTypeRef(id) => { ctx.resolve_type(id).self_template_params(ctx) @@ -540,7 +542,7 @@ impl TemplateParameters for TypeKind { TypeKind::BlockPointer | TypeKind::Reference(_) | TypeKind::UnresolvedTypeRef(..) | - TypeKind::Named | + TypeKind::TypeParam | TypeKind::Alias(_) | TypeKind::ObjCId | TypeKind::ObjCSel | @@ -637,10 +639,12 @@ 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, - clang::Cursor, - /* parent_id */ - Option), + UnresolvedTypeRef( + clang::Type, + clang::Cursor, + /* parent_id */ + Option + ), /// An indirection to another type. /// @@ -649,7 +653,7 @@ pub enum TypeKind { ResolvedTypeRef(ItemId), /// A named type, that is, a template parameter. - Named, + TypeParam, /// Objective C interface. Always referenced through a pointer ObjCInterface(ObjCInterface), @@ -685,7 +689,7 @@ impl Type { let definition = inst.template_definition(); ctx.resolve_type(definition).is_unsized(ctx, &definition) } - TypeKind::Named | + TypeKind::TypeParam | TypeKind::Int(..) | TypeKind::Float(..) | TypeKind::Complex(..) | @@ -711,18 +715,21 @@ impl Type { /// /// It's sort of nasty and full of special-casing, but hopefully the /// comments in every special case justify why they're there. - pub fn from_clang_ty(potential_id: ItemId, - ty: &clang::Type, - location: Cursor, - parent_id: Option, - ctx: &mut BindgenContext) - -> Result, ParseError> { + pub fn from_clang_ty( + potential_id: ItemId, + ty: &clang::Type, + location: Cursor, + parent_id: Option, + ctx: &mut BindgenContext, + ) -> Result, ParseError> { use clang_sys::*; { - let already_resolved = ctx.builtin_or_resolved_ty(potential_id, - parent_id, - ty, - Some(location)); + let already_resolved = ctx.builtin_or_resolved_ty( + potential_id, + parent_id, + ty, + Some(location), + ); if let Some(ty) = already_resolved { debug!("{:?} already resolved: {:?}", ty, location); return Ok(ParseResult::AlreadyResolved(ty)); @@ -733,10 +740,12 @@ impl Type { let cursor = ty.declaration(); let mut name = cursor.spelling(); - debug!("from_clang_ty: {:?}, ty: {:?}, loc: {:?}", - potential_id, - ty, - location); + debug!( + "from_clang_ty: {:?}, ty: {:?}, loc: {:?}", + potential_id, + ty, + location + ); debug!("currently_parsed_types: {:?}", ctx.currently_parsed_types()); let canonical_ty = ty.canonical_type(); @@ -755,8 +764,10 @@ impl Type { // We are rewriting them as id to suppress multiple conflicting // typedefs at root level if ty_kind == CXType_Typedef { - let is_template_type_param = ty.declaration().kind() == CXCursor_TemplateTypeParameter; - let is_canonical_objcpointer = canonical_ty.kind() == CXType_ObjCObjectPointer; + let is_template_type_param = ty.declaration().kind() == + CXCursor_TemplateTypeParameter; + let is_canonical_objcpointer = canonical_ty.kind() == + CXType_ObjCObjectPointer; // We have found a template type for objc interface if is_canonical_objcpointer && is_template_type_param { @@ -769,16 +780,19 @@ impl Type { if location.kind() == CXCursor_ClassTemplatePartialSpecialization { // Sorry! (Not sorry) - warn!("Found a partial template specialization; bindgen does not \ + warn!( + "Found a partial template specialization; bindgen does not \ support partial template specialization! Constructing \ - opaque type instead."); - return Ok(ParseResult::New(Opaque::from_clang_ty(&canonical_ty), - None)); + opaque type instead." + ); + return Ok( + ParseResult::New(Opaque::from_clang_ty(&canonical_ty), None), + ); } let kind = if location.kind() == CXCursor_TemplateRef || - (ty.template_args().is_some() && - ty_kind != CXType_Typedef) { + (ty.template_args().is_some() && ty_kind != CXType_Typedef) + { // This is a template instantiation. match TemplateInstantiation::from_ty(&ty, ctx) { Some(inst) => TypeKind::TemplateInstantiation(inst), @@ -818,25 +832,29 @@ impl Type { let signature = try!(FunctionSig::from_ty(ty, &location, 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.is_fully_instantiated_template() { - debug!("Template specialization: {:?}, {:?} {:?}", - ty, - location, - canonical_ty); - let complex = CompInfo::from_ty(potential_id, - ty, - Some(location), - ctx) - .expect("C'mon"); + debug!( + "Template specialization: {:?}, {:?} {:?}", + ty, + location, + canonical_ty + ); + let complex = CompInfo::from_ty( + potential_id, + ty, + Some(location), + ctx, + ).expect("C'mon"); TypeKind::Comp(complex) } else { match location.kind() { CXCursor_CXXBaseSpecifier | CXCursor_ClassTemplate => { if location.kind() == - CXCursor_CXXBaseSpecifier { + CXCursor_CXXBaseSpecifier + { // In the case we're parsing a base specifier // inside an unexposed or invalid type, it means // that we're parsing one of two things: @@ -876,29 +894,34 @@ impl Type { // [2]: forward-inherit-struct-with-fields.hpp // [3]: forward-inherit-struct.hpp // [4]: inherit-namespaced.hpp - if location.spelling() - .chars() - .all(|c| { - c.is_alphanumeric() || c == '_' - }) { + if location.spelling().chars().all(|c| { + c.is_alphanumeric() || c == '_' + }) + { return Err(ParseError::Recurse); } } else { name = location.spelling(); } - let complex = CompInfo::from_ty(potential_id, - ty, - Some(location), - ctx); + let complex = CompInfo::from_ty( + potential_id, + ty, + Some(location), + ctx, + ); match complex { Ok(complex) => TypeKind::Comp(complex), Err(_) => { - warn!("Could not create complex type \ + warn!( + "Could not create complex type \ from class template or base \ - specifier, using opaque blob"); + specifier, using opaque blob" + ); let opaque = Opaque::from_clang_ty(ty); - return Ok(ParseResult::New(opaque, None)); + return Ok( + ParseResult::New(opaque, None), + ); } } } @@ -929,10 +952,10 @@ impl Type { } CXCursor_TemplateTypeParameter => { let param = - Item::named_type(None, + Item::type_param(None, cur, ctx) - .expect("Item::named_type shouldn't \ + .expect("Item::type_param shouldn't \ ever fail if we are looking \ at a TemplateTypeParameter"); args.push(param); @@ -945,9 +968,11 @@ impl Type { let inner_type = match inner { Ok(inner) => inner, Err(..) => { - error!("Failed to parse template alias \ + error!( + "Failed to parse template alias \ {:?}", - location); + location + ); return Err(ParseError::Continue); } }; @@ -958,35 +983,42 @@ impl Type { let referenced = location.referenced().unwrap(); let referenced_ty = referenced.cur_type(); - debug!("TemplateRef: location = {:?}; referenced = \ + debug!( + "TemplateRef: location = {:?}; referenced = \ {:?}; referenced_ty = {:?}", - location, - referenced, - referenced_ty); - - return Self::from_clang_ty(potential_id, - &referenced_ty, - referenced, - parent_id, - ctx); + location, + referenced, + referenced_ty + ); + + return Self::from_clang_ty( + potential_id, + &referenced_ty, + referenced, + parent_id, + ctx, + ); } CXCursor_TypeRef => { let referenced = location.referenced().unwrap(); let referenced_ty = referenced.cur_type(); let declaration = referenced_ty.declaration(); - debug!("TypeRef: location = {:?}; referenced = \ + debug!( + "TypeRef: location = {:?}; referenced = \ {:?}; referenced_ty = {:?}", - location, - referenced, - referenced_ty); - - let item = - Item::from_ty_or_ref_with_id(potential_id, - referenced_ty, - declaration, - parent_id, - ctx); + location, + referenced, + referenced_ty + ); + + let item = Item::from_ty_or_ref_with_id( + potential_id, + referenced_ty, + declaration, + parent_id, + ctx, + ); return Ok(ParseResult::AlreadyResolved(item)); } CXCursor_NamespaceRef => { @@ -994,10 +1026,12 @@ impl Type { } _ => { if ty.kind() == CXType_Unexposed { - warn!("Unexposed type {:?}, recursing inside, \ + warn!( + "Unexposed type {:?}, recursing inside, \ loc: {:?}", - ty, - location); + ty, + location + ); return Err(ParseError::Recurse); } @@ -1013,11 +1047,13 @@ impl Type { return Err(ParseError::Continue); } - 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, + ); } // NOTE: We don't resolve pointers eagerly because the pointee type // might not have been parsed, and if it contains templates or @@ -1050,8 +1086,8 @@ impl Type { // pointers, etc, which isn't trivial given function pointers // are mostly unexposed. I don't have the time for it right now. let mut pointee = ty.pointee_type().unwrap(); - let canonical_pointee = canonical_ty.pointee_type() - .unwrap(); + let canonical_pointee = + canonical_ty.pointee_type().unwrap(); if pointee.call_conv() != canonical_pointee.call_conv() { pointee = canonical_pointee; } @@ -1064,29 +1100,32 @@ impl Type { // can even add bindings for that, so huh. CXType_RValueReference | CXType_LValueReference => { - let inner = Item::from_ty_or_ref(ty.pointee_type() - .unwrap(), - location, - None, - ctx); + let inner = Item::from_ty_or_ref( + ty.pointee_type().unwrap(), + location, + None, + ctx, + ); TypeKind::Reference(inner) } // XXX DependentSizedArray is wrong CXType_VariableArray | CXType_DependentSizedArray => { - let inner = Item::from_ty(ty.elem_type().as_ref().unwrap(), - location, - None, - ctx) - .expect("Not able to resolve array element?"); + let inner = Item::from_ty( + ty.elem_type().as_ref().unwrap(), + location, + None, + ctx, + ).expect("Not able to resolve array element?"); TypeKind::Pointer(inner) } CXType_IncompleteArray => { - let inner = Item::from_ty(ty.elem_type().as_ref().unwrap(), - location, - None, - ctx) - .expect("Not able to resolve array element?"); + let inner = Item::from_ty( + ty.elem_type().as_ref().unwrap(), + location, + None, + ctx, + ).expect("Not able to resolve array element?"); TypeKind::Array(inner, 0) } CXType_FunctionNoProto | @@ -1114,11 +1153,12 @@ impl Type { TypeKind::Enum(enum_) } CXType_Record => { - let complex = CompInfo::from_ty(potential_id, - ty, - Some(location), - ctx) - .expect("Not a complex type?"); + let complex = CompInfo::from_ty( + potential_id, + ty, + Some(location), + ctx, + ).expect("Not a complex type?"); if name.is_empty() { // The pretty-printed name may contain typedefed name, @@ -1138,19 +1178,22 @@ impl Type { // That being said, that should be fixed eventually. CXType_Vector | CXType_ConstantArray => { - let inner = Item::from_ty(ty.elem_type().as_ref().unwrap(), - location, - None, - ctx) - .expect("Not able to resolve array element?"); + let inner = Item::from_ty( + ty.elem_type().as_ref().unwrap(), + location, + None, + ctx, + ).expect("Not able to resolve array element?"); TypeKind::Array(inner, ty.num_elements().unwrap()) } 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, + ); } CXType_ObjCId => TypeKind::ObjCId, CXType_ObjCSel => TypeKind::ObjCSel, @@ -1162,10 +1205,12 @@ impl Type { TypeKind::ObjCInterface(interface) } _ => { - error!("unsupported type: kind = {:?}; ty = {:?}; at {:?}", - ty.kind(), - ty, - location); + error!( + "unsupported type: kind = {:?}; ty = {:?}; at {:?}", + ty.kind(), + ty, + location + ); return Err(ParseError::Continue); } } @@ -1184,7 +1229,8 @@ impl Trace for Type { type Extra = Item; fn trace(&self, context: &BindgenContext, tracer: &mut T, item: &Item) - where T: Tracer, + where + T: Tracer, { match *self.kind() { TypeKind::Pointer(inner) | @@ -1197,8 +1243,10 @@ impl Trace for Type { TypeKind::TemplateAlias(inner, ref template_params) => { tracer.visit_kind(inner, EdgeKind::TypeReference); for &item in template_params { - tracer.visit_kind(item, - EdgeKind::TemplateParameterDefinition); + tracer.visit_kind( + item, + EdgeKind::TemplateParameterDefinition, + ); } } TypeKind::TemplateInstantiation(ref inst) => { @@ -1222,7 +1270,7 @@ impl Trace for Type { // None of these variants have edges to other items and types. TypeKind::Opaque | TypeKind::UnresolvedTypeRef(_, _, None) | - TypeKind::Named | + TypeKind::TypeParam | TypeKind::Void | TypeKind::NullPtr | TypeKind::Int(_) | diff --git a/src/ir/var.rs b/src/ir/var.rs index b1efc57ab1..987bfd5048 100644 --- a/src/ir/var.rs +++ b/src/ir/var.rs @@ -44,12 +44,13 @@ pub struct Var { impl Var { /// Construct a new `Var`. - pub fn new(name: String, - mangled: Option, - ty: ItemId, - val: Option, - is_const: bool) - -> Var { + pub fn new( + name: String, + mangled: Option, + ty: ItemId, + val: Option, + is_const: bool, + ) -> Var { assert!(!name.is_empty()); Var { name: name, @@ -87,20 +88,24 @@ impl Var { } impl DotAttributes for Var { - fn dot_attributes(&self, - _ctx: &BindgenContext, - out: &mut W) - -> io::Result<()> - where W: io::Write, + fn dot_attributes( + &self, + _ctx: &BindgenContext, + out: &mut W, + ) -> io::Result<()> + where + W: io::Write, { if self.is_const { try!(writeln!(out, "consttrue")); } if let Some(ref mangled) = self.mangled_name { - try!(writeln!(out, - "mangled name{}", - mangled)); + try!(writeln!( + out, + "mangled name{}", + mangled + )); } Ok(()) @@ -108,9 +113,10 @@ impl DotAttributes for Var { } impl ClangSubItemParser for Var { - fn parse(cursor: clang::Cursor, - ctx: &mut BindgenContext) - -> Result, ParseError> { + fn parse( + cursor: clang::Cursor, + ctx: &mut BindgenContext, + ) -> Result, ParseError> { use clang_sys::*; use cexpr::expr::EvalResult; use cexpr::literal::CChar; @@ -168,10 +174,11 @@ impl ClangSubItemParser for Var { (TypeKind::Int(IntKind::U8), VarType::Char(c)) } EvalResult::Str(val) => { - let char_ty = - Item::builtin_type(TypeKind::Int(IntKind::U8), - true, - ctx); + let char_ty = Item::builtin_type( + TypeKind::Int(IntKind::U8), + true, + ctx, + ); (TypeKind::Pointer(char_ty), VarType::String(val)) } EvalResult::Int(Wrapping(value)) => { @@ -195,8 +202,10 @@ impl ClangSubItemParser for Var { let ty = Item::builtin_type(type_kind, true, ctx); - Ok(ParseResult::New(Var::new(name, None, ty, Some(val), true), - Some(cursor))) + Ok(ParseResult::New( + Var::new(name, None, ty, Some(val), true), + Some(cursor), + )) } CXCursor_VarDecl => { let name = cursor.spelling(); @@ -213,10 +222,12 @@ impl ClangSubItemParser for Var { let ty = match Item::from_ty(&ty, cursor, None, ctx) { Ok(ty) => ty, Err(e) => { - assert_eq!(ty.kind(), - CXType_Auto, - "Couldn't resolve constant type, and it \ - wasn't an nondeductible auto type!"); + assert_eq!( + ty.kind(), + CXType_Auto, + "Couldn't resolve constant type, and it \ + wasn't an nondeductible auto type!" + ); return Err(e); } }; @@ -225,8 +236,9 @@ impl ClangSubItemParser for Var { // tests/headers/inner_const.hpp // // That's fine because in that case we know it's not a literal. - let canonical_ty = ctx.safe_resolve_type(ty) - .and_then(|t| t.safe_canonical_type(ctx)); + let canonical_ty = ctx.safe_resolve_type(ty).and_then(|t| { + t.safe_canonical_type(ctx) + }); let is_integer = canonical_ty.map_or(false, |t| t.is_integer()); let is_float = canonical_ty.map_or(false, |t| t.is_float()); @@ -241,7 +253,8 @@ impl ClangSubItemParser for Var { _ => unreachable!(), }; - let mut val = cursor.evaluate() + let mut val = cursor + .evaluate() .and_then(|v| v.as_int()) .map(|val| val as i64); if val.is_none() || !kind.signedness_matches(val.unwrap()) { @@ -255,13 +268,13 @@ impl ClangSubItemParser for Var { VarType::Int(val) }) } else if is_float { - cursor.evaluate() - .and_then(|v| v.as_double()) - .map(VarType::Float) + cursor.evaluate().and_then(|v| v.as_double()).map( + VarType::Float, + ) } else { - cursor.evaluate() - .and_then(|v| v.as_literal_string()) - .map(VarType::String) + cursor.evaluate().and_then(|v| v.as_literal_string()).map( + VarType::String, + ) }; let mangling = cursor_mangling(ctx, &cursor); @@ -278,10 +291,11 @@ impl ClangSubItemParser for Var { } /// Try and parse a macro using all the macros parsed until now. -fn parse_macro(ctx: &BindgenContext, - cursor: &clang::Cursor, - unit: &clang::TranslationUnit) - -> Option<(Vec, cexpr::expr::EvalResult)> { +fn parse_macro( + ctx: &BindgenContext, + cursor: &clang::Cursor, + unit: &clang::TranslationUnit, +) -> Option<(Vec, cexpr::expr::EvalResult)> { use cexpr::{expr, nom}; let mut cexpr_tokens = match unit.cexpr_tokens(cursor) { @@ -309,16 +323,15 @@ fn parse_macro(ctx: &BindgenContext, } match parser.macro_definition(&cexpr_tokens) { - nom::IResult::Done(_, (id, val)) => { - Some((id.into(), val)) - } - _ => None + nom::IResult::Done(_, (id, val)) => Some((id.into(), val)), + _ => None, } } -fn parse_int_literal_tokens(cursor: &clang::Cursor, - unit: &clang::TranslationUnit) - -> Option { +fn parse_int_literal_tokens( + cursor: &clang::Cursor, + unit: &clang::TranslationUnit, +) -> Option { use cexpr::{expr, nom}; use cexpr::expr::EvalResult; @@ -334,9 +347,10 @@ fn parse_int_literal_tokens(cursor: &clang::Cursor, } } -fn get_integer_literal_from_cursor(cursor: &clang::Cursor, - unit: &clang::TranslationUnit) - -> Option { +fn get_integer_literal_from_cursor( + cursor: &clang::Cursor, + unit: &clang::TranslationUnit, +) -> Option { use clang_sys::*; let mut value = None; cursor.visit(|c| { diff --git a/src/lib.rs b/src/lib.rs index 74a20292cd..3954ee2679 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -80,7 +80,7 @@ mod codegen { include!(concat!(env!("OUT_DIR"), "/codegen.rs")); } -pub use features::{RustTarget, LATEST_STABLE_RUST, RUST_TARGET_STRINGS}; +pub use features::{LATEST_STABLE_RUST, RUST_TARGET_STRINGS, RustTarget}; use features::RustFeatures; use ir::context::{BindgenContext, ItemId}; use ir::item::Item; @@ -95,7 +95,7 @@ use std::process::{Command, Stdio}; use std::sync::Arc; use syntax::ast; -use syntax::codemap::{Span, DUMMY_SP}; +use syntax::codemap::{DUMMY_SP, Span}; use syntax::print::pp::eof; use syntax::print::pprust; use syntax::ptr::P; @@ -199,7 +199,9 @@ impl Builder { .map(|item| { output_vector.push("--bitfield-enum".into()); output_vector.push( - item.trim_left_matches("^").trim_right_matches("$").into(), + item.trim_left_matches("^") + .trim_right_matches("$") + .into(), ); }) .count(); @@ -211,7 +213,9 @@ impl Builder { .map(|item| { output_vector.push("--constified-enum".into()); output_vector.push( - item.trim_left_matches("^").trim_right_matches("$").into(), + item.trim_left_matches("^") + .trim_right_matches("$") + .into(), ); }) .count(); @@ -223,7 +227,9 @@ impl Builder { .map(|item| { output_vector.push("--constified-enum-module".into()); output_vector.push( - item.trim_left_matches("^").trim_right_matches("$").into(), + item.trim_left_matches("^") + .trim_right_matches("$") + .into(), ); }) .count(); @@ -235,7 +241,9 @@ impl Builder { .map(|item| { output_vector.push("--blacklist-type".into()); output_vector.push( - item.trim_left_matches("^").trim_right_matches("$").into(), + item.trim_left_matches("^") + .trim_right_matches("$") + .into(), ); }) .count(); @@ -311,7 +319,9 @@ impl Builder { .map(|&(ref item, _)| { output_vector.push("--framework".into()); output_vector.push( - item.trim_left_matches("^").trim_right_matches("$").into(), + item.trim_left_matches("^") + .trim_right_matches("$") + .into(), ); }) .count(); @@ -355,7 +365,9 @@ impl Builder { .map(|&(ref item, _)| { output_vector.push("--clang-args".into()); output_vector.push( - item.trim_left_matches("^").trim_right_matches("$").into(), + item.trim_left_matches("^") + .trim_right_matches("$") + .into(), ); }) .count(); @@ -375,7 +387,9 @@ impl Builder { .map(|item| { output_vector.push("--opaque-type".into()); output_vector.push( - item.trim_left_matches("^").trim_right_matches("$").into(), + item.trim_left_matches("^") + .trim_right_matches("$") + .into(), ); }) .count(); @@ -386,7 +400,9 @@ impl Builder { .map(|item| { output_vector.push("--raw-line".into()); output_vector.push( - item.trim_left_matches("^").trim_right_matches("$").into(), + item.trim_left_matches("^") + .trim_right_matches("$") + .into(), ); }) .count(); @@ -397,7 +413,9 @@ impl Builder { .map(|&(ref item, _)| { output_vector.push("--static".into()); output_vector.push( - item.trim_left_matches("^").trim_right_matches("$").into(), + item.trim_left_matches("^") + .trim_right_matches("$") + .into(), ); }) .count(); @@ -417,7 +435,9 @@ impl Builder { .map(|item| { output_vector.push("--whitelist-function".into()); output_vector.push( - item.trim_left_matches("^").trim_right_matches("$").into(), + item.trim_left_matches("^") + .trim_right_matches("$") + .into(), ); }) .count(); @@ -429,7 +449,9 @@ impl Builder { .map(|item| { output_vector.push("--whitelist-type".into()); output_vector.push( - item.trim_left_matches("^").trim_right_matches("$").into(), + item.trim_left_matches("^") + .trim_right_matches("$") + .into(), ); }) .count(); @@ -441,7 +463,9 @@ impl Builder { .map(|item| { output_vector.push("--whitelist-var".into()); output_vector.push( - item.trim_left_matches("^").trim_right_matches("$").into(), + item.trim_left_matches("^") + .trim_right_matches("$") + .into(), ); }) .count(); @@ -507,8 +531,9 @@ impl Builder { /// /// The file `name` will be added to the clang arguments. pub fn header_contents(mut self, name: &str, contents: &str) -> Builder { - self.input_header_contents - .push((name.into(), contents.into())); + self.input_header_contents.push( + (name.into(), contents.into()), + ); self } @@ -676,9 +701,9 @@ impl Builder { /// Make the generated bindings link the given framework. pub fn link_framework>(mut self, library: T) -> Builder { - self.options - .links - .push((library.into(), LinkType::Framework)); + self.options.links.push( + (library.into(), LinkType::Framework), + ); self } @@ -823,9 +848,13 @@ impl Builder { } /// Avoid generating any unstable Rust, such as Rust unions, in the generated bindings. - #[deprecated(note="please use `rust_target` instead")] + #[deprecated(note = "please use `rust_target` instead")] pub fn unstable_rust(self, doit: bool) -> Self { - let rust_target = if doit { RustTarget::Nightly } else { LATEST_STABLE_RUST }; + let rust_target = if doit { + RustTarget::Nightly + } else { + LATEST_STABLE_RUST + }; self.rust_target(rust_target) } @@ -882,17 +911,17 @@ impl Builder { pub fn generate<'ctx>(mut self) -> Result, ()> { self.options.input_header = self.input_headers.pop(); self.options.clang_args.extend( - self.input_headers.drain(..).flat_map(|header| { - iter::once("-include".into()).chain(iter::once(header)) - }), + self.input_headers + .drain(..) + .flat_map(|header| { + iter::once("-include".into()).chain(iter::once(header)) + }), ); self.options.input_unsaved_files.extend( - self.input_header_contents - .drain(..) - .map(|(name, contents)| { - clang::UnsavedFile::new(&name, &contents) - }), + self.input_header_contents.drain(..).map(|(name, contents)| { + clang::UnsavedFile::new(&name, &contents) + }), ); Bindings::generate(self.options, None) @@ -904,13 +933,9 @@ impl Builder { /// issues. The resulting file will be named something like `__bindgen.i` or /// `__bindgen.ii` pub fn dump_preprocessed_input(&self) -> io::Result<()> { - let clang = clang_sys::support::Clang::find(None, &[]) - .ok_or_else(|| { - io::Error::new( - io::ErrorKind::Other, - "Cannot find clang executable", - ) - })?; + let clang = clang_sys::support::Clang::find(None, &[]).ok_or_else(|| { + io::Error::new(io::ErrorKind::Other, "Cannot find clang executable") + })?; // The contents of a wrapper file that includes all the input header // files. @@ -1184,7 +1209,6 @@ impl BindgenOptions { pub fn rust_features(&self) -> RustFeatures { self.rust_features } - } impl Default for BindgenOptions { @@ -1322,8 +1346,10 @@ impl<'ctx> Bindings<'ctx> { }; // TODO: Make this path fixup configurable? - if let Some(clang) = - clang_sys::support::Clang::find(None, &clang_args_for_clang_sys) + if let Some(clang) = clang_sys::support::Clang::find( + None, + &clang_args_for_clang_sys, + ) { // If --target is specified, assume caller knows what they're doing // and don't mess with include paths for them @@ -1378,8 +1404,9 @@ impl<'ctx> Bindings<'ctx> { let mut mod_str = vec![]; { let ref_writer = Box::new(mod_str.by_ref()) as Box; - self.write(ref_writer) - .expect("Could not write bindings to string"); + self.write(ref_writer).expect( + "Could not write bindings to string", + ); } String::from_utf8(mod_str).unwrap() } @@ -1565,24 +1592,25 @@ pub fn clang_version() -> ClangVersion { } let raw_v: String = clang::extract_clang_version(); - let split_v: Option> = raw_v - .split_whitespace() - .nth(2) - .map(|v| v.split('.').collect()); + let split_v: Option> = raw_v.split_whitespace().nth(2).map(|v| { + v.split('.').collect() + }); match split_v { - Some(v) => if v.len() >= 2 { - let maybe_major = v[0].parse::(); - let maybe_minor = v[1].parse::(); - match (maybe_major, maybe_minor) { - (Ok(major), Ok(minor)) => { - return ClangVersion { - parsed: Some((major, minor)), - full: raw_v.clone(), + Some(v) => { + if v.len() >= 2 { + let maybe_major = v[0].parse::(); + let maybe_minor = v[1].parse::(); + match (maybe_major, maybe_minor) { + (Ok(major), Ok(minor)) => { + return ClangVersion { + parsed: Some((major, minor)), + full: raw_v.clone(), + } } + _ => {} } - _ => {} } - }, + } None => {} }; ClangVersion { @@ -1606,11 +1634,9 @@ fn commandline_flag_unit_test_function() { .map(|&x| x.into()) .collect::>(); - assert!( - test_cases - .iter() - .all(|ref x| command_line_flags.contains(x),) - ); + assert!(test_cases.iter().all( + |ref x| command_line_flags.contains(x), + )); //Test 2 let bindings = ::builder() @@ -1633,10 +1659,8 @@ fn commandline_flag_unit_test_function() { .collect::>(); println!("{:?}", command_line_flags); - assert!( - test_cases - .iter() - .all(|ref x| command_line_flags.contains(x),) - ); + assert!(test_cases.iter().all( + |ref x| command_line_flags.contains(x), + )); } diff --git a/src/main.rs b/src/main.rs index 32248cb00f..dc3572b394 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,8 +1,8 @@ extern crate bindgen; -#[cfg(feature="logging")] +#[cfg(feature = "logging")] extern crate env_logger; #[macro_use] -#[cfg(feature="logging")] +#[cfg(feature = "logging")] extern crate log; extern crate clang_sys; extern crate clap; @@ -12,21 +12,20 @@ use std::env; use std::panic; #[macro_use] -#[cfg(not(feature="logging"))] +#[cfg(not(feature = "logging"))] mod log_stubs; mod options; use options::builder_from_flags; pub fn main() { - #[cfg(feature="logging")] + #[cfg(feature = "logging")] 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 bind_args: Vec<_> = env::args().collect(); @@ -65,8 +64,7 @@ pub fn main() { } let bindings = builder_result.unwrap(); - bindings.write(output) - .expect("Unable to write output"); + bindings.write(output).expect("Unable to write output"); } Err(error) => { println!("{}", error); @@ -77,10 +75,14 @@ pub fn main() { fn print_verbose_err() { println!("Bindgen unexpectedly panicked"); - println!("This may be caused by one of the known-unsupported \ + println!( + "This may be caused by one of the known-unsupported \ things (https://github.com/rust-lang-nursery/rust-bindgen#c), \ please modify the bindgen flags to work around it as \ - described in https://github.com/rust-lang-nursery/rust-bindgen#c"); - println!("Otherwise, please file an issue at \ - https://github.com/rust-lang-nursery/rust-bindgen/issues/new"); + described in https://github.com/rust-lang-nursery/rust-bindgen#c" + ); + println!( + "Otherwise, please file an issue at \ + https://github.com/rust-lang-nursery/rust-bindgen/issues/new" + ); } diff --git a/src/options.rs b/src/options.rs index a6a104d0ab..68b127ae0d 100644 --- a/src/options.rs +++ b/src/options.rs @@ -66,7 +66,8 @@ where .help("Avoid deriving Debug on any type."), Arg::with_name("impl-debug") .long("impl-debug") - .help("Create Debug implementation, if it can not be derived automatically."), + .help("Create Debug implementation, if it can not be derived \ + automatically."), Arg::with_name("no-derive-default") .long("no-derive-default") .hidden(true) diff --git a/src/parse.rs b/src/parse.rs index 73bb7b25d8..5869f302bf 100644 --- a/src/parse.rs +++ b/src/parse.rs @@ -34,61 +34,69 @@ pub trait ClangSubItemParser: Sized { /// /// 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, ParseError>; + fn parse( + cursor: clang::Cursor, + context: &mut BindgenContext, + ) -> Result, ParseError>; } /// An intermediate representation item that can be parsed from a Clang cursor. pub trait ClangItemParser: Sized { /// Parse this item from the given Clang cursor. - fn parse(cursor: clang::Cursor, - parent: Option, - context: &mut BindgenContext) - -> Result; + fn parse( + cursor: clang::Cursor, + parent: Option, + context: &mut BindgenContext, + ) -> Result; /// Parse this item from the given Clang type. - fn from_ty(ty: &clang::Type, - location: clang::Cursor, - parent: Option, - ctx: &mut BindgenContext) - -> Result; + fn from_ty( + ty: &clang::Type, + location: clang::Cursor, + parent: Option, + ctx: &mut BindgenContext, + ) -> Result; /// Identical to `from_ty`, but use the given `id` as the `ItemId` for the /// newly parsed item. - fn from_ty_with_id(id: ItemId, - ty: &clang::Type, - location: clang::Cursor, - parent: Option, - ctx: &mut BindgenContext) - -> Result; + fn from_ty_with_id( + id: ItemId, + ty: &clang::Type, + location: clang::Cursor, + parent: Option, + ctx: &mut BindgenContext, + ) -> Result; /// 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: clang::Cursor, - parent_id: Option, - context: &mut BindgenContext) - -> ItemId; + fn from_ty_or_ref( + ty: clang::Type, + location: clang::Cursor, + parent_id: Option, + context: &mut BindgenContext, + ) -> ItemId; /// Identical to `from_ty_or_ref`, but use the given `potential_id` as the /// `ItemId` for the newly parsed item. - fn from_ty_or_ref_with_id(potential_id: ItemId, - ty: clang::Type, - location: clang::Cursor, - parent_id: Option, - context: &mut BindgenContext) - -> ItemId; + fn from_ty_or_ref_with_id( + potential_id: ItemId, + ty: clang::Type, + location: clang::Cursor, + parent_id: Option, + context: &mut BindgenContext, + ) -> ItemId; /// Create a named template type. - fn named_type(with_id: Option, - location: clang::Cursor, - ctx: &mut BindgenContext) - -> Option; + fn type_param( + with_id: Option, + location: clang::Cursor, + ctx: &mut BindgenContext, + ) -> Option; /// 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 a93e7a1357..a6f51336f2 100644 --- a/src/regex_set.rs +++ b/src/regex_set.rs @@ -20,8 +20,9 @@ impl RegexSet { /// Extend this set with every regex in the iterator. pub fn extend(&mut self, iter: I) - where I: IntoIterator, - S: AsRef, + where + I: IntoIterator, + S: AsRef, { for s in iter.into_iter() { self.insert(s) @@ -30,12 +31,13 @@ impl RegexSet { /// Insert a new regex into this set. pub fn insert(&mut self, string: S) - where S: AsRef, + where + S: AsRef, { self.items.push(format!("^{}$", string.as_ref())); self.set = None; } - + /// Returns slice of String from its field 'items' pub fn get_items(&self) -> &[String] { &self.items[..] @@ -61,10 +63,13 @@ impl RegexSet { /// Does the given `string` match any of the regexes in this set? pub fn matches(&self, string: S) -> bool - where S: AsRef, + where + S: AsRef, { let s = string.as_ref(); - self.set.as_ref().map(|set| set.is_match(s)).unwrap_or(false) + self.set.as_ref().map(|set| set.is_match(s)).unwrap_or( + false, + ) } } diff --git a/tests/stylo_sanity.rs b/tests/stylo_sanity.rs index c8a8a0d50c..dfbfa9e3aa 100755 --- a/tests/stylo_sanity.rs +++ b/tests/stylo_sanity.rs @@ -1,27 +1,27 @@ -extern crate bindgen; - -/// A sanity test that we can generate bindings for Stylo. -/// -/// We don't assert on expected output because its just too big. The output will -/// change too often, and it won't be clear what is going on at a glance, unlike -/// the other tests with smaller input headers. -/// -/// This test is relatively slow, so we also only run it in release mode. -/// -/// Finally, uncomment the `panic!` at the bottom of the test to get logs timing -/// how long bindings generation takes for Stylo. Stylo bindings generation -/// takes too long to be a proper `#[bench]`. -#[test] -#[cfg(not(any(debug_assertions, - feature = "testing_only_extra_assertions", - feature = "testing_only_libclang_3_8")))] -#[cfg(any(feature = "testing_only_libclang_3_9", - feature = "testing_only_libclang_4"))] -fn sanity_check_can_generate_stylo_bindings() { - use std::time::Instant; - - let then = Instant::now(); - +extern crate bindgen; + +/// A sanity test that we can generate bindings for Stylo. +/// +/// We don't assert on expected output because its just too big. The output will +/// change too often, and it won't be clear what is going on at a glance, unlike +/// the other tests with smaller input headers. +/// +/// This test is relatively slow, so we also only run it in release mode. +/// +/// Finally, uncomment the `panic!` at the bottom of the test to get logs timing +/// how long bindings generation takes for Stylo. Stylo bindings generation +/// takes too long to be a proper `#[bench]`. +#[test] +#[cfg(not(any(debug_assertions, + feature = "testing_only_extra_assertions", + feature = "testing_only_libclang_3_8")))] +#[cfg(any(feature = "testing_only_libclang_3_9", + feature = "testing_only_libclang_4"))] +fn sanity_check_can_generate_stylo_bindings() { + use std::time::Instant; + + let then = Instant::now(); + bindgen::builder() .header(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/stylo.hpp")) .whitelisted_function("Servo_.*") @@ -535,16 +535,18 @@ fn sanity_check_can_generate_stylo_bindings() { .clang_arg("-DOS_POSIX=1") .clang_arg("-DOS_LINUX=1") .generate() - .expect("Should generate stylo bindings"); - - let now = Instant::now(); - - println!(""); - println!(""); - println!("Generated Stylo bindings in: {:?}", - now.duration_since(then)); - println!(""); - println!(""); - - // panic!("Uncomment this line to get timing logs"); -} + .expect("Should generate stylo bindings"); + + let now = Instant::now(); + + println!(""); + println!(""); + println!( + "Generated Stylo bindings in: {:?}", + now.duration_since(then) + ); + println!(""); + println!(""); + + // panic!("Uncomment this line to get timing logs"); +} diff --git a/tests/tests.rs b/tests/tests.rs index cf04af5077..01f46ac6c3 100644 --- a/tests/tests.rs +++ b/tests/tests.rs @@ -8,15 +8,18 @@ use std::fs; use std::io::{BufRead, BufReader, Error, ErrorKind, Read, Write}; use std::path::PathBuf; -#[path="../src/options.rs"] +#[path = "../src/options.rs"] mod options; use options::builder_from_flags; -fn compare_generated_header(header: &PathBuf, - builder: Builder) - -> Result<(), Error> { - let file_name = try!(header.file_name() - .ok_or(Error::new(ErrorKind::Other, "spawn_bindgen expects a file"))); +fn compare_generated_header( + header: &PathBuf, + builder: Builder, +) -> Result<(), Error> { + let file_name = try!(header.file_name().ok_or(Error::new( + ErrorKind::Other, + "spawn_bindgen expects a file", + ))); let mut expected = PathBuf::from(header); expected.pop(); @@ -40,7 +43,7 @@ fn compare_generated_header(header: &PathBuf, expected.push("libclang-3.8"); } else { match clang_version().parsed { - None => {}, + None => {} Some(version) => { let (maj, min) = version; let version_str = if maj >= 4 { @@ -56,10 +59,12 @@ fn compare_generated_header(header: &PathBuf, expected.push(file_name); if !expected.is_file() { - panic!("missing test expectation file and/or 'testing_only_libclang_$VERSION' \ + panic!( + "missing test expectation file and/or 'testing_only_libclang_$VERSION' \ feature for header '{}'; looking for expectation file at '{}'", - header.display(), - expected.display()); + header.display(), + expected.display() + ); } } @@ -80,8 +85,10 @@ fn compare_generated_header(header: &PathBuf, if !output.is_empty() { return Ok(()); } - return Err(Error::new(ErrorKind::Other, - "Something's gone really wrong!")); + return Err(Error::new( + ErrorKind::Other, + "Something's gone really wrong!", + )); } println!("diff expected generated"); @@ -126,13 +133,15 @@ fn create_bindgen_builder(header: &PathBuf) -> Result, Error> { flags.extend(extra_flags.into_iter()); } else if line.contains("bindgen-osx-only") { let prepend_flags = ["--raw-line", "#![cfg(target_os=\"macos\")]"]; - flags = prepend_flags.into_iter() + flags = prepend_flags + .into_iter() .map(ToString::to_string) .chain(flags) .collect(); } else if line.contains("bindgen-generate-bindings-on-linux-only") && - !cfg!(target_os = "linux") { - return Ok(None); + !cfg!(target_os = "linux") + { + return Ok(None); } } @@ -155,25 +164,29 @@ fn create_bindgen_builder(header: &PathBuf) -> Result, Error> { // - add header filename as 1st element // - prepend raw lines so they're in the right order for expected output // - append the test header's bindgen flags - let header_str = try!(header.to_str() - .ok_or(Error::new(ErrorKind::Other, "Invalid header file name"))); - - let prepend = ["bindgen", - "--with-derive-default", - header_str, - "--raw-line", - "", - "--raw-line", - "#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)]", - "--raw-line", - ""]; - - let args = prepend.into_iter() - .map(ToString::to_string) - .chain(flags.into_iter()); - - builder_from_flags(args) - .map(|(builder, _, _)| Some(builder)) + let header_str = try!(header.to_str().ok_or(Error::new( + ErrorKind::Other, + "Invalid header file name", + ))); + + let prepend = [ + "bindgen", + "--with-derive-default", + header_str, + "--raw-line", + "", + "--raw-line", + "#![allow(dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals)]", + "--raw-line", + "", + ]; + + let args = prepend.into_iter().map(ToString::to_string).chain( + flags + .into_iter(), + ); + + builder_from_flags(args).map(|(builder, _, _)| Some(builder)) } macro_rules! test_header { @@ -207,24 +220,33 @@ fn test_header_contents() { .generate() .unwrap() .to_string(); - assert_eq!(bindings, "/* automatically generated by rust-bindgen */ + assert_eq!( + bindings, + "/* automatically generated by rust-bindgen */ extern \"C\" { pub fn foo(a: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; } -"); +" + ); } #[test] fn test_multiple_header_calls_in_builder() { let actual = builder() - .header(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/headers/func_ptr.h")) + .header(concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/headers/func_ptr.h" + )) .header(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/headers/char.h")) .generate() .unwrap() .to_string(); - let expected = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/expectations/tests/test_multiple_header_calls_in_builder.rs")); + let expected = include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/expectations/tests/test_multiple_header_calls_in_builder.rs" + )); if actual != expected { println!("Generated bindings differ from expected!"); @@ -247,19 +269,25 @@ fn test_multiple_header_calls_in_builder() { #[cfg(not(target_os = "windows"))] fn no_system_header_includes() { use std::process::Command; - assert!(Command::new("./ci/no-includes.sh") + assert!( + Command::new("./ci/no-includes.sh") .current_dir(env!("CARGO_MANIFEST_DIR")) .spawn() .expect("should spawn ./ci/no-includes.sh OK") .wait() .expect("should wait for ./ci/no-includes OK") - .success()); + .success() + ); } #[test] fn dump_preprocessed_input() { - let arg_keyword = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/headers/arg_keyword.hpp"); - let empty_layout = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/headers/cpp-empty-layout.hpp"); + let arg_keyword = + concat!(env!("CARGO_MANIFEST_DIR"), "/tests/headers/arg_keyword.hpp"); + let empty_layout = concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/headers/cpp-empty-layout.hpp" + ); builder() .header(arg_keyword) @@ -278,8 +306,12 @@ fn dump_preprocessed_input() { let arg_keyword = slurp(arg_keyword); let empty_layout = slurp(empty_layout); - assert!(bindgen_ii.find(&arg_keyword).is_some(), - "arg_keyword.hpp is in the preprocessed file"); - assert!(bindgen_ii.find(&empty_layout).is_some(), - "cpp-empty-layout.hpp is in the preprocessed file"); + assert!( + bindgen_ii.find(&arg_keyword).is_some(), + "arg_keyword.hpp is in the preprocessed file" + ); + assert!( + bindgen_ii.find(&empty_layout).is_some(), + "cpp-empty-layout.hpp is in the preprocessed file" + ); }