diff --git a/build.rs b/build.rs index cb33217d10..acae6d6722 100644 --- a/build.rs +++ b/build.rs @@ -7,8 +7,8 @@ mod target { pub fn main() { let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap()); - let mut dst = File::create(Path::new(&out_dir).join("host-target.txt")) - .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(); } @@ -24,8 +24,8 @@ 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()); @@ -57,7 +57,8 @@ mod testgen { "test_header!(header_{}, {:?});", func, entry.path(), - ).unwrap(); + ) + .unwrap(); } _ => {} } diff --git a/ci/assert-rustfmt.sh b/ci/assert-rustfmt.sh index bd268600ec..de8ede82ca 100755 --- a/ci/assert-rustfmt.sh +++ b/ci/assert-rustfmt.sh @@ -3,14 +3,10 @@ set -xeu cd "$(dirname "$0")/.." -# Ensure we have the most up-to-date `rustfmt`. -cargo install -f rustfmt +rustup update nightly +rustup component add rustfmt --toolchain nightly # Run `rustfmt` on the crate! If `rustfmt` can't make a long line shorter, it # prints an error and exits non-zero, so tell it to kindly shut its yapper and # make sure it doesn't cause us to exit this whole script non-zero. -cargo fmt --quiet || true - -# Exit non-zero if this resulted in any diffs. -./ci/assert-no-diff.sh - +rustup run nightly cargo fmt -- --check diff --git a/ci/script.sh b/ci/script.sh index 7003618a56..73c5614b54 100755 --- a/ci/script.sh +++ b/ci/script.sh @@ -45,8 +45,7 @@ case "$BINDGEN_JOB" in ./ci/assert-docs.sh ./ci/test-book.sh ./ci/no-includes.sh - # `rustfmt` isn't reaching a fixed point on bindgen - # code... https://github.com/rust-lang/rustfmt/issues/1376 + # Disabled because https://github.com/rust-lang/rustfmt/issues/3799. # ./ci/assert-rustfmt.sh ;; diff --git a/rustfmt.toml b/rustfmt.toml index d0a32d00e3..092e69c1d5 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -1,5 +1,2 @@ max_width = 80 -brace_style = "SameLineWhere" -struct_lit_single_line = false -where_trailing_comma = true -normalize_comments = false +binop_separator = "back" diff --git a/src/callbacks.rs b/src/callbacks.rs index 81fe0c0eb6..91920738d6 100644 --- a/src/callbacks.rs +++ b/src/callbacks.rs @@ -37,8 +37,7 @@ pub trait ParseCallbacks: fmt::Debug + UnwindSafe { /// This will be run on every string macro. The callback can not influence the further /// treatment of the macro, but may use the value to generate additional code or configuration. - fn str_macro(&self, _name: &str, _value: &[u8]) { - } + fn str_macro(&self, _name: &str, _value: &[u8]) {} /// This function should return whether, given an enum variant /// name, and value, this enum variant will forcibly be a constant. diff --git a/src/clang.rs b/src/clang.rs index b470e224ad..9af6b46d3e 100644 --- a/src/clang.rs +++ b/src/clang.rs @@ -6,14 +6,14 @@ use cexpr; use clang_sys::*; -use regex; use ir::context::BindgenContext; -use std::{mem, ptr, slice}; +use regex; use std::ffi::{CStr, CString}; use std::fmt; use std::hash::Hash; use std::hash::Hasher; -use std::os::raw::{c_char, c_int, c_uint, c_ulong, c_longlong, c_ulonglong}; +use std::os::raw::{c_char, c_int, c_longlong, c_uint, c_ulong, c_ulonglong}; +use std::{mem, ptr, slice}; /// A cursor into the Clang AST, pointing to an AST node. /// @@ -43,7 +43,11 @@ impl Cursor { /// The USR can be used to compare entities across translation units. pub fn usr(&self) -> Option { let s = unsafe { cxstring_into_string(clang_getCursorUSR(self.x)) }; - if s.is_empty() { None } else { Some(s) } + if s.is_empty() { + None + } else { + Some(s) + } } /// Is this cursor's referent a declaration? @@ -210,8 +214,9 @@ impl Cursor { 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.unwrap().kind() == + CXCursor_NamespaceAlias || + semantic_parent.unwrap().kind() == CXCursor_NamespaceRef) { semantic_parent = semantic_parent.unwrap().fallible_semantic_parent(); @@ -300,7 +305,11 @@ impl Cursor { let s = unsafe { cxstring_into_string(clang_Cursor_getRawCommentText(self.x)) }; - if s.is_empty() { None } else { Some(s) } + if s.is_empty() { + None + } else { + Some(s) + } } /// Get the referent's parsed comment. @@ -346,7 +355,11 @@ impl Cursor { x: clang_getCursorReferenced(self.x), }; - if ret.is_valid() { Some(ret) } else { None } + if ret.is_valid() { + Some(ret) + } else { + None + } } } @@ -371,7 +384,11 @@ impl Cursor { let ret = Cursor { x: clang_getSpecializedCursorTemplate(self.x), }; - if ret.is_valid() { Some(ret) } else { None } + if ret.is_valid() { + Some(ret) + } else { + None + } } } @@ -438,11 +455,13 @@ impl Cursor { pub fn contains_cursor(&self, kind: CXCursorKind) -> bool { let mut found = false; - self.visit(|c| if c.kind() == kind { - found = true; - CXChildVisit_Break - } else { - CXChildVisit_Continue + self.visit(|c| { + if c.kind() == kind { + found = true; + CXChildVisit_Break + } else { + CXChildVisit_Continue + } }); found @@ -459,7 +478,11 @@ impl Cursor { pub fn bit_width(&self) -> Option { unsafe { let w = clang_getFieldDeclBitWidth(self.x); - if w == -1 { None } else { Some(w as u32) } + if w == -1 { + None + } else { + Some(w as u32) + } } } @@ -470,7 +493,11 @@ impl Cursor { let t = Type { x: clang_getEnumDeclIntegerType(self.x), }; - if t.is_valid() { Some(t) } else { None } + if t.is_valid() { + Some(t) + } else { + None + } } } @@ -509,7 +536,8 @@ impl Cursor { self.visit(|cur| { if cur.kind() == CXCursor_UnexposedAttr { found_attr = cur.tokens().iter().any(|t| { - t.kind == CXToken_Identifier && t.spelling() == attr.as_bytes() + t.kind == CXToken_Identifier && + t.spelling() == attr.as_bytes() }); if found_attr { @@ -530,7 +558,11 @@ impl Cursor { x: unsafe { clang_getTypedefDeclUnderlyingType(self.x) }, }; - if inner.is_valid() { Some(inner) } else { None } + if inner.is_valid() { + Some(inner) + } else { + None + } } /// Get the linkage kind for this cursor's referent. @@ -559,12 +591,11 @@ impl Cursor { // CXCursor_FunctionDecl | // CXCursor_CXXMethod => { self.num_args().ok().map(|num| { - (0..num).map(|i| { - Cursor { + (0..num) + .map(|i| Cursor { x: unsafe { clang_Cursor_getArgument(self.x, i as c_uint) }, - } - }) - .collect() + }) + .collect() }) } @@ -576,7 +607,11 @@ impl Cursor { pub fn num_args(&self) -> Result { unsafe { let w = clang_Cursor_getNumArguments(self.x); - if w == -1 { Err(()) } else { Ok(w as u32) } + if w == -1 { + Err(()) + } else { + Ok(w as u32) + } } } @@ -642,7 +677,11 @@ impl Cursor { let rt = Type { x: unsafe { clang_getCursorResultType(self.x) }, }; - if rt.is_valid() { Some(rt) } else { None } + if rt.is_valid() { + Some(rt) + } else { + None + } } /// Gets the tokens that correspond to that cursor. @@ -654,26 +693,29 @@ impl Cursor { pub fn cexpr_tokens(self) -> Vec { use cexpr::token; - self.tokens().iter().filter_map(|token| { - let kind = match token.kind { - CXToken_Punctuation => token::Kind::Punctuation, - CXToken_Literal => token::Kind::Literal, - CXToken_Identifier => token::Kind::Identifier, - CXToken_Keyword => token::Kind::Keyword, - // NB: cexpr is not too happy about comments inside - // expressions, so we strip them down here. - CXToken_Comment => return None, - _ => { - error!("Found unexpected token kind: {:?}", token); - return None; - } - }; + self.tokens() + .iter() + .filter_map(|token| { + let kind = match token.kind { + CXToken_Punctuation => token::Kind::Punctuation, + CXToken_Literal => token::Kind::Literal, + CXToken_Identifier => token::Kind::Identifier, + CXToken_Keyword => token::Kind::Keyword, + // NB: cexpr is not too happy about comments inside + // expressions, so we strip them down here. + CXToken_Comment => return None, + _ => { + error!("Found unexpected token kind: {:?}", token); + return None; + } + }; - Some(token::Token { - kind, - raw: token.spelling().to_vec().into_boxed_slice(), + Some(token::Token { + kind, + raw: token.spelling().to_vec().into_boxed_slice(), + }) }) - }).collect() + .collect() } } @@ -690,11 +732,14 @@ impl<'a> RawTokens<'a> { let mut tokens = ptr::null_mut(); let mut token_count = 0; let range = cursor.extent(); - let tu = unsafe { - clang_Cursor_getTranslationUnit(cursor.x) - }; + let tu = unsafe { clang_Cursor_getTranslationUnit(cursor.x) }; unsafe { clang_tokenize(tu, range, &mut tokens, &mut token_count) }; - Self { cursor, tu, tokens, token_count } + Self { + cursor, + tu, + tokens, + token_count, + } } fn as_slice(&self) -> &[CXToken] { @@ -717,7 +762,11 @@ impl<'a> Drop for RawTokens<'a> { fn drop(&mut self) { if !self.tokens.is_null() { unsafe { - clang_disposeTokens(self.tu, self.tokens, self.token_count as c_uint); + clang_disposeTokens( + self.tu, + self.tokens, + self.token_count as c_uint, + ); } } } @@ -790,9 +839,7 @@ where Visitor: FnMut(Cursor) -> CXChildVisitResult, { let func: &mut Visitor = unsafe { mem::transmute(data) }; - let child = Cursor { - x: cur, - }; + let child = Cursor { x: cur }; (*func)(child) } @@ -942,8 +989,9 @@ impl Type { fn clang_size_of(&self, ctx: &BindgenContext) -> c_longlong { match self.kind() { // Work-around https://bugs.llvm.org/show_bug.cgi?id=40975 - CXType_RValueReference | - CXType_LValueReference => ctx.target_pointer_size() as c_longlong, + CXType_RValueReference | CXType_LValueReference => { + ctx.target_pointer_size() as c_longlong + } // Work-around https://bugs.llvm.org/show_bug.cgi?id=40813 CXType_Auto if self.is_non_deductible_auto_type() => return -6, _ => unsafe { clang_Type_getSizeOf(self.x) }, @@ -954,8 +1002,9 @@ impl Type { fn clang_align_of(&self, ctx: &BindgenContext) -> c_longlong { match self.kind() { // Work-around https://bugs.llvm.org/show_bug.cgi?id=40975 - CXType_RValueReference | - CXType_LValueReference => ctx.target_pointer_size() as c_longlong, + CXType_RValueReference | CXType_LValueReference => { + ctx.target_pointer_size() as c_longlong + } // Work-around https://bugs.llvm.org/show_bug.cgi?id=40813 CXType_Auto if self.is_non_deductible_auto_type() => return -6, _ => unsafe { clang_Type_getAlignOf(self.x) }, @@ -966,11 +1015,18 @@ impl Type { /// for them. pub fn size(&self, ctx: &BindgenContext) -> usize { let val = self.clang_size_of(ctx); - if val < 0 { 0 } else { val as usize } + if val < 0 { + 0 + } else { + val as usize + } } /// What is the size of this type? - pub fn fallible_size(&self, ctx: &BindgenContext) -> Result { + pub fn fallible_size( + &self, + ctx: &BindgenContext, + ) -> Result { let val = self.clang_size_of(ctx); if val < 0 { Err(LayoutError::from(val as i32)) @@ -983,11 +1039,18 @@ impl Type { /// returning `0`. pub fn align(&self, ctx: &BindgenContext) -> usize { let val = self.clang_align_of(ctx); - if val < 0 { 0 } else { val as usize } + if val < 0 { + 0 + } else { + val as usize + } } /// What is the alignment of this type? - pub fn fallible_align(&self, ctx: &BindgenContext) -> Result { + pub fn fallible_align( + &self, + ctx: &BindgenContext, + ) -> Result { let val = self.clang_align_of(ctx); if val < 0 { Err(LayoutError::from(val as i32)) @@ -998,7 +1061,10 @@ impl Type { /// Get the layout for this type, or an error describing why it does not /// have a valid layout. - pub fn fallible_layout(&self, ctx: &BindgenContext) -> Result<::ir::layout::Layout, LayoutError> { + pub fn fallible_layout( + &self, + ctx: &BindgenContext, + ) -> Result<::ir::layout::Layout, LayoutError> { use ir::layout::Layout; let size = self.fallible_size(ctx)?; let align = self.fallible_align(ctx)?; @@ -1012,7 +1078,7 @@ impl Type { // 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 + return None; } let n = unsafe { clang_Type_getNumTemplateArguments(self.x) }; @@ -1027,12 +1093,10 @@ impl Type { /// If this type is a class template specialization, return its /// template arguments. Otherwise, return None. pub fn template_args(&self) -> Option { - self.num_template_args().map(|n| { - TypeTemplateArgIterator { - x: self.x, - length: n, - index: 0, - } + self.num_template_args().map(|n| TypeTemplateArgIterator { + x: self.x, + length: n, + index: 0, }) } @@ -1041,12 +1105,11 @@ impl Type { /// Returns None if the type is not a function prototype. pub fn args(&self) -> Option> { self.num_args().ok().map(|num| { - (0..num).map(|i| { - Type { + (0..num) + .map(|i| Type { x: unsafe { clang_getArgType(self.x, i as c_uint) }, - } - }) - .collect() + }) + .collect() }) } @@ -1056,11 +1119,14 @@ impl Type { pub fn num_args(&self) -> Result { unsafe { let w = clang_getNumArgTypes(self.x); - if w == -1 { Err(()) } else { Ok(w as u32) } + if w == -1 { + Err(()) + } else { + Ok(w as u32) + } } } - /// Given that this type is a pointer type, return the type that it points /// to. pub fn pointee_type(&self) -> Option { @@ -1126,7 +1192,11 @@ impl Type { let rt = Type { x: unsafe { clang_getResultType(self.x) }, }; - if rt.is_valid() { Some(rt) } else { None } + if rt.is_valid() { + Some(rt) + } else { + None + } } /// Given that this type is a function type, get its calling convention. If @@ -1186,15 +1256,19 @@ impl Type { // This is terrible :( fn hacky_parse_associated_type>(spelling: S) -> bool { lazy_static! { - static ref ASSOC_TYPE_RE: regex::Regex = - regex::Regex::new(r"typename type\-parameter\-\d+\-\d+::.+").unwrap(); + static ref ASSOC_TYPE_RE: regex::Regex = regex::Regex::new( + r"typename type\-parameter\-\d+\-\d+::.+" + ) + .unwrap(); } ASSOC_TYPE_RE.is_match(spelling.as_ref()) } self.kind() == CXType_Unexposed && (hacky_parse_associated_type(self.spelling()) || - hacky_parse_associated_type(self.canonical_type().spelling())) + hacky_parse_associated_type( + self.canonical_type().spelling(), + )) } } @@ -1263,20 +1337,9 @@ impl SourceLocation { let mut col = 0; let mut off = 0; clang_getSpellingLocation( - self.x, - &mut file, - &mut line, - &mut col, - &mut off, + self.x, &mut file, &mut line, &mut col, &mut off, ); - ( - File { - x: file, - }, - line as usize, - col as usize, - off as usize, - ) + (File { x: file }, line as usize, col as usize, off as usize) } } } @@ -1375,14 +1438,14 @@ impl Iterator for CommentAttributesIterator { self.index += 1; Some(CommentAttribute { name: unsafe { - cxstring_into_string( - clang_HTMLStartTag_getAttrName(self.x, idx), - ) + cxstring_into_string(clang_HTMLStartTag_getAttrName( + self.x, idx, + )) }, value: unsafe { - cxstring_into_string( - clang_HTMLStartTag_getAttrValue(self.x, idx), - ) + cxstring_into_string(clang_HTMLStartTag_getAttrValue( + self.x, idx, + )) }, }) } else { @@ -1508,9 +1571,7 @@ impl TranslationUnit { if tu.is_null() { None } else { - Some(TranslationUnit { - x: tu, - }) + Some(TranslationUnit { x: tu }) } } @@ -1552,7 +1613,6 @@ impl Drop for TranslationUnit { } } - /// A diagnostic message generated while parsing a translation unit. pub struct Diagnostic { x: CXDiagnostic, @@ -1615,8 +1675,7 @@ impl fmt::Debug for UnsavedFile { write!( fmt, "UnsavedFile(name: {:?}, contents: {:?})", - self.name, - self.contents + self.name, self.contents ) } } @@ -1672,7 +1731,11 @@ pub fn ast_dump(c: &Cursor, depth: isize) -> CXChildVisitResult { if templ_kind != CXCursor_NoDeclFound { print_indent( depth, - format!(" {}template-kind = {}", prefix, kind_to_str(templ_kind)), + format!( + " {}template-kind = {}", + prefix, + kind_to_str(templ_kind) + ), ); } if let Some(usr) = c.usr() { @@ -1769,18 +1832,18 @@ pub fn ast_dump(c: &Cursor, depth: isize) -> CXChildVisitResult { depth, format!(" {}spelling = \"{}\"", prefix, ty.spelling()), ); - let num_template_args = if clang_Type_getNumTemplateArguments::is_loaded() { - unsafe { clang_Type_getNumTemplateArguments(ty.x) } - } else { - -1 - }; + let num_template_args = + if clang_Type_getNumTemplateArguments::is_loaded() { + unsafe { clang_Type_getNumTemplateArguments(ty.x) } + } else { + -1 + }; if num_template_args >= 0 { print_indent( depth, format!( " {}number-of-template-args = {}", - prefix, - num_template_args + prefix, num_template_args ), ); } @@ -1882,7 +1945,8 @@ impl EvalResult { let mut found_cant_eval = false; cursor.visit(|c| { if c.kind() == CXCursor_TypeRef && - c.cur_type().canonical_type().kind() == CXType_Unexposed { + c.cur_type().canonical_type().kind() == CXType_Unexposed + { found_cant_eval = true; return CXChildVisit_Break; } @@ -1922,7 +1986,7 @@ impl EvalResult { if !clang_EvalResult_isUnsignedInt::is_loaded() { // FIXME(emilio): There's no way to detect underflow here, and clang // will just happily give us a value. - return Some(unsafe { clang_EvalResult_getAsInt(self.x) } as i64) + return Some(unsafe { clang_EvalResult_getAsInt(self.x) } as i64); } if unsafe { clang_EvalResult_isUnsignedInt(self.x) } != 0 { @@ -1931,7 +1995,7 @@ impl EvalResult { return None; } - return Some(value as i64) + return Some(value as i64); } let value = unsafe { clang_EvalResult_getAsLongLong(self.x) }; diff --git a/src/codegen/bitfield_unit.rs b/src/codegen/bitfield_unit.rs index caab2dc69a..a5a8ac77d4 100755 --- a/src/codegen/bitfield_unit.rs +++ b/src/codegen/bitfield_unit.rs @@ -1,19 +1,14 @@ #[repr(C)] #[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)] -pub struct __BindgenBitfieldUnit -{ +pub struct __BindgenBitfieldUnit { storage: Storage, align: [Align; 0], } -impl __BindgenBitfieldUnit -{ +impl __BindgenBitfieldUnit { #[inline] pub const fn new(storage: Storage) -> Self { - Self { - storage, - align: [], - } + Self { storage, align: [] } } } @@ -28,12 +23,11 @@ where let byte_index = index / 8; let byte = self.storage.as_ref()[byte_index]; - let bit_index = - if cfg!(target_endian = "big") { - 7 - (index % 8) - } else { - index % 8 - }; + let bit_index = if cfg!(target_endian = "big") { + 7 - (index % 8) + } else { + index % 8 + }; let mask = 1 << bit_index; @@ -47,12 +41,11 @@ where let byte_index = index / 8; let byte = &mut self.storage.as_mut()[byte_index]; - let bit_index = - if cfg!(target_endian = "big") { - 7 - (index % 8) - } else { - index % 8 - }; + let bit_index = if cfg!(target_endian = "big") { + 7 - (index % 8) + } else { + index % 8 + }; let mask = 1 << bit_index; if val { @@ -66,18 +59,20 @@ where pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 { debug_assert!(bit_width <= 64); debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); - debug_assert!((bit_offset + (bit_width as usize)) / 8 <= self.storage.as_ref().len()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= + self.storage.as_ref().len() + ); let mut val = 0; for i in 0..(bit_width as usize) { if self.get_bit(i + bit_offset) { - let index = - if cfg!(target_endian = "big") { - bit_width as usize - 1 - i - } else { - i - }; + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; val |= 1 << index; } } @@ -89,17 +84,19 @@ where pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) { debug_assert!(bit_width <= 64); debug_assert!(bit_offset / 8 < self.storage.as_ref().len()); - debug_assert!((bit_offset + (bit_width as usize)) / 8 <= self.storage.as_ref().len()); + debug_assert!( + (bit_offset + (bit_width as usize)) / 8 <= + self.storage.as_ref().len() + ); for i in 0..(bit_width as usize) { let mask = 1 << i; let val_bit_is_set = val & mask == mask; - let index = - if cfg!(target_endian = "big") { - bit_width as usize - 1 - i - } else { - i - }; + let index = if cfg!(target_endian = "big") { + bit_width as usize - 1 - i + } else { + i + }; self.set_bit(index + bit_offset, val_bit_is_set); } } diff --git a/src/codegen/bitfield_unit_tests.rs b/src/codegen/bitfield_unit_tests.rs index d39878ccd9..3a9239c2c8 100644 --- a/src/codegen/bitfield_unit_tests.rs +++ b/src/codegen/bitfield_unit_tests.rs @@ -26,7 +26,8 @@ use std::mem; #[test] fn bitfield_unit_get_bit() { - let unit = __BindgenBitfieldUnit::<[u8; 2], u64>::new([0b10011101, 0b00011101]); + let unit = + __BindgenBitfieldUnit::<[u8; 2], u64>::new([0b10011101, 0b00011101]); let mut bits = vec![]; for i in 0..16 { @@ -35,32 +36,21 @@ fn bitfield_unit_get_bit() { println!(); println!("bits = {:?}", bits); - assert_eq!(bits, &[ - // 0b10011101 - true, - false, - true, - true, - true, - false, - false, - true , - - // 0b00011101 - true, - false, - true, - true, - true, - false, - false, - false - ]); + assert_eq!( + bits, + &[ + // 0b10011101 + true, false, true, true, true, false, false, true, + // 0b00011101 + true, false, true, true, true, false, false, false + ] + ); } #[test] fn bitfield_unit_set_bit() { - let mut unit = __BindgenBitfieldUnit::<[u8; 2], u64>::new([0b00000000, 0b00000000]); + let mut unit = + __BindgenBitfieldUnit::<[u8; 2], u64>::new([0b00000000, 0b00000000]); for i in 0..16 { if i % 3 == 0 { @@ -72,7 +62,8 @@ fn bitfield_unit_set_bit() { assert_eq!(unit.get_bit(i), i % 3 == 0); } - let mut unit = __BindgenBitfieldUnit::<[u8; 2], u64>::new([0b11111111, 0b11111111]); + let mut unit = + __BindgenBitfieldUnit::<[u8; 2], u64>::new([0b11111111, 0b11111111]); for i in 0..16 { if i % 3 == 0 { @@ -87,15 +78,39 @@ fn bitfield_unit_set_bit() { #[test] fn bitfield_unit_align() { - assert_eq!(mem::align_of::<__BindgenBitfieldUnit<[u8; 1], u8>>(), mem::align_of::()); - assert_eq!(mem::align_of::<__BindgenBitfieldUnit<[u8; 1], u16>>(), mem::align_of::()); - assert_eq!(mem::align_of::<__BindgenBitfieldUnit<[u8; 1], u32>>(), mem::align_of::()); - assert_eq!(mem::align_of::<__BindgenBitfieldUnit<[u8; 1], u64>>(), mem::align_of::()); - - assert_eq!(mem::align_of::<__BindgenBitfieldUnit<[u8; 8], u8>>(), mem::align_of::()); - assert_eq!(mem::align_of::<__BindgenBitfieldUnit<[u8; 8], u16>>(), mem::align_of::()); - assert_eq!(mem::align_of::<__BindgenBitfieldUnit<[u8; 8], u32>>(), mem::align_of::()); - assert_eq!(mem::align_of::<__BindgenBitfieldUnit<[u8; 8], u64>>(), mem::align_of::()); + assert_eq!( + mem::align_of::<__BindgenBitfieldUnit<[u8; 1], u8>>(), + mem::align_of::() + ); + assert_eq!( + mem::align_of::<__BindgenBitfieldUnit<[u8; 1], u16>>(), + mem::align_of::() + ); + assert_eq!( + mem::align_of::<__BindgenBitfieldUnit<[u8; 1], u32>>(), + mem::align_of::() + ); + assert_eq!( + mem::align_of::<__BindgenBitfieldUnit<[u8; 1], u64>>(), + mem::align_of::() + ); + + assert_eq!( + mem::align_of::<__BindgenBitfieldUnit<[u8; 8], u8>>(), + mem::align_of::() + ); + assert_eq!( + mem::align_of::<__BindgenBitfieldUnit<[u8; 8], u16>>(), + mem::align_of::() + ); + assert_eq!( + mem::align_of::<__BindgenBitfieldUnit<[u8; 8], u32>>(), + mem::align_of::() + ); + assert_eq!( + mem::align_of::<__BindgenBitfieldUnit<[u8; 8], u64>>(), + mem::align_of::() + ); } macro_rules! bitfield_unit_get { diff --git a/src/codegen/helpers.rs b/src/codegen/helpers.rs index 1e8534ee09..b1cf2050e6 100644 --- a/src/codegen/helpers.rs +++ b/src/codegen/helpers.rs @@ -17,14 +17,20 @@ pub mod attributes { } pub fn repr_list(which_ones: &[&str]) -> TokenStream { - let which_ones = which_ones.iter().cloned().map(|one| TokenStream::from_str(one).expect("repr to be valid")); + let which_ones = which_ones + .iter() + .cloned() + .map(|one| TokenStream::from_str(one).expect("repr to be valid")); quote! { #[repr( #( #which_ones ),* )] } } pub fn derives(which_ones: &[&str]) -> TokenStream { - let which_ones = which_ones.iter().cloned().map(|one| Ident::new(one, Span::call_site())); + let which_ones = which_ones + .iter() + .cloned() + .map(|one| Ident::new(one, Span::call_site())); quote! { #[derive( #( #which_ones ),* )] } @@ -97,7 +103,10 @@ pub fn blob(ctx: &BindgenContext, layout: Layout) -> TokenStream { } /// Integer type of the same size as the given `Layout`. -pub fn integer_type(ctx: &BindgenContext, layout: Layout) -> Option { +pub fn integer_type( + ctx: &BindgenContext, + layout: Layout, +) -> Option { let name = Layout::known_type_for_size(ctx, layout.size)?; let name = Ident::new(name, Span::call_site()); Some(quote! { #name }) @@ -131,8 +140,8 @@ pub mod ast_ty { use ir::function::FunctionSig; use ir::layout::Layout; use ir::ty::FloatKind; - use std::str::FromStr; use proc_macro2::{self, TokenStream}; + use std::str::FromStr; pub fn raw_type(ctx: &BindgenContext, name: &str) -> TokenStream { let ident = ctx.rust_ident_raw(name); @@ -171,7 +180,8 @@ pub mod ast_ty { 8 => quote! { f64 }, // TODO(emilio): If rust ever gains f128 we should // use it here and below. - _ => super::integer_type(ctx, layout).unwrap_or(quote! { f64 }), + _ => super::integer_type(ctx, layout) + .unwrap_or(quote! { f64 }), } } None => { @@ -219,10 +229,7 @@ pub mod ast_ty { } } - pub fn float_expr( - ctx: &BindgenContext, - f: f64, - ) -> Result { + pub fn float_expr(ctx: &BindgenContext, f: f64) -> Result { if f.is_finite() { let val = proc_macro2::Literal::f64_unsuffixed(f); @@ -261,17 +268,16 @@ pub mod ast_ty { signature .argument_types() .iter() - .map(|&(ref name, _ty)| { - match *name { - Some(ref name) => { - let name = ctx.rust_ident(name); - quote! { #name } - } - None => { - unnamed_arguments += 1; - let name = ctx.rust_ident(format!("arg{}", unnamed_arguments)); - quote! { #name } - } + .map(|&(ref name, _ty)| match *name { + Some(ref name) => { + let name = ctx.rust_ident(name); + quote! { #name } + } + None => { + unnamed_arguments += 1; + let name = + ctx.rust_ident(format!("arg{}", unnamed_arguments)); + quote! { #name } } }) .collect() diff --git a/src/codegen/impl_debug.rs b/src/codegen/impl_debug.rs index fd4865111b..eac54fd16b 100644 --- a/src/codegen/impl_debug.rs +++ b/src/codegen/impl_debug.rs @@ -1,7 +1,7 @@ use ir::comp::{BitfieldUnit, CompKind, Field, FieldData, FieldMethods}; use ir::context::BindgenContext; use ir::item::{HasTypeParamInArray, IsOpaque, Item, ItemCanonicalName}; -use ir::ty::{RUST_DERIVE_IN_ARRAY_LIMIT, TypeKind}; +use ir::ty::{TypeKind, RUST_DERIVE_IN_ARRAY_LIMIT}; use proc_macro2; pub fn gen_debug_impl( @@ -177,9 +177,10 @@ impl<'a> ImplDebug<'a> for Item { 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(name, quote! { #name_ident }) @@ -187,9 +188,7 @@ impl<'a> ImplDebug<'a> for Item { if ctx.options().use_core { // There is no String in core; reducing field visibility to avoid breaking // no_std setups. - Some(( - format!("{}: [...]", name), vec![] - )) + Some((format!("{}: [...]", name), vec![])) } else { // Let's implement our own print function Some(( @@ -209,16 +208,14 @@ impl<'a> ImplDebug<'a> for Item { if ctx.options().use_core { // There is no format! in core; reducing field visibility to avoid breaking // no_std setups. - Some(( - format!("{}(...)", name), vec![] - )) + Some((format!("{}(...)", name), vec![])) } else { let self_ids = 0..len; Some(( format!("{}({{}})", name), vec![quote! { #(format!("{:?}", self.#self_ids)),* - }] + }], )) } } @@ -235,8 +232,9 @@ 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.function_pointers_can_derive() => { - Some((format!("{}: FunctionPointer", name), vec![])) + if !sig.function_pointers_can_derive() => + { + Some((format!("{}: FunctionPointer", name), vec![])) } _ => debug_print(name, quote! { #name_ident }), } diff --git a/src/codegen/impl_partialeq.rs b/src/codegen/impl_partialeq.rs index ca61b4bf49..d73f36bb4e 100644 --- a/src/codegen/impl_partialeq.rs +++ b/src/codegen/impl_partialeq.rs @@ -1,4 +1,3 @@ - use ir::comp::{CompInfo, CompKind, Field, FieldMethods}; use ir::context::BindgenContext; use ir::item::{IsOpaque, Item}; @@ -50,15 +49,17 @@ pub fn gen_partialeq_impl( let name = fd.name().unwrap(); tokens.push(gen_field(ctx, ty_item, name)); } - Field::Bitfields(ref bu) => for bitfield in bu.bitfields() { - if let Some(_) = bitfield.name() { - let getter_name = bitfield.getter_name(); - let name_ident = ctx.rust_ident_raw(getter_name); - tokens.push(quote! { - self.#name_ident () == other.#name_ident () - }); + Field::Bitfields(ref bu) => { + for bitfield in bu.bitfields() { + if let Some(_) = bitfield.name() { + let getter_name = bitfield.getter_name(); + let name_ident = ctx.rust_ident_raw(getter_name); + tokens.push(quote! { + self.#name_ident () == other.#name_ident () + }); + } } - }, + } } } } @@ -70,8 +71,14 @@ pub fn gen_partialeq_impl( }) } -fn gen_field(ctx: &BindgenContext, ty_item: &Item, name: &str) -> proc_macro2::TokenStream { - fn quote_equals(name_ident: proc_macro2::Ident) -> proc_macro2::TokenStream { +fn gen_field( + ctx: &BindgenContext, + ty_item: &Item, + name: &str, +) -> proc_macro2::TokenStream { + fn quote_equals( + name_ident: proc_macro2::Ident, + ) -> proc_macro2::TokenStream { quote! { self.#name_ident == other.#name_ident } } @@ -106,20 +113,22 @@ fn gen_field(ctx: &BindgenContext, ty_item: &Item, name: &str) -> proc_macro2::T } } - TypeKind::Array(_, len) => if len <= RUST_DERIVE_IN_ARRAY_LIMIT { - quote_equals(name_ident) - } else { - quote! { - &self. #name_ident [..] == &other. #name_ident [..] + TypeKind::Array(_, len) => { + if len <= RUST_DERIVE_IN_ARRAY_LIMIT { + quote_equals(name_ident) + } else { + quote! { + &self. #name_ident [..] == &other. #name_ident [..] + } } - }, + } TypeKind::Vector(_, len) => { let self_ids = 0..len; let other_ids = 0..len; quote! { #(self.#self_ids == other.#other_ids &&)* true } - }, + } TypeKind::ResolvedTypeRef(t) | TypeKind::TemplateAlias(t, _) | diff --git a/src/codegen/mod.rs b/src/codegen/mod.rs index 8e1eded25e..c7f1b2bdb3 100644 --- a/src/codegen/mod.rs +++ b/src/codegen/mod.rs @@ -1,7 +1,7 @@ -mod impl_debug; -mod impl_partialeq; mod error; mod helpers; +mod impl_debug; +mod impl_partialeq; pub mod struct_layout; #[cfg(test)] @@ -18,12 +18,15 @@ use super::BindgenOptions; use ir::analysis::{HasVtable, Sizedness}; use ir::annotations::FieldAccessorKind; use ir::comment; -use ir::comp::{Base, Bitfield, BitfieldUnit, CompInfo, CompKind, Field, - FieldData, FieldMethods, Method, MethodKind}; +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, CanDerivePartialOrd, CanDeriveOrd, - CanDerivePartialEq, CanDeriveEq, CanDerive}; +use ir::derive::{ + CanDerive, CanDeriveCopy, CanDeriveDebug, CanDeriveDefault, CanDeriveEq, + CanDeriveHash, CanDeriveOrd, CanDerivePartialEq, CanDerivePartialOrd, +}; use ir::dot; use ir::enum_ty::{Enum, EnumVariant, EnumVariantValue}; use ir::function::{Abi, Function, FunctionKind, FunctionSig, Linkage}; @@ -33,12 +36,14 @@ use ir::item_kind::ItemKind; use ir::layout::Layout; use ir::module::Module; use ir::objc::{ObjCInterface, ObjCMethod}; -use ir::template::{AsTemplateParam, TemplateInstantiation, TemplateParameters}; +use ir::template::{ + AsTemplateParam, TemplateInstantiation, TemplateParameters, +}; use ir::ty::{Type, TypeKind}; use ir::var::Var; -use quote::TokenStreamExt; use proc_macro2::{self, Ident, Span}; +use quote::TokenStreamExt; use std; use std::borrow::Cow; @@ -48,12 +53,15 @@ use std::fmt::Write; use std::iter; use std::ops; use std::str::FromStr; -use {HashMap, HashSet, Entry}; +use {Entry, HashMap, HashSet}; // Name of type defined in constified enum module pub static CONSTIFIED_ENUM_MODULE_REPR_NAME: &'static str = "Type"; -fn top_level_path(ctx: &BindgenContext, item: &Item) -> Vec { +fn top_level_path( + ctx: &BindgenContext, + item: &Item, +) -> Vec { let mut path = vec![quote! { self }]; if ctx.options().enable_cxx_namespaces { @@ -65,7 +73,10 @@ fn top_level_path(ctx: &BindgenContext, item: &Item) -> Vec proc_macro2::TokenStream { +fn root_import( + ctx: &BindgenContext, + module: &Item, +) -> proc_macro2::TokenStream { assert!(ctx.options().enable_cxx_namespaces, "Somebody messed it up"); assert!(module.is_module()); @@ -75,7 +86,6 @@ fn root_import(ctx: &BindgenContext, module: &Item) -> proc_macro2::TokenStream let root_ident = ctx.rust_ident(&root); path.push(quote! { #root_ident }); - let mut tokens = quote! {}; tokens.append_separated(path, quote!(::)); @@ -268,10 +278,7 @@ impl AppendImplicitTemplateParams for proc_macro2::TokenStream { ctx: &BindgenContext, item: &Item, ) { - let item = item.id() - .into_resolver() - .through_type_refs() - .resolve(ctx); + let item = item.id().into_resolver().through_type_refs().resolve(ctx); match *item.expect_type().kind() { TypeKind::UnresolvedTypeRef(..) => { @@ -297,13 +304,17 @@ impl AppendImplicitTemplateParams for proc_macro2::TokenStream { TypeKind::ObjCId | TypeKind::ObjCSel | TypeKind::TemplateInstantiation(..) => return, - _ => {}, + _ => {} } - let params: Vec<_> = item.used_template_params(ctx).iter().map(|p| { - p.try_to_rust_ty(ctx, &()) - .expect("template params cannot fail to be a rust type") - }).collect(); + let params: Vec<_> = item + .used_template_params(ctx) + .iter() + .map(|p| { + p.try_to_rust_ty(ctx, &()) + .expect("template params cannot fail to be a rust type") + }) + .collect(); if !params.is_empty() { self.append_all(quote! { < #( #params ),* > @@ -431,7 +442,9 @@ impl CodeGenerator for Module { if let Some(raw_lines) = ctx.options().module_lines.get(&path) { for raw_line in raw_lines { found_any = true; - result.push(proc_macro2::TokenStream::from_str(raw_line).unwrap()); + result.push( + proc_macro2::TokenStream::from_str(raw_line).unwrap(), + ); } } @@ -500,7 +513,8 @@ impl CodeGenerator for Var { }); } VarType::Int(val) => { - let int_kind = self.ty() + let int_kind = self + .ty() .into_resolver() .through_type_aliases() .through_type_refs() @@ -570,7 +584,7 @@ impl CodeGenerator for Var { } let maybe_mut = if self.is_const() { - quote! { } + quote! {} } else { quote! { mut } }; @@ -627,13 +641,14 @@ impl CodeGenerator for Type { return; } - let inner_item = inner.into_resolver() - .through_type_refs() - .resolve(ctx); + let inner_item = + inner.into_resolver().through_type_refs().resolve(ctx); let name = item.canonical_name(ctx); let inner_rust_type = { - if let TypeKind::Function(fnsig) = inner_item.kind().expect_type().kind() { + if let TypeKind::Function(fnsig) = + inner_item.kind().expect_type().kind() + { utils::fnsig_block(ctx, fnsig) } else { panic!("invalid block typedef: {:?}", inner_item) @@ -656,16 +671,15 @@ impl CodeGenerator for Type { result.saw_block(); } TypeKind::Comp(ref ci) => ci.codegen(ctx, result, item), - TypeKind::TemplateAlias(inner, _) | - TypeKind::Alias(inner) => { - let inner_item = inner.into_resolver() - .through_type_refs() - .resolve(ctx); + TypeKind::TemplateAlias(inner, _) | TypeKind::Alias(inner) => { + let inner_item = + inner.into_resolver().through_type_refs().resolve(ctx); let name = item.canonical_name(ctx); let path = item.canonical_path(ctx); { - let through_type_aliases = inner.into_resolver() + let through_type_aliases = inner + .into_resolver() .through_type_refs() .through_type_aliases() .resolve(ctx); @@ -720,8 +734,7 @@ impl CodeGenerator for Type { warn!( "Item contained invalid named type, skipping: \ {:?}, {:?}", - item, - inner_item + item, inner_item ); return; } @@ -737,15 +750,12 @@ impl CodeGenerator for Type { // We prefer using `pub use` over `pub type` because of: // https://github.com/rust-lang/rust/issues/26264 - if inner_rust_type.to_string() - .chars() - .all(|c| match c { - // These are the only characters allowed in simple - // paths, eg `good::dogs::Bront`. - 'A'..='Z' | 'a'..='z' | '0'..='9' | ':' | '_' | ' ' => true, - _ => false, - }) && - outer_params.is_empty() && + if inner_rust_type.to_string().chars().all(|c| match c { + // These are the only characters allowed in simple + // paths, eg `good::dogs::Bront`. + 'A'..='Z' | 'a'..='z' | '0'..='9' | ':' | '_' | ' ' => true, + _ => false, + }) && outer_params.is_empty() && inner_item.expect_type().canonical_type(ctx).is_enum() { tokens.append_all(quote! { @@ -764,10 +774,14 @@ impl CodeGenerator for Type { pub type #rust_name }); - let params: Vec<_> = outer_params.into_iter() + let params: Vec<_> = outer_params + .into_iter() .filter_map(|p| p.as_template_param(ctx, &())) .collect(); - if params.iter().any(|p| ctx.resolve_type(*p).is_invalid_type_param()) { + if params + .iter() + .any(|p| ctx.resolve_type(*p).is_invalid_type_param()) + { warn!( "Item contained invalid template \ parameter: {:?}", @@ -775,10 +789,14 @@ impl CodeGenerator for Type { ); return; } - let params: Vec<_> = params.iter().map(|p| { - p.try_to_rust_ty(ctx, &()) - .expect("type parameters can always convert to rust ty OK") - }).collect(); + let params: Vec<_> = params + .iter() + .map(|p| { + p.try_to_rust_ty(ctx, &()).expect( + "type parameters can always convert to rust ty OK", + ) + }) + .collect(); if !params.is_empty() { tokens.append_all(quote! { @@ -1038,7 +1056,8 @@ impl<'a> FieldCodegen<'a> for FieldData { // `BitfieldUnit` and `Bitfield`. assert!(self.bitfield_width().is_none()); - let field_item = self.ty().into_resolver().through_type_refs().resolve(ctx); + let field_item = + self.ty().into_resolver().through_type_refs().resolve(ctx); let field_ty = field_item.expect_type(); let mut ty = self.ty().to_rust_ty_or_opaque(ctx, &()); ty.append_implicit_template_params(ctx, field_item); @@ -1082,10 +1101,10 @@ impl<'a> FieldCodegen<'a> for FieldData { } } - let field_name = - self.name() - .map(|name| ctx.rust_mangle(name).into_owned()) - .expect("Each field should have a name in codegen!"); + let field_name = self + .name() + .map(|name| ctx.rust_mangle(name).into_owned()) + .expect("Each field should have a name in codegen!"); let field_ident = ctx.rust_ident_raw(field_name.as_str()); if !parent.is_union() { @@ -1096,9 +1115,10 @@ 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); @@ -1168,7 +1188,10 @@ impl<'a> FieldCodegen<'a> for FieldData { impl BitfieldUnit { /// Get the constructor name for this bitfield unit. fn ctor_name(&self) -> proc_macro2::TokenStream { - let ctor_name = Ident::new(&format!("new_bitfield_{}", self.nth()), Span::call_site()); + let ctor_name = Ident::new( + &format!("new_bitfield_{}", self.nth()), + Span::call_site(), + ); quote! { #ctor_name } @@ -1190,9 +1213,9 @@ impl Bitfield { mut ctor_impl: proc_macro2::TokenStream, ) -> proc_macro2::TokenStream { let bitfield_ty = ctx.resolve_type(self.ty()); - 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 = helpers::blob(ctx, bitfield_ty_layout); let offset = self.offset_into_unit(); @@ -1306,11 +1329,7 @@ impl<'a> FieldCodegen<'a> for BitfieldUnit { ctor_params.push(quote! { #param_name : #bitfield_ty }); - ctor_impl = bf.extend_ctor_impl( - ctx, - param_name, - ctor_impl, - ); + ctor_impl = bf.extend_ctor_impl(ctx, param_name, ctor_impl); } if generate_ctor { @@ -1373,19 +1392,20 @@ 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_int_ty = match helpers::integer_type(ctx, bitfield_ty_layout) { - Some(int_ty) => { - *bitfield_representable_as_int = true; - int_ty - } - None => { - *bitfield_representable_as_int = false; - return; - } - }; + let bitfield_ty_layout = bitfield_ty + .layout(ctx) + .expect("Bitfield without layout? Gah!"); + let bitfield_int_ty = + match helpers::integer_type(ctx, bitfield_ty_layout) { + Some(int_ty) => { + *bitfield_representable_as_int = true; + int_ty + } + None => { + *bitfield_representable_as_int = false; + return; + } + }; let bitfield_ty = bitfield_ty.to_rust_ty_or_opaque(ctx, bitfield_ty_item); @@ -1529,7 +1549,8 @@ impl CodeGenerator for CompInfo { let codegen_depth = item.codegen_depth(ctx); let fields_should_be_private = item.annotations().private_fields().unwrap_or(false); - let struct_accessor_kind = item.annotations() + let struct_accessor_kind = item + .annotations() .accessor_kind() .unwrap_or(FieldAccessorKind::None); for field in self.fields() { @@ -1584,7 +1605,10 @@ impl CodeGenerator for CompInfo { } else { explicit_align = Some(layout.align); if !ctx.options().rust_features.repr_align { - let ty = helpers::blob(ctx, Layout::new(0, layout.align)); + let ty = helpers::blob( + ctx, + Layout::new(0, layout.align), + ); fields.push(quote! { pub __bindgen_align: #ty , }); @@ -1668,7 +1692,7 @@ impl CodeGenerator for CompInfo { < #( #generic_param_names ),* > } } else { - quote! { } + quote! {} }; let mut attributes = vec![]; @@ -1682,7 +1706,11 @@ impl CodeGenerator for CompInfo { if packed && !is_opaque { let n = layout.map_or(1, |l| l.align); assert!(ctx.options().rust_features().repr_packed_n || n == 1); - let packed_repr = if n == 1 { "packed".to_string() } else { format!("packed({})", n) }; + let packed_repr = if n == 1 { + "packed".to_string() + } else { + format!("packed({})", n) + }; attributes.push(attributes::repr_list(&["C", &packed_repr])); } else { attributes.push(attributes::repr("C")); @@ -1699,13 +1727,12 @@ impl CodeGenerator for CompInfo { } } - let mut derives = vec![]; 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) { @@ -1750,10 +1777,10 @@ impl CodeGenerator for CompInfo { if item.can_derive_partialeq(ctx) { derives.push("PartialEq"); } else { - needs_partialeq_impl = - ctx.options().derive_partialeq && + needs_partialeq_impl = ctx.options().derive_partialeq && ctx.options().impl_partialeq && - ctx.lookup_can_derive_partialeq_or_partialord(item.id()) == CanDerive::Manually; + ctx.lookup_can_derive_partialeq_or_partialord(item.id()) == + CanDerive::Manually; } if item.can_derive_eq(ctx) { @@ -1827,34 +1854,36 @@ impl CodeGenerator for CompInfo { let size = layout.size; let align = layout.align; - let check_struct_align = - if align > ctx.target_pointer_size() && - !ctx.options().rust_features().repr_align - { - None - } else { - Some(quote! { - assert_eq!(#align_of_expr, - #align, - concat!("Alignment of ", stringify!(#canonical_ident))); + let check_struct_align = if align > + ctx.target_pointer_size() && + !ctx.options().rust_features().repr_align + { + None + } else { + Some(quote! { + assert_eq!(#align_of_expr, + #align, + concat!("Alignment of ", stringify!(#canonical_ident))); - }) - }; + }) + }; // FIXME when [issue #465](https://github.com/rust-lang/rust-bindgen/issues/465) ready - let too_many_base_vtables = self.base_members() + let too_many_base_vtables = self + .base_members() .iter() .filter(|base| base.ty.has_vtable(ctx)) - .count() > 1; + .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 { - vec![] - } else { - let asserts = self.fields() + let check_field_offset = if should_skip_field_offset_checks + { + vec![] + } else { + let asserts = self.fields() .iter() .filter_map(|field| match *field { Field::DataMember(ref f) if f.name().is_some() => Some(f), @@ -1879,8 +1908,8 @@ impl CodeGenerator for CompInfo { }) .collect::>(); - asserts - }; + asserts + }; let item = quote! { #[test] @@ -1918,7 +1947,8 @@ impl CodeGenerator for CompInfo { *sig, /* const */ false, - ).codegen_method( + ) + .codegen_method( ctx, &mut methods, &mut method_names, @@ -1983,15 +2013,19 @@ impl CodeGenerator for CompInfo { } if needs_partialeq_impl { - if let Some(impl_) = impl_partialeq::gen_partialeq_impl(ctx, self, item, &ty_for_impl) { - + if let Some(impl_) = impl_partialeq::gen_partialeq_impl( + ctx, + self, + item, + &ty_for_impl, + ) { let partialeq_bounds = if !generic_param_names.is_empty() { let bounds = generic_param_names.iter().map(|t| { quote! { #t: PartialEq } }); quote! { where #( #bounds ),* } } else { - quote! { } + quote! {} }; let prefix = ctx.trait_prefix(); @@ -2067,7 +2101,9 @@ impl MethodCodegen for Method { _ => panic!("How in the world?"), }; - if let (Abi::ThisCall, false) = (signature.abi(), ctx.options().rust_features().thiscall_abi) { + if let (Abi::ThisCall, false) = + (signature.abi(), ctx.options().rust_features().thiscall_abi) + { return; } @@ -2118,10 +2154,9 @@ impl MethodCodegen for Method { // variable called `__bindgen_tmp` we're going to create. if self.is_constructor() { let prefix = ctx.trait_prefix(); - let tmp_variable_decl = - quote! { - let mut __bindgen_tmp = ::#prefix::mem::uninitialized() - }; + let tmp_variable_decl = quote! { + let mut __bindgen_tmp = ::#prefix::mem::uninitialized() + }; stmts.push(tmp_variable_decl); exprs[0] = quote! { &mut __bindgen_tmp @@ -2152,7 +2187,9 @@ impl MethodCodegen for Method { let mut attrs = vec![]; attrs.push(attributes::inline()); - if signature.must_use() && ctx.options().rust_features().must_use_function { + if signature.must_use() && + ctx.options().rust_features().must_use_function + { attrs.push(attributes::must_use()); } @@ -2172,21 +2209,21 @@ pub enum EnumVariation { /// The code for this enum will use a Rust enum Rust { /// Indicates whether the generated struct should be #[non_exhaustive] - non_exhaustive: bool + non_exhaustive: bool, }, /// The code for this enum will use a bitfield Bitfield, /// The code for this enum will use consts Consts, /// The code for this enum will use a module containing consts - ModuleConsts + ModuleConsts, } impl EnumVariation { fn is_rust(&self) -> bool { match *self { - EnumVariation::Rust{ .. } => true, - _ => false + EnumVariation::Rust { .. } => true, + _ => false, } } @@ -2195,7 +2232,7 @@ impl EnumVariation { fn is_const(&self) -> bool { match *self { EnumVariation::Consts | EnumVariation::ModuleConsts => true, - _ => false + _ => false, } } } @@ -2225,7 +2262,6 @@ impl std::str::FromStr for EnumVariation { } } - /// A helper type to construct different enum variations. enum EnumBuilder<'a> { Rust { @@ -2274,16 +2310,14 @@ impl<'a> EnumBuilder<'a> { let ident = Ident::new(name, Span::call_site()); match enum_variation { - EnumVariation::Bitfield => { - EnumBuilder::Bitfield { - codegen_depth: enum_codegen_depth, - canonical_name: name, - tokens: quote! { - #( #attrs )* - pub struct #ident (pub #repr); - }, - } - } + EnumVariation::Bitfield => EnumBuilder::Bitfield { + codegen_depth: enum_codegen_depth, + canonical_name: name, + tokens: quote! { + #( #attrs )* + pub struct #ident (pub #repr); + }, + }, EnumVariation::Rust { .. } => { let tokens = quote!(); @@ -2296,20 +2330,19 @@ impl<'a> EnumBuilder<'a> { } } - EnumVariation::Consts => { - EnumBuilder::Consts { - variants: vec![ - quote! { - #( #attrs )* - pub type #ident = #repr; - } - ], - codegen_depth: enum_codegen_depth, - } - } + EnumVariation::Consts => EnumBuilder::Consts { + variants: vec![quote! { + #( #attrs )* + pub type #ident = #repr; + }], + codegen_depth: enum_codegen_depth, + }, EnumVariation::ModuleConsts => { - let ident = Ident::new(CONSTIFIED_ENUM_MODULE_REPR_NAME, Span::call_site()); + let ident = Ident::new( + CONSTIFIED_ENUM_MODULE_REPR_NAME, + Span::call_site(), + ); let type_definition = quote! { #( #attrs )* pub type #ident = #repr; @@ -2343,13 +2376,20 @@ impl<'a> EnumBuilder<'a> { let mut doc = quote! {}; if ctx.options().generate_comments { if let Some(raw_comment) = variant.comment() { - let comment = comment::preprocess(raw_comment, self.codegen_depth()); + let comment = + comment::preprocess(raw_comment, self.codegen_depth()); doc = attributes::doc(comment); } } match self { - EnumBuilder::Rust { attrs, ident, tokens, emitted_any_variants: _, codegen_depth } => { + EnumBuilder::Rust { + attrs, + ident, + tokens, + emitted_any_variants: _, + codegen_depth, + } => { let name = ctx.rust_ident(variant_name); EnumBuilder::Rust { attrs, @@ -2365,7 +2405,8 @@ impl<'a> EnumBuilder<'a> { } EnumBuilder::Bitfield { canonical_name, .. } => { - if ctx.options().rust_features().associated_const && is_ty_named { + if ctx.options().rust_features().associated_const && is_ty_named + { let enum_ident = ctx.rust_ident(canonical_name); let variant_ident = ctx.rust_ident(variant_name); result.push(quote! { @@ -2390,9 +2431,7 @@ impl<'a> EnumBuilder<'a> { self } - EnumBuilder::Consts { - .. - } => { + EnumBuilder::Consts { .. } => { let constant_name = match mangling_prefix { Some(prefix) => { Cow::Owned(format!("{}_{}", prefix, variant_name)) @@ -2436,7 +2475,13 @@ impl<'a> EnumBuilder<'a> { result: &mut CodegenResult<'b>, ) -> proc_macro2::TokenStream { match self { - EnumBuilder::Rust { attrs, ident, tokens, emitted_any_variants, .. } => { + EnumBuilder::Rust { + attrs, + ident, + tokens, + emitted_any_variants, + .. + } => { let variants = if !emitted_any_variants { quote!(__bindgen_cannot_repr_c_on_empty_enum = 0) } else { @@ -2536,12 +2581,10 @@ 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 \ @@ -2580,20 +2623,24 @@ impl CodeGenerator for Enum { match variation { EnumVariation::Rust { non_exhaustive } => { attrs.push(attributes::repr(repr_name)); - if non_exhaustive && ctx.options().rust_features().non_exhaustive { + if non_exhaustive && + ctx.options().rust_features().non_exhaustive + { attrs.push(attributes::non_exhaustive()); - } else if non_exhaustive && !ctx.options().rust_features().non_exhaustive { + } else if non_exhaustive && + !ctx.options().rust_features().non_exhaustive + { panic!("The rust target you're using doesn't seem to support non_exhaustive enums"); } - }, + } EnumVariation::Bitfield => { if ctx.options().rust_features.repr_transparent { attrs.push(attributes::repr("transparent")); } else { attrs.push(attributes::repr("C")); } - }, - _ => {}, + } + _ => {} }; if let Some(comment) = item.comment(ctx) { @@ -2601,7 +2648,8 @@ impl CodeGenerator for Enum { } if !variation.is_const() { - let mut derives = vec!["Debug", "Copy", "Clone", "PartialEq", "Eq", "Hash"]; + let mut derives = + vec!["Debug", "Copy", "Clone", "PartialEq", "Eq", "Hash"]; if item.can_derive_partialord(ctx) { derives.push("PartialOrd"); @@ -2685,9 +2733,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; } @@ -2708,17 +2756,20 @@ impl CodeGenerator for Enum { let parent_name = parent_canonical_name.as_ref().unwrap(); - Cow::Owned( - format!("{}_{}", parent_name, variant_name), - ) + Cow::Owned(format!( + "{}_{}", + parent_name, variant_name + )) }; let existing_variant_name = entry.get(); // Use associated constants for named enums. if enum_ty.name().is_some() && - ctx.options().rust_features().associated_const { + ctx.options().rust_features().associated_const + { let enum_canonical_name = &ident; - let variant_name = ctx.rust_ident_raw(&*mangled_name); + let variant_name = + ctx.rust_ident_raw(&*mangled_name); result.push(quote! { impl #enum_rust_ty { pub const #variant_name : #enum_rust_ty = @@ -2772,12 +2823,8 @@ impl CodeGenerator for Enum { parent_canonical_name.as_ref().unwrap(); Ident::new( - &format!( - "{}_{}", - parent_name, - variant_name - ), - Span::call_site() + &format!("{}_{}", parent_name, variant_name), + Span::call_site(), ) }; @@ -2823,9 +2870,8 @@ trait TryToOpaque { ctx: &BindgenContext, extra: &Self::Extra, ) -> error::Result { - self.try_get_layout(ctx, extra).map(|layout| { - helpers::blob(ctx, layout) - }) + self.try_get_layout(ctx, extra) + .map(|layout| helpers::blob(ctx, layout)) } } @@ -2855,11 +2901,7 @@ trait ToOpaque: TryToOpaque { } } -impl ToOpaque for T -where - T: TryToOpaque, -{ -} +impl ToOpaque for T where T: TryToOpaque {} /// Fallible conversion from an IR thing to an *equivalent* Rust type. /// @@ -2895,8 +2937,7 @@ trait TryToRustTyOrOpaque: TryToRustTy + TryToOpaque { impl TryToRustTyOrOpaque for T where - T: TryToRustTy - + TryToOpaque, + T: TryToRustTy + TryToOpaque, { type Extra = E; @@ -2905,15 +2946,13 @@ where ctx: &BindgenContext, extra: &E, ) -> error::Result { - self.try_to_rust_ty(ctx, extra).or_else( - |_| if let Ok(layout) = - self.try_get_layout(ctx, extra) - { + self.try_to_rust_ty(ctx, extra).or_else(|_| { + if let Ok(layout) = self.try_get_layout(ctx, extra) { Ok(helpers::blob(ctx, layout)) } else { Err(error::Error::NoLayoutForOpaqueBlob) - }, - ) + } + }) } } @@ -2955,15 +2994,14 @@ where ctx: &BindgenContext, extra: &E, ) -> proc_macro2::TokenStream { - 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)) } } impl TryToOpaque for T where - T: Copy + Into + T: Copy + Into, { type Extra = (); @@ -2978,7 +3016,7 @@ where impl TryToRustTy for T where - T: Copy + Into + T: Copy + Into, { type Extra = (); @@ -3041,15 +3079,11 @@ impl TryToRustTy for Type { TypeKind::Void => Ok(raw_type(ctx, "c_void")), // TODO: we should do something smart with nullptr, or maybe *const // c_void is enough? - TypeKind::NullPtr => { - Ok(raw_type(ctx, "c_void").to_ptr(true)) - } + TypeKind::NullPtr => Ok(raw_type(ctx, "c_void").to_ptr(true)), TypeKind::Int(ik) => { match ik { IntKind::Bool => Ok(quote! { bool }), - IntKind::Char { - .. - } => Ok(raw_type(ctx, "c_char")), + IntKind::Char { .. } => Ok(raw_type(ctx, "c_char")), IntKind::SChar => Ok(raw_type(ctx, "c_schar")), IntKind::UChar => Ok(raw_type(ctx, "c_uchar")), IntKind::Short => Ok(raw_type(ctx, "c_short")), @@ -3061,12 +3095,14 @@ impl TryToRustTy for Type { IntKind::LongLong => Ok(raw_type(ctx, "c_longlong")), IntKind::ULongLong => Ok(raw_type(ctx, "c_ulonglong")), IntKind::WChar => { - let layout = self.layout(ctx).expect("Couldn't compute wchar_t's layout?"); + let layout = self + .layout(ctx) + .expect("Couldn't compute wchar_t's layout?"); let ty = Layout::known_type_for_size(ctx, layout.size) .expect("Non-representable wchar_t?"); let ident = ctx.rust_ident_raw(ty); Ok(quote! { #ident }) - }, + } IntKind::I8 => Ok(quote! { i8 }), IntKind::U8 => Ok(quote! { u8 }), @@ -3076,9 +3112,7 @@ impl TryToRustTy for Type { IntKind::U32 => Ok(quote! { u32 }), IntKind::I64 => Ok(quote! { i64 }), IntKind::U64 => Ok(quote! { u64 }), - IntKind::Custom { - name, .. - } => { + IntKind::Custom { name, .. } => { let ident = ctx.rust_ident_raw(name); Ok(quote! { #ident @@ -3102,9 +3136,12 @@ impl TryToRustTy for Type { } } } - TypeKind::Float(fk) => Ok(float_kind_rust_type(ctx, fk, self.layout(ctx))), + TypeKind::Float(fk) => { + Ok(float_kind_rust_type(ctx, fk, self.layout(ctx))) + } TypeKind::Complex(fk) => { - let float_path = float_kind_rust_type(ctx, fk, self.layout(ctx)); + let float_path = + float_kind_rust_type(ctx, fk, self.layout(ctx)); ctx.generated_bindgen_complex(); Ok(if ctx.options().enable_cxx_namespaces { @@ -3137,7 +3174,8 @@ impl TryToRustTy for Type { } TypeKind::Enum(..) => { let path = item.namespace_aware_canonical_path(ctx); - let path = proc_macro2::TokenStream::from_str(&path.join("::")).unwrap(); + let path = proc_macro2::TokenStream::from_str(&path.join("::")) + .unwrap(); Ok(quote!(#path)) } TypeKind::TemplateInstantiation(ref inst) => { @@ -3151,14 +3189,18 @@ impl TryToRustTy for Type { let void = raw_type(ctx, "c_void"); return Ok(void.to_ptr(/* is_const = */ false)); } - let template_params = item.used_template_params(ctx) + let template_params = item + .used_template_params(ctx) .into_iter() .filter(|param| param.is_template_param(ctx, &())) .collect::>(); if item.is_opaque(ctx, &()) && !template_params.is_empty() { self.try_to_opaque(ctx, item) - } else if let Some(ty) = self.name().and_then(|name| utils::type_from_named(ctx, name)) { + } else if let Some(ty) = self + .name() + .and_then(|name| utils::type_from_named(ctx, name)) + { Ok(ty) } else { utils::build_path(item, ctx) @@ -3175,11 +3217,11 @@ impl TryToRustTy for Type { utils::build_path(item, ctx) } TypeKind::Opaque => self.try_to_opaque(ctx, item), - TypeKind::Pointer(inner) | - TypeKind::Reference(inner) => { + TypeKind::Pointer(inner) | TypeKind::Reference(inner) => { let is_const = ctx.resolve_type(inner).is_const(); - let inner = inner.into_resolver().through_type_refs().resolve(ctx); + let inner = + inner.into_resolver().through_type_refs().resolve(ctx); let inner_ty = inner.expect_type(); // Regardless if we can properly represent the inner type, we @@ -3203,13 +3245,10 @@ impl TryToRustTy for Type { #ident }) } - TypeKind::ObjCSel => { - Ok(quote! { - objc::runtime::Sel - }) - } - TypeKind::ObjCId | - TypeKind::ObjCInterface(..) => Ok(quote! { + TypeKind::ObjCSel => Ok(quote! { + objc::runtime::Sel + }), + TypeKind::ObjCId | TypeKind::ObjCInterface(..) => Ok(quote! { id }), ref u @ TypeKind::UnresolvedTypeRef(..) => { @@ -3227,9 +3266,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) } } @@ -3245,23 +3284,25 @@ impl TryToRustTy for TemplateInstantiation { return Err(error::Error::InstantiationOfOpaqueType); } - let def = self.template_definition() + let def = self + .template_definition() .into_resolver() .through_type_refs() .resolve(ctx); let mut ty = quote! {}; let def_path = def.namespace_aware_canonical_path(ctx); - ty.append_separated(def_path.into_iter().map(|p| ctx.rust_ident(p)), quote!(::)); + ty.append_separated( + def_path.into_iter().map(|p| ctx.rust_ident(p)), + quote!(::), + ); let def_params = def.self_template_params(ctx); if def_params.is_empty() { // This can happen if we generated an opaque type for a partial // template specialization, and we've hit an instantiation of // that partial specialization. - extra_assert!( - def.is_opaque(ctx, &()) - ); + extra_assert!(def.is_opaque(ctx, &())); return Err(error::Error::InstantiationOfOpaqueType); } @@ -3273,11 +3314,12 @@ impl TryToRustTy for TemplateInstantiation { // reconstruct them somehow. We don't have any means of doing // that reconstruction at this time. - let template_args = self.template_arguments() + let template_args = self + .template_arguments() .iter() .zip(def_params.iter()) - // Only pass type arguments for the type parameters that - // the def uses. + // Only pass type arguments for the type parameters that + // the def uses. .filter(|&(_, param)| ctx.uses_template_parameter(def.id(), *param)) .map(|(arg, _)| { let arg = arg.into_resolver().through_type_refs().resolve(ctx); @@ -3315,11 +3357,9 @@ impl TryToRustTy for FunctionSig { warn!("Skipping function with thiscall ABI that isn't supported by the configured Rust target"); Ok(proc_macro2::TokenStream::new()) } - _ => { - Ok(quote! { - unsafe extern #abi fn ( #( #arguments ),* ) #ret - }) - } + _ => Ok(quote! { + unsafe extern #abi fn ( #( #arguments ),* ) #ret + }), } } } @@ -3346,10 +3386,12 @@ impl CodeGenerator for Function { // Pure virtual methods have no actual symbol, so we can't generate // something meaningful for them. match self.kind() { - FunctionKind::Method(ref method_kind) if method_kind.is_pure_virtual() => { + FunctionKind::Method(ref method_kind) + if method_kind.is_pure_virtual() => + { return; } - _ => {}, + _ => {} } // Similar to static member variables in a class template, we can't @@ -3387,7 +3429,9 @@ impl CodeGenerator for Function { let mut attributes = vec![]; - if signature.must_use() && ctx.options().rust_features().must_use_function { + if signature.must_use() && + ctx.options().rust_features().must_use_function + { attributes.push(attributes::must_use()); } @@ -3414,9 +3458,7 @@ impl CodeGenerator for Function { Abi::Unknown(unknown_abi) => { panic!( "Invalid or unknown abi {:?} for function {:?} ({:?})", - unknown_abi, - canonical_name, - self + unknown_abi, canonical_name, self ); } abi => abi, @@ -3440,7 +3482,6 @@ impl CodeGenerator for Function { } } - fn objc_method_codegen( ctx: &BindgenContext, method: &ObjCMethod, @@ -3458,8 +3499,7 @@ fn objc_method_codegen( } } else { let fn_args = fn_args.clone(); - let args = iter::once(quote! { self }) - .chain(fn_args.into_iter()); + let args = iter::once(quote! { self }).chain(fn_args.into_iter()); quote! { ( #( #args ),* ) #fn_ret } @@ -3471,7 +3511,10 @@ fn objc_method_codegen( let class_name = class_name .expect("Generating a class method without class name?") .to_owned(); - let expect_msg = proc_macro2::Literal::string(&format!("Couldn't find {}", class_name)); + let expect_msg = proc_macro2::Literal::string(&format!( + "Couldn't find {}", + class_name + )); quote! { msg_send!(objc::runtime::Class::get(#class_name).expect(#expect_msg), #methods_and_args) } @@ -3481,7 +3524,8 @@ fn objc_method_codegen( } }; - let method_name = ctx.rust_ident(format!("{}{}", prefix, method.rust_name())); + let method_name = + ctx.rust_ident(format!("{}{}", prefix, method.rust_name())); ( quote! { @@ -3491,7 +3535,7 @@ fn objc_method_codegen( }, quote! { unsafe fn #method_name #sig ; - } + }, ) } @@ -3516,12 +3560,8 @@ 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() { let ambiquity = @@ -3560,7 +3600,9 @@ impl CodeGenerator for ObjCInterface { } } -pub(crate) fn codegen(context: BindgenContext) -> (Vec, BindgenOptions) { +pub(crate) fn codegen( + context: BindgenContext, +) -> (Vec, BindgenOptions) { context.gen(|context| { let _t = context.timer("codegen"); let counter = Cell::new(0); @@ -3579,20 +3621,26 @@ pub(crate) fn codegen(context: BindgenContext) -> (Vec if let Some(path) = context.options().emit_ir_graphviz.as_ref() { match dot::write_dot_file(context, path) { - Ok(()) => info!("Your dot file was generated successfully into: {}", path), + Ok(()) => info!( + "Your dot file was generated successfully into: {}", + path + ), Err(e) => error!("{}", e), } } - context.resolve_item(context.root_module()) - .codegen(context, &mut result, &()); + context.resolve_item(context.root_module()).codegen( + context, + &mut result, + &(), + ); result.items }) } mod utils { - use super::{ToRustTyOrOpaque, error}; + use super::{error, ToRustTyOrOpaque}; use ir::context::BindgenContext; use ir::function::{Abi, FunctionSig}; use ir::item::{Item, ItemCanonicalPath}; @@ -3604,7 +3652,7 @@ mod utils { pub fn prepend_bitfield_unit_type( ctx: &BindgenContext, - result: &mut Vec + result: &mut Vec, ) { let bitfield_unit_src = include_str!("./bitfield_unit.rs"); let bitfield_unit_src = if ctx.options().rust_features().min_const_fn { @@ -3612,7 +3660,8 @@ mod utils { } else { Cow::Owned(bitfield_unit_src.replace("const fn ", "fn ")) }; - let bitfield_unit_type = proc_macro2::TokenStream::from_str(&bitfield_unit_src).unwrap(); + let bitfield_unit_type = + proc_macro2::TokenStream::from_str(&bitfield_unit_src).unwrap(); let bitfield_unit_type = quote!(#bitfield_unit_type); let items = vec![bitfield_unit_type]; @@ -3673,9 +3722,9 @@ mod utils { // If the target supports `const fn`, declare eligible functions // as `const fn` else just `fn`. let const_fn = if ctx.options().rust_features().min_const_fn { - quote!{ const fn } + quote! { const fn } } else { - quote!{ fn } + quote! { fn } }; // TODO(emilio): The fmt::Debug impl could be way nicer with @@ -3757,15 +3806,17 @@ mod utils { } }; - let items = vec![union_field_decl, - union_field_impl, - union_field_default_impl, - union_field_clone_impl, - union_field_copy_impl, - union_field_debug_impl, - union_field_hash_impl, - union_field_partialeq_impl, - union_field_eq_impl]; + let items = vec![ + union_field_decl, + union_field_impl, + union_field_default_impl, + union_field_clone_impl, + union_field_copy_impl, + union_field_debug_impl, + union_field_hash_impl, + union_field_partialeq_impl, + union_field_eq_impl, + ]; let old_items = mem::replace(result, items); result.extend(old_items.into_iter()); @@ -3780,9 +3831,9 @@ mod utils { // If the target supports `const fn`, declare eligible functions // as `const fn` else just `fn`. let const_fn = if ctx.options().rust_features().min_const_fn { - quote!{ const fn } + quote! { const fn } } else { - quote!{ fn } + quote! { fn } }; let incomplete_array_decl = quote! { @@ -3839,18 +3890,18 @@ mod utils { } }; - let items = vec![incomplete_array_decl, - incomplete_array_impl, - incomplete_array_debug_impl, - incomplete_array_clone_impl]; + let items = vec![ + incomplete_array_decl, + incomplete_array_impl, + incomplete_array_debug_impl, + incomplete_array_clone_impl, + ]; let old_items = mem::replace(result, items); result.extend(old_items.into_iter()); } - pub fn prepend_complex_type( - result: &mut Vec, - ) { + pub fn prepend_complex_type(result: &mut Vec) { let complex_type = quote! { #[derive(PartialEq, Copy, Clone, Hash, Debug, Default)] #[repr(C)] @@ -3870,12 +3921,16 @@ mod utils { ctx: &BindgenContext, ) -> error::Result { let path = item.namespace_aware_canonical_path(ctx); - let tokens = proc_macro2::TokenStream::from_str(&path.join("::")).unwrap(); + let tokens = + proc_macro2::TokenStream::from_str(&path.join("::")).unwrap(); Ok(tokens) } - fn primitive_ty(ctx: &BindgenContext, name: &str) -> proc_macro2::TokenStream { + fn primitive_ty( + ctx: &BindgenContext, + name: &str, + ) -> proc_macro2::TokenStream { let ident = ctx.rust_ident_raw(name); quote! { #ident @@ -3911,7 +3966,7 @@ mod utils { ) -> proc_macro2::TokenStream { let return_item = ctx.resolve_item(sig.return_type()); if let TypeKind::Void = *return_item.kind().expect_type().kind() { - quote! { } + quote! {} } else { let ret_ty = return_item.to_rust_ty_or_opaque(ctx, &()); quote! { @@ -3927,58 +3982,63 @@ mod utils { use super::ToPtr; let mut unnamed_arguments = 0; - let mut args = sig.argument_types().iter().map(|&(ref name, ty)| { - let arg_item = ctx.resolve_item(ty); - let arg_ty = arg_item.kind().expect_type(); - - // From the C90 standard[1]: - // - // A declaration of a parameter as "array of type" shall be - // adjusted to "qualified pointer to type", where the type - // qualifiers (if any) are those specified within the [ and ] of - // the array type derivation. - // - // [1]: http://c0x.coding-guidelines.com/6.7.5.3.html - let arg_ty = match *arg_ty.canonical_type(ctx).kind() { - TypeKind::Array(t, _) => { - let stream = if ctx.options().array_pointers_in_arguments { - arg_ty.to_rust_ty_or_opaque(ctx, &arg_item) - } else { - t.to_rust_ty_or_opaque(ctx, &()) - }; - stream.to_ptr(ctx.resolve_type(t).is_const()) - } - TypeKind::Pointer(inner) => { - let inner = ctx.resolve_item(inner); - let inner_ty = inner.expect_type(); - if let TypeKind::ObjCInterface(_) = *inner_ty.canonical_type(ctx).kind() { - quote! { - id + let mut args = sig + .argument_types() + .iter() + .map(|&(ref name, ty)| { + let arg_item = ctx.resolve_item(ty); + let arg_ty = arg_item.kind().expect_type(); + + // From the C90 standard[1]: + // + // A declaration of a parameter as "array of type" shall be + // adjusted to "qualified pointer to type", where the type + // qualifiers (if any) are those specified within the [ and ] of + // the array type derivation. + // + // [1]: http://c0x.coding-guidelines.com/6.7.5.3.html + let arg_ty = match *arg_ty.canonical_type(ctx).kind() { + TypeKind::Array(t, _) => { + let stream = + if ctx.options().array_pointers_in_arguments { + arg_ty.to_rust_ty_or_opaque(ctx, &arg_item) + } else { + t.to_rust_ty_or_opaque(ctx, &()) + }; + stream.to_ptr(ctx.resolve_type(t).is_const()) + } + TypeKind::Pointer(inner) => { + let inner = ctx.resolve_item(inner); + let inner_ty = inner.expect_type(); + if let TypeKind::ObjCInterface(_) = + *inner_ty.canonical_type(ctx).kind() + { + quote! { + id + } + } else { + arg_item.to_rust_ty_or_opaque(ctx, &()) } - } else { - arg_item.to_rust_ty_or_opaque(ctx, &()) } - }, - _ => { - arg_item.to_rust_ty_or_opaque(ctx, &()) - } - }; + _ => arg_item.to_rust_ty_or_opaque(ctx, &()), + }; - let arg_name = match *name { - Some(ref name) => ctx.rust_mangle(name).into_owned(), - None => { - unnamed_arguments += 1; - format!("arg{}", unnamed_arguments) - } - }; + let arg_name = match *name { + Some(ref name) => ctx.rust_mangle(name).into_owned(), + None => { + unnamed_arguments += 1; + format!("arg{}", unnamed_arguments) + } + }; - assert!(!arg_name.is_empty()); - let arg_name = ctx.rust_ident(arg_name); + assert!(!arg_name.is_empty()); + let arg_name = ctx.rust_ident(arg_name); - quote! { - #arg_name : #arg_ty - } - }).collect::>(); + quote! { + #arg_name : #arg_ty + } + }) + .collect::>(); if sig.is_variadic() { args.push(quote! { ... }) @@ -3998,11 +4058,12 @@ mod utils { }); let return_item = ctx.resolve_item(sig.return_type()); - let ret_ty = if let TypeKind::Void = *return_item.kind().expect_type().kind() { - quote! { () } - } else { - return_item.to_rust_ty_or_opaque(ctx, &()) - }; + let ret_ty = + if let TypeKind::Void = *return_item.kind().expect_type().kind() { + quote! { () } + } else { + return_item.to_rust_ty_or_opaque(ctx, &()) + }; quote! { *const ::block::Block<(#(#args,)*), #ret_ty> diff --git a/src/codegen/struct_layout.rs b/src/codegen/struct_layout.rs index 29d281aa4b..3c03ff1152 100644 --- a/src/codegen/struct_layout.rs +++ b/src/codegen/struct_layout.rs @@ -166,7 +166,8 @@ impl<'a> StructLayoutTracker<'a> { // This means that the structs in the array are super-unsafe to // access, since they won't be properly aligned, but there's not too // much we can do about it. - 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 > self.ctx.target_pointer_size() { field_layout.size = align_to(layout.size, layout.align) * len; @@ -212,7 +213,10 @@ impl<'a> StructLayoutTracker<'a> { if need_padding && padding_bytes != 0 { Some(Layout::new( padding_bytes, - cmp::min(field_layout.align, self.ctx.target_pointer_size()) + cmp::min( + field_layout.align, + self.ctx.target_pointer_size(), + ), )) } else { None @@ -235,11 +239,13 @@ impl<'a> StructLayoutTracker<'a> { padding_layout.map(|layout| self.padding_field(layout)) } - pub fn pad_struct(&mut self, layout: Layout) -> Option { + pub fn pad_struct( + &mut self, + layout: Layout, + ) -> Option { debug!( "pad_struct:\n\tself = {:#?}\n\tlayout = {:#?}", - self, - layout + self, layout ); if layout.size < self.latest_offset { @@ -261,15 +267,15 @@ impl<'a> StructLayoutTracker<'a> { // 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 > self.ctx.target_pointer_size()) + (self.last_field_was_bitfield && + padding_bytes >= + self.latest_field_layout.unwrap().align) || + layout.align > self.ctx.target_pointer_size()) { let layout = if self.is_packed { Layout::new(padding_bytes, 1) } else if self.last_field_was_bitfield || - layout.align > self.ctx.target_pointer_size() + layout.align > self.ctx.target_pointer_size() { // We've already given up on alignment here. Layout::for_size(self.ctx, padding_bytes) @@ -315,7 +321,10 @@ impl<'a> StructLayoutTracker<'a> { self.padding_count += 1; - let padding_field_name = Ident::new(&format!("__bindgen_padding_{}", padding_count), Span::call_site()); + let padding_field_name = Ident::new( + &format!("__bindgen_padding_{}", padding_count), + Span::call_site(), + ); self.max_field_align = cmp::max(self.max_field_align, layout.align); @@ -342,9 +351,7 @@ impl<'a> StructLayoutTracker<'a> { // current field alignment and the bitfield size and alignment are. debug!( "align_to_bitfield? {}: {:?} {:?}", - self.last_field_was_bitfield, - layout, - new_field_layout + self.last_field_was_bitfield, layout, new_field_layout ); // Avoid divide-by-zero errors if align is 0. diff --git a/src/features.rs b/src/features.rs index 4dc526ec67..e700ca75b3 100644 --- a/src/features.rs +++ b/src/features.rs @@ -227,27 +227,27 @@ mod test { fn target_features() { let f_1_0 = RustFeatures::from(RustTarget::Stable_1_0); assert!( - !f_1_0.untagged_union - && !f_1_0.associated_const - && !f_1_0.builtin_clone_impls - && !f_1_0.repr_align - && !f_1_0.thiscall_abi + !f_1_0.untagged_union && + !f_1_0.associated_const && + !f_1_0.builtin_clone_impls && + !f_1_0.repr_align && + !f_1_0.thiscall_abi ); let f_1_21 = RustFeatures::from(RustTarget::Stable_1_21); assert!( - f_1_21.untagged_union - && f_1_21.associated_const - && f_1_21.builtin_clone_impls - && !f_1_21.repr_align - && !f_1_21.thiscall_abi + f_1_21.untagged_union && + f_1_21.associated_const && + f_1_21.builtin_clone_impls && + !f_1_21.repr_align && + !f_1_21.thiscall_abi ); let f_nightly = RustFeatures::from(RustTarget::Nightly); assert!( - f_nightly.untagged_union - && f_nightly.associated_const - && f_nightly.builtin_clone_impls - && f_nightly.repr_align - && f_nightly.thiscall_abi + f_nightly.untagged_union && + f_nightly.associated_const && + f_nightly.builtin_clone_impls && + f_nightly.repr_align && + f_nightly.thiscall_abi ); } diff --git a/src/ir/analysis/derive.rs b/src/ir/analysis/derive.rs index dbfe35a4a9..e07f6bc2c0 100644 --- a/src/ir/analysis/derive.rs +++ b/src/ir/analysis/derive.rs @@ -2,18 +2,18 @@ use std::fmt; -use super::{ConstrainResult, MonotoneFramework, generate_dependencies}; +use super::{generate_dependencies, ConstrainResult, MonotoneFramework}; use ir::analysis::has_vtable::HasVtable; use ir::comp::CompKind; use ir::context::{BindgenContext, ItemId}; use ir::derive::CanDerive; use ir::function::FunctionSig; -use ir::item::{Item, IsOpaque}; +use ir::item::{IsOpaque, Item}; use ir::template::TemplateParameters; use ir::traversal::{EdgeKind, Trace}; use ir::ty::RUST_DERIVE_IN_ARRAY_LIMIT; -use ir::ty::{TypeKind, Type}; -use {HashSet, HashMap, Entry}; +use ir::ty::{Type, TypeKind}; +use {Entry, HashMap, HashSet}; /// Which trait to consider when doing the `CannotDerive` analysis. #[derive(Debug, Copy, Clone)] @@ -110,19 +110,26 @@ impl<'ctx> CannotDerive<'ctx> { can_derive: CanDerive, ) -> ConstrainResult { let id = id.into(); - trace!("inserting {:?} can_derive<{}>={:?}", id, self.derive_trait, can_derive); + trace!( + "inserting {:?} can_derive<{}>={:?}", + id, + self.derive_trait, + can_derive + ); if let CanDerive::Yes = can_derive { return ConstrainResult::Same; } match self.can_derive.entry(id) { - Entry::Occupied(mut entry) => if *entry.get() < can_derive { - entry.insert(can_derive); - ConstrainResult::Changed - } else { - ConstrainResult::Same - }, + Entry::Occupied(mut entry) => { + if *entry.get() < can_derive { + entry.insert(can_derive); + ConstrainResult::Changed + } else { + ConstrainResult::Same + } + } Entry::Vacant(entry) => { entry.insert(can_derive); ConstrainResult::Changed @@ -132,41 +139,50 @@ impl<'ctx> CannotDerive<'ctx> { fn constrain_type(&mut self, item: &Item, ty: &Type) -> CanDerive { if !self.ctx.whitelisted_items().contains(&item.id()) { - trace!(" cannot derive {} for blacklisted type", self.derive_trait); + trace!( + " cannot derive {} for blacklisted type", + self.derive_trait + ); return CanDerive::No; } if self.derive_trait.not_by_name(self.ctx, &item) { - trace!(" cannot derive {} for explicitly excluded type", self.derive_trait); + trace!( + " cannot derive {} for explicitly excluded type", + self.derive_trait + ); return CanDerive::No; } trace!("ty: {:?}", ty); if item.is_opaque(self.ctx, &()) { - if !self.derive_trait.can_derive_union() - && ty.is_union() - && self.ctx.options().rust_features().untagged_union + if !self.derive_trait.can_derive_union() && + ty.is_union() && + self.ctx.options().rust_features().untagged_union { trace!( - " cannot derive {} for Rust unions", self.derive_trait + " cannot derive {} for Rust unions", + self.derive_trait ); return CanDerive::No; } - let layout_can_derive = ty.layout(self.ctx) - .map_or(CanDerive::Yes, |l| { + let layout_can_derive = + ty.layout(self.ctx).map_or(CanDerive::Yes, |l| { l.opaque().array_size_within_derive_limit(self.ctx) }); match layout_can_derive { CanDerive::Yes => { trace!( - " we can trivially derive {} for the layout", self.derive_trait + " we can trivially derive {} for the layout", + self.derive_trait ); } _ => { trace!( - " we cannot derive {} for the layout", self.derive_trait + " we cannot derive {} for the layout", + self.derive_trait ); } }; @@ -194,7 +210,7 @@ impl<'ctx> CannotDerive<'ctx> { let inner_type = self.ctx.resolve_type(inner).canonical_type(self.ctx); if let TypeKind::Function(ref sig) = *inner_type.kind() { - return self.derive_trait.can_derive_fnptr(sig) + return self.derive_trait.can_derive_fnptr(sig); } else { return self.derive_trait.can_derive_pointer(); } @@ -205,31 +221,34 @@ impl<'ctx> CannotDerive<'ctx> { // Complex cases need more information TypeKind::Array(t, len) => { - let inner_type = self.can_derive - .get(&t.into()) - .cloned() - .unwrap_or_default(); + let inner_type = + self.can_derive.get(&t.into()).cloned().unwrap_or_default(); if inner_type != CanDerive::Yes { trace!( " arrays of T for which we cannot derive {} \ - also cannot derive {}", self.derive_trait, self.derive_trait + also cannot derive {}", + self.derive_trait, + self.derive_trait ); return CanDerive::No; } - if len == 0 && !self.derive_trait.can_derive_incomplete_array() { + if len == 0 && !self.derive_trait.can_derive_incomplete_array() + { trace!( - " cannot derive {} for incomplete arrays", self.derive_trait + " cannot derive {} for incomplete arrays", + self.derive_trait ); return CanDerive::No; } else { if self.derive_trait.can_derive_large_array() { - trace!(" array can derive {}", self.derive_trait); - return CanDerive::Yes; + trace!(" array can derive {}", self.derive_trait); + return CanDerive::Yes; } else { if len <= RUST_DERIVE_IN_ARRAY_LIMIT { trace!( - " array is small enough to derive {}", self.derive_trait + " array is small enough to derive {}", + self.derive_trait ); return CanDerive::Yes; } else { @@ -242,19 +261,19 @@ impl<'ctx> CannotDerive<'ctx> { } } TypeKind::Vector(t, len) => { - let inner_type = self.can_derive - .get(&t.into()) - .cloned() - .unwrap_or_default(); + let inner_type = + self.can_derive.get(&t.into()).cloned().unwrap_or_default(); if inner_type != CanDerive::Yes { trace!( " vectors of T for which we cannot derive {} \ - also cannot derive {}", self.derive_trait, self.derive_trait + also cannot derive {}", + self.derive_trait, + self.derive_trait ); return CanDerive::No; } assert_ne!(len, 0, "vectors cannot have zero length"); - return self.derive_trait.can_derive_vector() + return self.derive_trait.can_derive_vector(); } TypeKind::Comp(ref info) => { @@ -263,19 +282,28 @@ impl<'ctx> CannotDerive<'ctx> { "The early ty.is_opaque check should have handled this case" ); - if !self.derive_trait.can_derive_compound_forward_decl() - && info.is_forward_declaration() { - trace!(" cannot derive {} for forward decls", self.derive_trait); + if !self.derive_trait.can_derive_compound_forward_decl() && + info.is_forward_declaration() + { + trace!( + " cannot derive {} for forward decls", + self.derive_trait + ); return CanDerive::No; } // NOTE: Take into account that while unions in C and C++ are copied by // default, the may have an explicit destructor in C++, so we can't // defer this check just for the union case. - if !self.derive_trait.can_derive_compound_with_destructor() - && self.ctx.lookup_has_destructor(item.id().expect_type_id(self.ctx)) + if !self.derive_trait.can_derive_compound_with_destructor() && + self.ctx.lookup_has_destructor( + item.id().expect_type_id(self.ctx), + ) { - trace!(" comp has destructor which cannot derive {}", self.derive_trait); + trace!( + " comp has destructor which cannot derive {}", + self.derive_trait + ); return CanDerive::No; } @@ -284,34 +312,39 @@ impl<'ctx> CannotDerive<'ctx> { if self.ctx.options().rust_features().untagged_union && // https://github.com/rust-lang/rust/issues/36640 (!info.self_template_params(self.ctx).is_empty() || - !item.all_template_params(self.ctx).is_empty()) { + !item.all_template_params(self.ctx).is_empty()) + { trace!( " cannot derive {} for Rust union because issue 36640", self.derive_trait ); return CanDerive::No; } - // fall through to be same as non-union handling + // fall through to be same as non-union handling } else { if self.ctx.options().rust_features().untagged_union { trace!( - " cannot derive {} for Rust unions", self.derive_trait + " cannot derive {} for Rust unions", + self.derive_trait ); return CanDerive::No; } let layout_can_derive = ty.layout(self.ctx).map_or(CanDerive::Yes, |l| { - l.opaque().array_size_within_derive_limit(self.ctx) + l.opaque() + .array_size_within_derive_limit(self.ctx) }); match layout_can_derive { CanDerive::Yes => { trace!( - " union layout can trivially derive {}", self.derive_trait + " union layout can trivially derive {}", + self.derive_trait ); } _ => { trace!( - " union layout cannot derive {}", self.derive_trait + " union layout cannot derive {}", + self.derive_trait ); } }; @@ -319,9 +352,13 @@ impl<'ctx> CannotDerive<'ctx> { } } - if !self.derive_trait.can_derive_compound_with_vtable() - && item.has_vtable(self.ctx) { - trace!(" cannot derive {} for comp with vtable", self.derive_trait); + if !self.derive_trait.can_derive_compound_with_vtable() && + item.has_vtable(self.ctx) + { + trace!( + " cannot derive {} for comp with vtable", + self.derive_trait + ); return CanDerive::No; } @@ -348,7 +385,11 @@ impl<'ctx> CannotDerive<'ctx> { } } - fn constrain_join(&mut self, item: &Item, consider_edge: EdgePredicate) -> CanDerive { + fn constrain_join( + &mut self, + item: &Item, + consider_edge: EdgePredicate, + ) -> CanDerive { let mut candidate = None; item.trace( @@ -378,7 +419,10 @@ impl<'ctx> CannotDerive<'ctx> { ); if candidate.is_none() { - trace!(" can derive {} because there are no members", self.derive_trait); + trace!( + " can derive {} because there are no members", + self.derive_trait + ); } candidate.unwrap_or_default() } @@ -389,8 +433,10 @@ impl DeriveTrait { match self { DeriveTrait::Copy => ctx.no_copy_by_name(item), DeriveTrait::Hash => ctx.no_hash_by_name(item), - DeriveTrait::PartialEqOrPartialOrd => ctx.no_partialeq_by_name(item), - _ => false + DeriveTrait::PartialEqOrPartialOrd => { + ctx.no_partialeq_by_name(item) + } + _ => false, } } @@ -398,17 +444,16 @@ impl DeriveTrait { match self { DeriveTrait::PartialEqOrPartialOrd => consider_edge_default, _ => |kind| match kind { - EdgeKind::BaseMember | - EdgeKind::Field => true, + EdgeKind::BaseMember | EdgeKind::Field => true, _ => false, - } + }, } } fn consider_edge_typeref(&self) -> EdgePredicate { match self { DeriveTrait::PartialEqOrPartialOrd => consider_edge_default, - _ => |kind| kind == EdgeKind::TypeReference + _ => |kind| kind == EdgeKind::TypeReference, } } @@ -416,10 +461,11 @@ impl DeriveTrait { match self { DeriveTrait::PartialEqOrPartialOrd => consider_edge_default, _ => |kind| match kind { - EdgeKind::TemplateArgument | - EdgeKind::TemplateDeclaration => true, + EdgeKind::TemplateArgument | EdgeKind::TemplateDeclaration => { + true + } _ => false, - } + }, } } @@ -460,16 +506,16 @@ impl DeriveTrait { fn can_derive_incomplete_array(&self) -> bool { match self { - DeriveTrait::Copy | DeriveTrait::Hash | DeriveTrait::PartialEqOrPartialOrd => false, + DeriveTrait::Copy | + DeriveTrait::Hash | + DeriveTrait::PartialEqOrPartialOrd => false, _ => true, } } fn can_derive_fnptr(&self, f: &FunctionSig) -> CanDerive { match (self, f.function_pointers_can_derive()) { - (DeriveTrait::Copy, _) | - (DeriveTrait::Default, _) | - (_, true) => { + (DeriveTrait::Copy, _) | (DeriveTrait::Default, _) | (_, true) => { trace!(" function pointer can derive {}", self); CanDerive::Yes } @@ -526,21 +572,23 @@ impl DeriveTrait { (DeriveTrait::Default, TypeKind::ObjCSel) => { trace!(" types that always cannot derive Default"); CanDerive::No - }, - (DeriveTrait::Default, TypeKind::UnresolvedTypeRef(..)) => unreachable!( - "Type with unresolved type ref can't reach derive default" - ), + } + (DeriveTrait::Default, TypeKind::UnresolvedTypeRef(..)) => { + unreachable!( + "Type with unresolved type ref can't reach derive default" + ) + } // === Hash === (DeriveTrait::Hash, TypeKind::Float(..)) | (DeriveTrait::Hash, TypeKind::Complex(..)) => { trace!(" float cannot derive Hash"); CanDerive::No - }, + } // === others === _ => { trace!(" simple type that can always derive {}", self); CanDerive::Yes - }, + } } } } @@ -602,9 +650,7 @@ impl<'ctx> MonotoneFramework for CannotDerive<'ctx> { trace!("constrain: {:?}", id); if let Some(CanDerive::No) = self.can_derive.get(&id).cloned() { - trace!( - " already know it cannot derive {}", self.derive_trait - ); + trace!(" already know it cannot derive {}", self.derive_trait); return ConstrainResult::Same; } @@ -614,7 +660,9 @@ impl<'ctx> MonotoneFramework for CannotDerive<'ctx> { let mut can_derive = self.constrain_type(item, ty); if let CanDerive::Yes = can_derive { if !self.derive_trait.can_derive_large_array() && - ty.layout(self.ctx).map_or(false, |l| l.align > RUST_DERIVE_IN_ARRAY_LIMIT) + 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 @@ -647,12 +695,10 @@ impl<'ctx> MonotoneFramework for CannotDerive<'ctx> { impl<'ctx> From> for HashMap { fn from(analysis: CannotDerive<'ctx>) -> Self { - extra_assert!( - analysis - .can_derive - .values() - .all(|v| *v != CanDerive::Yes) - ); + extra_assert!(analysis + .can_derive + .values() + .all(|v| *v != CanDerive::Yes)); analysis.can_derive } @@ -662,9 +708,11 @@ impl<'ctx> From> for HashMap { /// /// Elements that are not `CanDerive::Yes` are kept in the set, so that it /// represents all items that cannot derive. -pub fn as_cannot_derive_set(can_derive: HashMap) -> HashSet { +pub fn as_cannot_derive_set( + can_derive: HashMap, +) -> HashSet { can_derive .into_iter() - .filter_map(|(k, v)| if v != CanDerive::Yes { Some(k) } else { None } ) + .filter_map(|(k, v)| if v != CanDerive::Yes { Some(k) } else { None }) .collect() } diff --git a/src/ir/analysis/has_destructor.rs b/src/ir/analysis/has_destructor.rs index c79b364591..12b6926069 100644 --- a/src/ir/analysis/has_destructor.rs +++ b/src/ir/analysis/has_destructor.rs @@ -1,9 +1,9 @@ //! Determining which types have destructors -use super::{ConstrainResult, MonotoneFramework, generate_dependencies}; +use super::{generate_dependencies, ConstrainResult, MonotoneFramework}; +use ir::comp::{CompKind, Field, FieldMethods}; use ir::context::{BindgenContext, ItemId}; use ir::traversal::EdgeKind; -use ir::comp::{CompKind, Field, FieldMethods}; use ir::ty::TypeKind; use {HashMap, HashSet}; @@ -121,14 +121,14 @@ impl<'ctx> MonotoneFramework for HasDestructorAnalysis<'ctx> { let base_or_field_destructor = info.base_members().iter().any(|base| { self.have_destructor.contains(&base.ty.into()) - }) || - info.fields().iter().any(|field| { - match *field { - Field::DataMember(ref data) => - self.have_destructor.contains(&data.ty().into()), - Field::Bitfields(_) => false - } - }); + }) || info.fields().iter().any( + |field| match *field { + Field::DataMember(ref data) => self + .have_destructor + .contains(&data.ty().into()), + Field::Bitfields(_) => false, + }, + ); if base_or_field_destructor { self.insert(id) } else { @@ -139,9 +139,9 @@ impl<'ctx> MonotoneFramework for HasDestructorAnalysis<'ctx> { } TypeKind::TemplateInstantiation(ref inst) => { - let definition_or_arg_destructor = - self.have_destructor.contains(&inst.template_definition().into()) - || + let definition_or_arg_destructor = self + .have_destructor + .contains(&inst.template_definition().into()) || inst.template_arguments().iter().any(|arg| { self.have_destructor.contains(&arg.into()) }); diff --git a/src/ir/analysis/has_float.rs b/src/ir/analysis/has_float.rs index 69cfcc859e..7c62a9e278 100644 --- a/src/ir/analysis/has_float.rs +++ b/src/ir/analysis/has_float.rs @@ -1,12 +1,12 @@ //! Determining which types has float. -use super::{ConstrainResult, MonotoneFramework, generate_dependencies}; -use {HashSet, HashMap}; +use super::{generate_dependencies, ConstrainResult, MonotoneFramework}; +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 {HashMap, HashSet}; /// An analysis that finds for each IR item whether it has float or not. /// @@ -132,24 +132,27 @@ impl<'ctx> MonotoneFramework for HasFloat<'ctx> { ConstrainResult::Same } - TypeKind::Float(..) | - TypeKind::Complex(..) => { + TypeKind::Float(..) | TypeKind::Complex(..) => { trace!(" float type has float"); self.insert(id) } TypeKind::Array(t, _) => { if self.has_float.contains(&t.into()) { - trace!(" Array with type T that has float also has float"); - return self.insert(id) + trace!( + " Array with type T that has float also has float" + ); + return self.insert(id); } trace!(" Array with type T that do not have float also do not have float"); ConstrainResult::Same } TypeKind::Vector(t, _) => { if self.has_float.contains(&t.into()) { - trace!(" Vector with type T that has float also has float"); - return self.insert(id) + trace!( + " Vector with type T that has float also has float" + ); + return self.insert(id); } trace!(" Vector with type T that do not have float also do not have float"); ConstrainResult::Same @@ -160,8 +163,10 @@ impl<'ctx> MonotoneFramework for HasFloat<'ctx> { TypeKind::Alias(t) | TypeKind::BlockPointer(t) => { if self.has_float.contains(&t.into()) { - trace!(" aliases and type refs to T which have float \ - also have float"); + trace!( + " aliases and type refs to T which have float \ + also have float" + ); self.insert(id) } else { trace!(" aliases and type refs to T which do not have float \ @@ -171,28 +176,23 @@ impl<'ctx> MonotoneFramework for HasFloat<'ctx> { } TypeKind::Comp(ref info) => { - let bases_have = info.base_members() + let bases_have = info + .base_members() .iter() .any(|base| self.has_float.contains(&base.ty.into())); if bases_have { trace!(" bases have float, so we also have"); return self.insert(id); } - let fields_have = info.fields() - .iter() - .any(|f| { - match *f { - Field::DataMember(ref data) => { - self.has_float.contains(&data.ty().into()) - } - Field::Bitfields(ref bfu) => { - bfu.bitfields() - .iter().any(|b| { - self.has_float.contains(&b.ty().into()) - }) - }, - } - }); + let fields_have = info.fields().iter().any(|f| match *f { + Field::DataMember(ref data) => { + self.has_float.contains(&data.ty().into()) + } + Field::Bitfields(ref bfu) => bfu + .bitfields() + .iter() + .any(|b| self.has_float.contains(&b.ty().into())), + }); if fields_have { trace!(" fields have float, so we also have"); return self.insert(id); @@ -203,20 +203,26 @@ impl<'ctx> MonotoneFramework for HasFloat<'ctx> { } TypeKind::TemplateInstantiation(ref template) => { - let args_have = template.template_arguments() + let args_have = template + .template_arguments() .iter() .any(|arg| self.has_float.contains(&arg.into())); if args_have { - trace!(" template args have float, so \ - insantiation also has float"); + trace!( + " template args have float, so \ + insantiation also has float" + ); return self.insert(id); } - let def_has = self.has_float + let def_has = self + .has_float .contains(&template.template_definition().into()); if def_has { - trace!(" template definition has float, so \ - insantiation also has"); + trace!( + " template definition has float, so \ + insantiation also has" + ); return self.insert(id); } @@ -227,7 +233,8 @@ impl<'ctx> MonotoneFramework for HasFloat<'ctx> { } 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 98959f0f12..4217f6f045 100644 --- a/src/ir/analysis/has_type_param_in_array.rs +++ b/src/ir/analysis/has_type_param_in_array.rs @@ -1,6 +1,6 @@ //! Determining which types has typed parameters in array. -use super::{ConstrainResult, MonotoneFramework, generate_dependencies}; +use super::{generate_dependencies, ConstrainResult, MonotoneFramework}; use ir::comp::Field; use ir::comp::FieldMethods; use ir::context::{BindgenContext, ItemId}; @@ -88,9 +88,7 @@ impl<'ctx> MonotoneFramework for HasTypeParameterInArray<'ctx> { type Extra = &'ctx BindgenContext; type Output = HashSet; - fn new( - ctx: &'ctx BindgenContext, - ) -> HasTypeParameterInArray<'ctx> { + fn new(ctx: &'ctx BindgenContext) -> HasTypeParameterInArray<'ctx> { let has_type_parameter_in_array = HashSet::default(); let dependencies = generate_dependencies(ctx, Self::consider_edge); @@ -169,7 +167,7 @@ impl<'ctx> MonotoneFramework for HasTypeParameterInArray<'ctx> { if self.has_type_parameter_in_array.contains(&t.into()) { trace!( " aliases and type refs to T which have array \ - also have array" + also have array" ); self.insert(id) } else { @@ -190,9 +188,9 @@ impl<'ctx> MonotoneFramework for HasTypeParameterInArray<'ctx> { 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().into()) - } + Field::DataMember(ref data) => self + .has_type_parameter_in_array + .contains(&data.ty().into()), Field::Bitfields(..) => false, }); if fields_have { @@ -212,18 +210,18 @@ impl<'ctx> MonotoneFramework for HasTypeParameterInArray<'ctx> { if args_have { trace!( " template args have array, so \ - insantiation also has array" + insantiation also has array" ); return self.insert(id); } - let def_has = self.has_type_parameter_in_array.contains( - &template.template_definition().into(), - ); + let def_has = self + .has_type_parameter_in_array + .contains(&template.template_definition().into()); if def_has { trace!( " template definition has array, so \ - insantiation also has" + insantiation also has" ); return self.insert(id); } diff --git a/src/ir/analysis/has_vtable.rs b/src/ir/analysis/has_vtable.rs index 410fca0576..40b997922e 100644 --- a/src/ir/analysis/has_vtable.rs +++ b/src/ir/analysis/has_vtable.rs @@ -1,12 +1,12 @@ //! Determining which types has vtable -use super::{ConstrainResult, MonotoneFramework, generate_dependencies}; +use super::{generate_dependencies, ConstrainResult, MonotoneFramework}; use ir::context::{BindgenContext, ItemId}; use ir::traversal::EdgeKind; use ir::ty::TypeKind; use std::cmp; use std::ops; -use {HashMap, Entry}; +use {Entry, HashMap}; /// The result of the `HasVtableAnalysis` for an individual item. #[derive(Copy, Clone, Debug, PartialEq, Eq, Ord)] @@ -19,7 +19,7 @@ pub enum HasVtableResult { SelfHasVtable, /// The item does not have a vtable pointer. - No + No, } impl Default for HasVtableResult { @@ -104,7 +104,11 @@ impl<'ctx> HasVtableAnalysis<'ctx> { } } - fn insert>(&mut self, id: Id, result: HasVtableResult) -> ConstrainResult { + fn insert>( + &mut self, + id: Id, + result: HasVtableResult, + ) -> ConstrainResult { if let HasVtableResult::No = result { return ConstrainResult::Same; } @@ -176,7 +180,9 @@ impl<'ctx> MonotoneFramework for HasVtableAnalysis<'ctx> { TypeKind::Alias(t) | TypeKind::ResolvedTypeRef(t) | TypeKind::Reference(t) => { - trace!(" aliases and references forward to their inner type"); + trace!( + " aliases and references forward to their inner type" + ); self.forward(t, id) } @@ -224,9 +230,10 @@ impl<'ctx> MonotoneFramework for HasVtableAnalysis<'ctx> { impl<'ctx> From> for HashMap { fn from(analysis: HasVtableAnalysis<'ctx>) -> Self { // We let the lack of an entry mean "No" to save space. - extra_assert!(analysis.have_vtable.values().all(|v| { - *v != HasVtableResult::No - })); + extra_assert!(analysis + .have_vtable + .values() + .all(|v| { *v != HasVtableResult::No })); analysis.have_vtable } diff --git a/src/ir/analysis/mod.rs b/src/ir/analysis/mod.rs index 9de6833b8b..a3ba9848d9 100644 --- a/src/ir/analysis/mod.rs +++ b/src/ir/analysis/mod.rs @@ -41,7 +41,7 @@ mod template_params; pub use self::template_params::UsedTemplateParameters; mod derive; -pub use self::derive::{CannotDerive, DeriveTrait, as_cannot_derive_set}; +pub use self::derive::{as_cannot_derive_set, CannotDerive, DeriveTrait}; mod has_vtable; pub use self::has_vtable::{HasVtable, HasVtableAnalysis, HasVtableResult}; mod has_destructor; @@ -56,9 +56,9 @@ pub use self::sizedness::{Sizedness, SizednessAnalysis, SizednessResult}; use ir::context::{BindgenContext, ItemId}; use ir::traversal::{EdgeKind, Trace}; -use HashMap; use std::fmt; use std::ops; +use HashMap; /// An analysis in the monotone framework. /// @@ -164,10 +164,9 @@ where 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); + }); } } @@ -196,9 +195,10 @@ where if ctx.whitelisted_items().contains(&sub_item) && consider_edge(edge_kind) { - dependencies.entry(sub_item).or_insert(vec![]).push( - item, - ); + dependencies + .entry(sub_item) + .or_insert(vec![]) + .push(item); } }, &(), @@ -325,13 +325,17 @@ mod tests { // Yes, what follows is a **terribly** inefficient set union // implementation. Don't copy this code outside of this test! - let original_size = - self.reachable.entry(node).or_insert(HashSet::default()).len(); + let original_size = self + .reachable + .entry(node) + .or_insert(HashSet::default()) + .len(); for sub_node in self.graph.0[&node].iter() { self.reachable.get_mut(&node).unwrap().insert(*sub_node); - let sub_reachable = self.reachable + let sub_reachable = self + .reachable .entry(*sub_node) .or_insert(HashSet::default()) .clone(); diff --git a/src/ir/analysis/sizedness.rs b/src/ir/analysis/sizedness.rs index dbf0e37df4..92a47ea8f9 100644 --- a/src/ir/analysis/sizedness.rs +++ b/src/ir/analysis/sizedness.rs @@ -1,12 +1,14 @@ //! Determining the sizedness of types (as base classes and otherwise). -use super::{ConstrainResult, MonotoneFramework, HasVtable, generate_dependencies}; +use super::{ + generate_dependencies, ConstrainResult, HasVtable, MonotoneFramework, +}; use ir::context::{BindgenContext, TypeId}; use ir::item::IsOpaque; use ir::traversal::EdgeKind; use ir::ty::TypeKind; use std::{cmp, ops}; -use {HashMap, Entry}; +use {Entry, HashMap}; /// The result of the `Sizedness` analysis for an individual item. /// @@ -140,7 +142,11 @@ impl<'ctx> SizednessAnalysis<'ctx> { /// Insert an incremental result, and return whether this updated our /// knowledge of types and we should continue the analysis. - fn insert(&mut self, id: TypeId, result: SizednessResult) -> ConstrainResult { + fn insert( + &mut self, + id: TypeId, + result: SizednessResult, + ) -> ConstrainResult { trace!("inserting {:?} for {:?}", result, id); if let SizednessResult::ZeroSized = result { @@ -180,15 +186,15 @@ impl<'ctx> MonotoneFramework for SizednessAnalysis<'ctx> { let dependencies = generate_dependencies(ctx, Self::consider_edge) .into_iter() .filter_map(|(id, sub_ids)| { - id.as_type_id(ctx) - .map(|id| { - ( - id, - sub_ids.into_iter() - .filter_map(|s| s.as_type_id(ctx)) - .collect::>() - ) - }) + id.as_type_id(ctx).map(|id| { + ( + id, + sub_ids + .into_iter() + .filter_map(|s| s.as_type_id(ctx)) + .collect::>(), + ) + }) }) .collect(); @@ -213,7 +219,9 @@ impl<'ctx> MonotoneFramework for SizednessAnalysis<'ctx> { fn constrain(&mut self, id: TypeId) -> ConstrainResult { trace!("constrain {:?}", id); - if let Some(SizednessResult::NonZeroSized) = self.sized.get(&id).cloned() { + if let Some(SizednessResult::NonZeroSized) = + self.sized.get(&id).cloned() + { trace!(" already know it is not zero-sized"); return ConstrainResult::Same; } @@ -227,8 +235,8 @@ impl<'ctx> MonotoneFramework for SizednessAnalysis<'ctx> { if id.is_opaque(self.ctx, &()) { trace!(" type is opaque; checking layout..."); - let result = ty.layout(self.ctx) - .map_or(SizednessResult::ZeroSized, |l| { + let result = + ty.layout(self.ctx).map_or(SizednessResult::ZeroSized, |l| { if l.size == 0 { trace!(" ...layout has size == 0"); SizednessResult::ZeroSized @@ -247,8 +255,10 @@ impl<'ctx> MonotoneFramework for SizednessAnalysis<'ctx> { } TypeKind::TypeParam => { - trace!(" type params sizedness depends on what they're \ - instantiated as"); + trace!( + " type params sizedness depends on what they're \ + instantiated as" + ); self.insert(id, SizednessResult::DependsOnTypeParam) } @@ -280,8 +290,10 @@ impl<'ctx> MonotoneFramework for SizednessAnalysis<'ctx> { } TypeKind::TemplateInstantiation(ref inst) => { - trace!(" template instantiations are zero-sized if their \ - definition is zero-sized"); + trace!( + " template instantiations are zero-sized if their \ + definition is zero-sized" + ); self.forward(inst.template_definition(), id) } @@ -305,7 +317,8 @@ impl<'ctx> MonotoneFramework for SizednessAnalysis<'ctx> { return self.insert(id, SizednessResult::NonZeroSized); } - let result = info.base_members() + let result = info + .base_members() .iter() .filter_map(|base| self.sized.get(&base.ty)) .fold(SizednessResult::ZeroSized, |a, b| a.join(*b)); @@ -339,9 +352,10 @@ impl<'ctx> MonotoneFramework for SizednessAnalysis<'ctx> { impl<'ctx> From> for HashMap { fn from(analysis: SizednessAnalysis<'ctx>) -> Self { // We let the lack of an entry mean "ZeroSized" to save space. - extra_assert!(analysis.sized.values().all(|v| { - *v != SizednessResult::ZeroSized - })); + extra_assert!(analysis + .sized + .values() + .all(|v| { *v != SizednessResult::ZeroSized })); analysis.sized } diff --git a/src/ir/analysis/template_params.rs b/src/ir/analysis/template_params.rs index bd1b51a2f0..da392162a1 100644 --- a/src/ir/analysis/template_params.rs +++ b/src/ir/analysis/template_params.rs @@ -203,18 +203,21 @@ impl<'ctx> UsedTemplateParameters<'ctx> { } } - fn take_this_id_usage_set>(&mut self, this_id: Id) -> ItemSet { + fn take_this_id_usage_set>( + &mut self, + this_id: Id, + ) -> ItemSet { let this_id = this_id.into(); self.used .get_mut(&this_id) .expect( "Should have a set of used template params for every item \ - id", + id", ) .take() .expect( "Should maintain the invariant that all used template param \ - sets are `Some` upon entry of `constrain`", + sets are `Some` upon entry of `constrain`", ) } @@ -231,7 +234,7 @@ impl<'ctx> UsedTemplateParameters<'ctx> { ) { trace!( " instantiation of blacklisted template, uses all template \ - arguments" + arguments" ); let args = instantiation @@ -252,8 +255,8 @@ impl<'ctx> UsedTemplateParameters<'ctx> { .as_ref() .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`", + param sets other than this_id's are `Some`, \ + a's used template param set should be `Some`", ) .iter() .cloned() @@ -289,7 +292,7 @@ impl<'ctx> UsedTemplateParameters<'ctx> { for (arg, param) in args.iter().zip(params.iter()) { trace!( " instantiation's argument {:?} is used if definition's \ - parameter {:?} is used", + parameter {:?} is used", arg, param ); @@ -297,7 +300,8 @@ impl<'ctx> UsedTemplateParameters<'ctx> { if used_by_def.contains(¶m.into()) { trace!(" param is used by template definition"); - let arg = arg.into_resolver() + let arg = arg + .into_resolver() .through_type_refs() .through_type_aliases() .resolve(self.ctx) @@ -307,15 +311,16 @@ impl<'ctx> UsedTemplateParameters<'ctx> { continue; } - let used_by_arg = self.used + let used_by_arg = self + .used .get(&arg) .expect("Should have a used entry for the template arg") .as_ref() .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`", + param sets other than this_id's are `Some`, \ + arg's used template param set should be \ + `Some`", ) .iter() .cloned(); @@ -339,7 +344,8 @@ impl<'ctx> UsedTemplateParameters<'ctx> { return; } - let used_by_sub_id = self.used + let used_by_sub_id = self + .used .get(&sub_id) .expect("Should have a used set for the sub_id successor") .as_ref() @@ -370,9 +376,7 @@ impl<'ctx> MonotoneFramework for UsedTemplateParameters<'ctx> { type Extra = &'ctx BindgenContext; type Output = HashMap; - fn new( - ctx: &'ctx BindgenContext, - ) -> UsedTemplateParameters<'ctx> { + fn new(ctx: &'ctx BindgenContext) -> UsedTemplateParameters<'ctx> { let mut used = HashMap::default(); let mut dependencies = HashMap::default(); let whitelisted_items: HashSet<_> = @@ -383,7 +387,13 @@ impl<'ctx> MonotoneFramework for UsedTemplateParameters<'ctx> { .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(); @@ -399,9 +409,10 @@ impl<'ctx> MonotoneFramework for UsedTemplateParameters<'ctx> { ctx, &mut |sub_item: ItemId, _| { used.entry(sub_item).or_insert(Some(ItemSet::new())); - dependencies.entry(sub_item).or_insert(vec![]).push( - item, - ); + dependencies + .entry(sub_item) + .or_insert(vec![]) + .push(item); }, &(), ); @@ -418,11 +429,11 @@ impl<'ctx> MonotoneFramework for UsedTemplateParameters<'ctx> { // 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); + let params = decl.self_template_params(ctx); for (arg, param) in args.iter().zip(params.iter()) { - let arg = arg.into_resolver() + let arg = arg + .into_resolver() .through_type_aliases() .through_type_refs() .resolve(ctx) @@ -487,7 +498,13 @@ impl<'ctx> MonotoneFramework for UsedTemplateParameters<'ctx> { .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() @@ -520,9 +537,9 @@ impl<'ctx> MonotoneFramework for UsedTemplateParameters<'ctx> { // 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().into(), - ) + if self + .whitelisted_items + .contains(&inst.template_definition().into()) { self.constrain_instantiation( id, @@ -548,7 +565,7 @@ impl<'ctx> MonotoneFramework for UsedTemplateParameters<'ctx> { 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!" + if it doesn't hold, the analysis might never terminate!" ); // Put the set back in the hash map and restore our invariant. @@ -576,8 +593,7 @@ impl<'ctx> MonotoneFramework for UsedTemplateParameters<'ctx> { } } -impl<'ctx> From> - for HashMap { +impl<'ctx> From> for HashMap { fn from(used_templ_params: UsedTemplateParameters<'ctx>) -> Self { used_templ_params .used diff --git a/src/ir/annotations.rs b/src/ir/annotations.rs index 654e168602..403bffc100 100644 --- a/src/ir/annotations.rs +++ b/src/ir/annotations.rs @@ -94,7 +94,11 @@ impl Annotations { let mut matched_one = false; anno.parse(&cursor.comment(), &mut matched_one); - if matched_one { Some(anno) } else { None } + if matched_one { + Some(anno) + } else { + None + } } /// Should this type be hidden? @@ -157,9 +161,10 @@ impl Annotations { 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_attrs() + .next() + .map_or(false, |attr| attr.name == "rustbindgen") { *matched = true; for attr in comment.get_tag_attrs() { @@ -168,14 +173,11 @@ impl Annotations { "hide" => self.hide = true, "nocopy" => self.disallow_copy = true, "replaces" => { - self.use_instead_of = - Some( - attr.value.split("::").map(Into::into).collect(), - ) - } - "derive" => { - self.derives.push(attr.value) + self.use_instead_of = Some( + attr.value.split("::").map(Into::into).collect(), + ) } + "derive" => self.derives.push(attr.value), "private" => { self.private_fields = Some(attr.value != "false") } diff --git a/src/ir/comment.rs b/src/ir/comment.rs index a189fe8a0a..4ebe19a225 100644 --- a/src/ir/comment.rs +++ b/src/ir/comment.rs @@ -67,7 +67,8 @@ fn preprocess_multi_line(comment: &str, indent: usize) -> String { let indent = make_indent(indent); // Strip any potential `*` characters preceding each line. let mut is_first = true; - let mut lines: Vec<_> = comment.lines() + let mut lines: Vec<_> = comment + .lines() .map(|line| line.trim().trim_start_matches('*').trim_start_matches('!')) .skip_while(|line| line.trim().is_empty()) // Skip the first empty lines. .map(|line| { @@ -78,7 +79,10 @@ fn preprocess_multi_line(comment: &str, indent: usize) -> String { .collect(); // Remove the trailing line corresponding to the `*/`. - if lines.last().map_or(false, |l| l.trim().is_empty() || l.trim() == "///") { + if lines + .last() + .map_or(false, |l| l.trim().is_empty() || l.trim() == "///") + { lines.pop(); } diff --git a/src/ir/comp.rs b/src/ir/comp.rs index 5e0b3ed62a..a82fd756af 100644 --- a/src/ir/comp.rs +++ b/src/ir/comp.rs @@ -52,13 +52,13 @@ pub enum MethodKind { }, } - impl MethodKind { /// Is this a destructor method? pub fn is_destructor(&self) -> bool { match *self { - MethodKind::Destructor | - MethodKind::VirtualDestructor { .. } => true, + MethodKind::Destructor | MethodKind::VirtualDestructor { .. } => { + true + } _ => false, } } @@ -87,7 +87,11 @@ pub struct Method { impl Method { /// Construct a new `Method`. - pub fn new(kind: MethodKind, signature: FunctionId, is_const: bool) -> Self { + pub fn new( + kind: MethodKind, + signature: FunctionId, + is_const: bool, + ) -> Self { Method { kind, signature, @@ -198,9 +202,7 @@ impl Field { /// 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) } @@ -219,9 +221,7 @@ impl Trace for Field { Field::DataMember(ref data) => { tracer.visit_kind(data.ty.into(), EdgeKind::Field); } - Field::Bitfields(BitfieldUnit { - ref bitfields, .. - }) => { + Field::Bitfields(BitfieldUnit { ref bitfields, .. }) => { for bf in bitfields { tracer.visit_kind(bf.ty().into(), EdgeKind::Field); } @@ -242,10 +242,10 @@ impl DotAttributes for Field { match *self { Field::DataMember(ref data) => data.dot_attributes(ctx, out), Field::Bitfields(BitfieldUnit { - layout, - ref bitfields, - .. - }) => { + layout, + ref bitfields, + .. + }) => { writeln!( out, r#" @@ -259,8 +259,7 @@ impl DotAttributes for Field { unit.align{} "#, - layout.size, - layout.align + layout.size, layout.align )?; for bf in bitfields { bf.dot_attributes(ctx, out)?; @@ -373,7 +372,10 @@ impl Bitfield { /// Panics if called before assigning bitfield accessor names or if /// this bitfield have no name. pub fn getter_name(&self) -> &str { - assert!(self.name().is_some(), "`Bitfield::getter_name` called on anonymous field"); + assert!( + self.name().is_some(), + "`Bitfield::getter_name` called on anonymous field" + ); self.getter_name.as_ref().expect( "`Bitfield::getter_name` should only be called after\ assigning bitfield accessor names", @@ -385,7 +387,10 @@ impl Bitfield { /// Panics if called before assigning bitfield accessor names or if /// this bitfield have no name. pub fn setter_name(&self) -> &str { - assert!(self.name().is_some(), "`Bitfield::setter_name` called on anonymous field"); + assert!( + self.name().is_some(), + "`Bitfield::setter_name` called on anonymous field" + ); self.setter_name.as_ref().expect( "`Bitfield::setter_name` should only be called\ after assigning bitfield accessor names", @@ -423,7 +428,6 @@ impl FieldMethods for Bitfield { } } - /// A raw field might be either of a plain data member or a bitfield within a /// bitfield allocation unit, but we haven't processed it and determined which /// yet (which would involve allocating it into a bitfield unit if it is a @@ -597,9 +601,8 @@ where for bitfield in raw_bitfields { let bitfield_width = bitfield.bitfield_width().unwrap() as usize; - let bitfield_layout = ctx.resolve_type(bitfield.ty()) - .layout(ctx) - .ok_or(())?; + let bitfield_layout = + ctx.resolve_type(bitfield.ty()).layout(ctx).ok_or(())?; let bitfield_size = bitfield_layout.size; let bitfield_align = bitfield_layout.align; @@ -628,8 +631,8 @@ where } 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); } @@ -724,20 +727,17 @@ impl CompFields { } }; - let result = - raw_fields_to_fields_and_bitfield_units(ctx, raws); + let result = raw_fields_to_fields_and_bitfield_units(ctx, raws); match result { Ok(fields_and_units) => { mem::replace( self, - CompFields::AfterComputingBitfieldUnits(fields_and_units)); + CompFields::AfterComputingBitfieldUnits(fields_and_units), + ); } Err(()) => { - mem::replace( - self, - CompFields::ErrorComputingBitfieldUnits - ); + mem::replace(self, CompFields::ErrorComputingBitfieldUnits); } } } @@ -754,7 +754,11 @@ impl CompFields { } }; - fn has_method(methods: &[Method], ctx: &BindgenContext, name: &str) -> bool { + fn has_method( + methods: &[Method], + ctx: &BindgenContext, + name: &str, + ) -> bool { methods.iter().any(|method| { let method_name = ctx.resolve_func(method.signature()).name(); method_name == name || ctx.rust_mangle(&method_name) == name @@ -776,7 +780,8 @@ impl CompFields { .map(|bitfield_name| { let bitfield_name = bitfield_name.to_string(); let getter = { - let mut getter = ctx.rust_mangle(&bitfield_name).to_string(); + let mut getter = + ctx.rust_mangle(&bitfield_name).to_string(); if has_method(methods, ctx, &getter) { getter.push_str("_bindgen_bitfield"); } @@ -803,21 +808,24 @@ impl CompFields { } anon_field_counter += 1; - let generated_name = format!("__bindgen_anon_{}", anon_field_counter); + let generated_name = + format!("__bindgen_anon_{}", anon_field_counter); *name = Some(generated_name); } - Field::Bitfields(ref mut bu) => for bitfield in &mut bu.bitfields { - if bitfield.name().is_none() { - continue; - } + Field::Bitfields(ref mut bu) => { + for bitfield in &mut bu.bitfields { + if bitfield.name().is_none() { + continue; + } - if let Some(AccessorNamesPair { getter, setter }) = - accessor_names.remove(bitfield.name().unwrap()) - { - bitfield.getter_name = Some(getter); - bitfield.setter_name = Some(setter); + if let Some(AccessorNamesPair { getter, setter }) = + accessor_names.remove(bitfield.name().unwrap()) + { + bitfield.getter_name = Some(getter); + bitfield.setter_name = Some(setter); + } } - }, + } } } } @@ -1185,8 +1193,7 @@ impl CompInfo { let mut ci = CompInfo::new(kind); ci.is_forward_declaration = location.map_or(true, |cur| match cur.kind() { - CXCursor_StructDecl | - CXCursor_UnionDecl | + CXCursor_StructDecl | CXCursor_UnionDecl | CXCursor_ClassDecl => !cur.is_definition(), _ => false, }); @@ -1195,16 +1202,20 @@ impl CompInfo { cursor.visit(|cur| { if cur.kind() != CXCursor_FieldDecl { if let Some((ty, clang_ty, offset)) = - maybe_anonymous_struct_field.take() { + maybe_anonymous_struct_field.take() + { if cur.kind() == CXCursor_TypedefDecl && - cur.typedef_type().unwrap().canonical_type() == clang_ty { + cur.typedef_type().unwrap().canonical_type() == + clang_ty + { // Typedefs of anonymous structs appear later in the ast // than the struct itself, that would otherwise be an // anonymous field. Detect that case here, and do // nothing. } else { - let field = - RawField::new(None, ty, None, None, None, false, offset); + let field = RawField::new( + None, ty, None, None, None, false, offset, + ); ci.fields.append_raw_field(field); } } @@ -1213,7 +1224,8 @@ impl CompInfo { match cur.kind() { CXCursor_FieldDecl => { if let Some((ty, clang_ty, offset)) = - maybe_anonymous_struct_field.take() { + maybe_anonymous_struct_field.take() + { let mut used = false; cur.visit(|child| { if child.cur_type() == clang_ty { @@ -1222,22 +1234,20 @@ impl CompInfo { CXChildVisit_Continue }); if !used { - let field = RawField::new(None, - ty, - None, - None, - None, - false, - offset); + let field = RawField::new( + None, ty, None, None, None, false, offset, + ); ci.fields.append_raw_field(field); } } let bit_width = cur.bit_width(); - let field_type = Item::from_ty_or_ref(cur.cur_type(), - cur, - Some(potential_id), - ctx); + let field_type = Item::from_ty_or_ref( + cur.cur_type(), + cur, + Some(potential_id), + ctx, + ); let comment = cur.raw_comment(); let annotations = Annotations::new(&cur); @@ -1247,18 +1257,22 @@ impl CompInfo { // Name can be empty if there are bitfields, for example, // see tests/headers/struct_with_bitfields.h - assert!(!name.is_empty() || bit_width.is_some(), - "Empty field name?"); + assert!( + !name.is_empty() || bit_width.is_some(), + "Empty field name?" + ); let name = if name.is_empty() { None } else { Some(name) }; - let field = RawField::new(name, - field_type, - comment, - annotations, - bit_width, - is_mutable, - offset); + let field = RawField::new( + name, + field_type, + comment, + annotations, + bit_width, + is_mutable, + offset, + ); ci.fields.append_raw_field(field); // No we look for things like attributes and stuff. @@ -1268,7 +1282,6 @@ impl CompInfo { } CXChildVisit_Continue }); - } CXCursor_UnexposedAttr => { ci.found_unknown_attr = true; @@ -1293,8 +1306,8 @@ impl CompInfo { // definition, it's a valid inner type. // // [1]: https://github.com/rust-lang/rust-bindgen/issues/482 - let is_inner_struct = cur.semantic_parent() == cursor || - cur.is_definition(); + let is_inner_struct = + cur.semantic_parent() == cursor || cur.is_definition(); if !is_inner_struct { return CXChildVisit_Continue; } @@ -1311,19 +1324,22 @@ impl CompInfo { // A declaration of an union or a struct without name could // also be an unnamed field, unfortunately. if cur.spelling().is_empty() && - cur.kind() != CXCursor_EnumDecl { + cur.kind() != CXCursor_EnumDecl + { let ty = cur.cur_type(); let offset = cur.offset_of_field().ok(); - maybe_anonymous_struct_field = Some((inner, ty, offset)); + maybe_anonymous_struct_field = + Some((inner, ty, offset)); } } CXCursor_PackedAttr => { ci.packed_attr = true; } CXCursor_TemplateTypeParameter => { - let param = Item::type_param(None, cur, ctx) - .expect("Item::type_param should't fail when pointing \ - at a TemplateTypeParameter"); + 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); } CXCursor_CXXBaseSpecifier => { @@ -1348,8 +1364,7 @@ impl CompInfo { field_name: field_name, }); } - CXCursor_Constructor | - CXCursor_Destructor | + CXCursor_Constructor | CXCursor_Destructor | CXCursor_CXXMethod => { let is_virtual = cur.method_is_virtual(); let is_static = cur.method_is_static(); @@ -1376,9 +1391,14 @@ impl CompInfo { // `FunctionSig`. let signature = match Item::parse(cur, Some(potential_id), ctx) { - Ok(item) if ctx.resolve_item(item) - .kind() - .is_function() => item, + Ok(item) + if ctx + .resolve_item(item) + .kind() + .is_function() => + { + item + } _ => return CXChildVisit_Continue, }; @@ -1424,7 +1444,8 @@ impl CompInfo { CXCursor_VarDecl => { let linkage = cur.linkage(); if linkage != CXLinkage_External && - linkage != CXLinkage_UniqueExternal { + linkage != CXLinkage_UniqueExternal + { return CXChildVisit_Continue; } @@ -1433,9 +1454,8 @@ impl CompInfo { return CXChildVisit_Continue; } - if let Ok(item) = Item::parse(cur, - Some(potential_id), - ctx) { + if let Ok(item) = Item::parse(cur, Some(potential_id), ctx) + { ci.inner_vars.push(item.as_var_id_unchecked()); } } @@ -1445,11 +1465,13 @@ impl CompInfo { CXCursor_FunctionTemplate | CXCursor_ConversionFunction => {} _ => { - warn!("unhandled comp member `{}` (kind {:?}) in `{}` ({})", - cur.spelling(), - clang::kind_to_str(cur.kind()), - cursor.spelling(), - cur.location()); + warn!( + "unhandled comp member `{}` (kind {:?}) in `{}` ({})", + cur.spelling(), + clang::kind_to_str(cur.kind()), + cursor.spelling(), + cur.location() + ); } } CXChildVisit_Continue @@ -1470,16 +1492,13 @@ impl CompInfo { use clang_sys::*; Ok(match cursor.kind() { CXCursor_UnionDecl => CompKind::Union, - CXCursor_ClassDecl | - CXCursor_StructDecl => CompKind::Struct, + CXCursor_ClassDecl | CXCursor_StructDecl => CompKind::Struct, CXCursor_CXXBaseSpecifier | CXCursor_ClassTemplatePartialSpecialization | - CXCursor_ClassTemplate => { - match cursor.template_kind() { - CXCursor_UnionDecl => CompKind::Union, - _ => CompKind::Struct, - } - } + CXCursor_ClassTemplate => match cursor.template_kind() { + CXCursor_UnionDecl => CompKind::Union, + _ => CompKind::Struct, + }, _ => { warn!("Unknown kind for comp type: {:?}", cursor); return Err(ParseError::Continue); @@ -1505,9 +1524,13 @@ impl CompInfo { } /// Is this compound type packed? - pub fn is_packed(&self, ctx: &BindgenContext, layout: &Option) -> bool { + pub fn is_packed( + &self, + ctx: &BindgenContext, + layout: &Option, + ) -> bool { if self.packed_attr { - return true + return true; } // Even though `libclang` doesn't expose `#pragma packed(...)`, we can @@ -1632,7 +1655,7 @@ impl IsOpaque for CompInfo { fn is_opaque(&self, ctx: &BindgenContext, layout: &Option) -> bool { if self.has_non_type_template_params { - return true + return true; } // When we do not have the layout for a bitfield's type (for example, it @@ -1647,17 +1670,14 @@ impl IsOpaque for CompInfo { // some strange things going on, and the best we can do is make the // whole struct opaque. if self.fields().iter().any(|f| match *f { - Field::DataMember(_) => { - false - }, - Field::Bitfields(ref unit) => { - unit.bitfields().iter().any(|bf| { - let bitfield_layout = ctx.resolve_type(bf.ty()) - .layout(ctx) - .expect("Bitfield without layout? Gah!"); - bf.width() / 8 > bitfield_layout.size as u32 - }) - } + Field::DataMember(_) => false, + Field::Bitfields(ref unit) => unit.bitfields().iter().any(|bf| { + let bitfield_layout = ctx + .resolve_type(bf.ty()) + .layout(ctx) + .expect("Bitfield without layout? Gah!"); + bf.width() / 8 > bitfield_layout.size as u32 + }), }) { return true; } @@ -1668,7 +1688,9 @@ impl IsOpaque for CompInfo { // // See https://github.com/rust-lang/rust-bindgen/issues/537 and // https://github.com/rust-lang/rust/issues/33158 - if self.is_packed(ctx, layout) && layout.map_or(false, |l| l.align > 1) { + if self.is_packed(ctx, layout) && + layout.map_or(false, |l| l.align > 1) + { warn!("Found a type that is both packed and aligned to greater than \ 1; Rust before version 1.33 doesn't have `#[repr(packed(N))]`, so we \ are treating it as opaque. You may wish to set bindgen's rust target \ @@ -1682,10 +1704,7 @@ impl IsOpaque for CompInfo { } impl TemplateParameters for CompInfo { - fn self_template_params( - &self, - _ctx: &BindgenContext, - ) -> Vec { + fn self_template_params(&self, _ctx: &BindgenContext) -> Vec { self.template_params.clone() } } diff --git a/src/ir/context.rs b/src/ir/context.rs index 6c9810364a..0fefe399a4 100644 --- a/src/ir/context.rs +++ b/src/ir/context.rs @@ -1,13 +1,17 @@ //! Common context that is passed around during parsing and codegen. -use super::analysis::{CannotDerive, DeriveTrait, as_cannot_derive_set, - HasTypeParameterInArray, HasVtableAnalysis, - HasVtableResult, HasDestructorAnalysis, - UsedTemplateParameters, HasFloat, SizednessAnalysis, - SizednessResult, analyze}; -use super::derive::{CanDeriveCopy, CanDeriveDebug, CanDeriveDefault, - CanDeriveHash, CanDerivePartialOrd, CanDeriveOrd, - CanDerivePartialEq, CanDeriveEq, CanDerive}; +use super::super::time::Timer; +use super::analysis::{ + analyze, as_cannot_derive_set, CannotDerive, DeriveTrait, + HasDestructorAnalysis, HasFloat, HasTypeParameterInArray, + HasVtableAnalysis, HasVtableResult, SizednessAnalysis, SizednessResult, + UsedTemplateParameters, +}; +use super::derive::{ + CanDerive, CanDeriveCopy, CanDeriveDebug, CanDeriveDefault, CanDeriveEq, + CanDeriveHash, CanDeriveOrd, CanDerivePartialEq, CanDerivePartialOrd, +}; +use super::function::Function; use super::int::IntKind; use super::item::{IsOpaque, Item, ItemAncestors, ItemSet}; use super::item_kind::ItemKind; @@ -15,9 +19,6 @@ use super::module::{Module, ModuleKind}; use super::template::{TemplateInstantiation, TemplateParameters}; use super::traversal::{self, Edge, ItemTraversal}; use super::ty::{FloatKind, Type, TypeKind}; -use super::function::Function; -use super::super::time::Timer; -use BindgenOptions; use callbacks::ParseCallbacks; use cexpr; use clang::{self, Cursor}; @@ -26,10 +27,11 @@ use parse::ClangItemParser; use proc_macro2::{Ident, Span}; use std::borrow::Cow; use std::cell::Cell; +use std::collections::HashMap as StdHashMap; use std::iter::IntoIterator; use std::mem; -use std::collections::HashMap as StdHashMap; -use {HashMap, HashSet, Entry}; +use BindgenOptions; +use {Entry, HashMap, HashSet}; /// An identifier for some kind of IR item. #[derive(Debug, Copy, Clone, Eq, PartialOrd, Ord, Hash)] @@ -199,7 +201,7 @@ impl ItemId { impl ::std::cmp::PartialEq for ItemId where - T: Copy + Into + T: Copy + Into, { fn eq(&self, rhs: &T) -> bool { let rhs: ItemId = (*rhs).into(); @@ -209,7 +211,7 @@ where impl CanDeriveDebug for T where - T: Copy + Into + T: Copy + Into, { fn can_derive_debug(&self, ctx: &BindgenContext) -> bool { ctx.options().derive_debug && ctx.lookup_can_derive_debug(*self) @@ -218,7 +220,7 @@ where impl CanDeriveDefault for T where - T: Copy + Into + T: Copy + Into, { fn can_derive_default(&self, ctx: &BindgenContext) -> bool { ctx.options().derive_default && ctx.lookup_can_derive_default(*self) @@ -227,7 +229,7 @@ where impl CanDeriveCopy for T where - T: Copy + Into + T: Copy + Into, { fn can_derive_copy(&self, ctx: &BindgenContext) -> bool { ctx.options().derive_copy && ctx.lookup_can_derive_copy(*self) @@ -236,7 +238,7 @@ where impl CanDeriveHash for T where - T: Copy + Into + T: Copy + Into, { fn can_derive_hash(&self, ctx: &BindgenContext) -> bool { ctx.options().derive_hash && ctx.lookup_can_derive_hash(*self) @@ -245,42 +247,46 @@ where impl CanDerivePartialOrd for T where - T: Copy + Into + T: Copy + Into, { fn can_derive_partialord(&self, ctx: &BindgenContext) -> bool { ctx.options().derive_partialord && - ctx.lookup_can_derive_partialeq_or_partialord(*self) == CanDerive::Yes + ctx.lookup_can_derive_partialeq_or_partialord(*self) == + CanDerive::Yes } } impl CanDerivePartialEq for T where - T: Copy + Into + T: Copy + Into, { fn can_derive_partialeq(&self, ctx: &BindgenContext) -> bool { ctx.options().derive_partialeq && - ctx.lookup_can_derive_partialeq_or_partialord(*self) == CanDerive::Yes + ctx.lookup_can_derive_partialeq_or_partialord(*self) == + CanDerive::Yes } } impl CanDeriveEq for T where - T: Copy + Into + T: Copy + Into, { fn can_derive_eq(&self, ctx: &BindgenContext) -> bool { ctx.options().derive_eq && - ctx.lookup_can_derive_partialeq_or_partialord(*self) == CanDerive::Yes && + ctx.lookup_can_derive_partialeq_or_partialord(*self) == + CanDerive::Yes && !ctx.lookup_has_float(*self) } } impl CanDeriveOrd for T where - T: Copy + Into + T: Copy + Into, { fn can_derive_ord(&self, ctx: &BindgenContext) -> bool { ctx.options().derive_ord && - ctx.lookup_can_derive_partialeq_or_partialord(*self) == CanDerive::Yes && + ctx.lookup_can_derive_partialeq_or_partialord(*self) == + CanDerive::Yes && !ctx.lookup_has_float(*self) } } @@ -476,7 +482,7 @@ impl<'ctx> Iterator for WhitelistedItemsTraversal<'ctx> { let id = self.traversal.next()?; if self.ctx.resolve_item(id).is_blacklisted(self.ctx) { - continue + continue; } return Some(id); @@ -526,7 +532,7 @@ fn find_effective_target(clang_args: &[String]) -> (String, bool) { // If we're running from a build script, try to find the cargo target. if let Ok(t) = env::var("TARGET") { - return (t, false) + return (t, false); } (HOST_TARGET.to_owned(), false) @@ -577,8 +583,11 @@ If you encounter an error missing from this list, please file an issue or a PR!" if let Some(ref ti) = target_info { if effective_target == HOST_TARGET { assert_eq!( - ti.pointer_width / 8, mem::size_of::<*mut ()>(), - "{:?} {:?}", effective_target, HOST_TARGET + ti.pointer_width / 8, + mem::size_of::<*mut ()>(), + "{:?} {:?}", + effective_target, + HOST_TARGET ); } } @@ -677,12 +686,11 @@ If you encounter an error missing from this list, please file an issue or a PR!" ) { debug!( "BindgenContext::add_item({:?}, declaration: {:?}, loc: {:?}", - item, - declaration, - location + item, declaration, location ); debug_assert!( - declaration.is_some() || !item.kind().is_type() || + declaration.is_some() || + !item.kind().is_type() || item.kind().expect_type().is_builtin_or_type_param() || item.kind().expect_type().is_opaque(self, &item) || item.kind().expect_type().is_unresolved_ref(), @@ -692,8 +700,8 @@ If you encounter an error missing from this list, please file an issue or a PR!" 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); @@ -731,7 +739,10 @@ If you encounter an error missing from this list, please file an issue or a PR!" debug!( "Invalid declaration {:?} found for type {:?}", declaration, - self.resolve_item_fallible(id).unwrap().kind().expect_type() + self.resolve_item_fallible(id) + .unwrap() + .kind() + .expect_type() ); return; } @@ -743,8 +754,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" } else { warn!( "Valid declaration with no USR: {:?}, {:?}", - declaration, - location + declaration, location ); TypeKey::Declaration(declaration) }; @@ -794,8 +804,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" pub fn add_type_param(&mut self, item: Item, definition: clang::Cursor) { debug!( "BindgenContext::add_type_param: item = {:?}; definition = {:?}", - item, - definition + item, definition ); assert!( @@ -816,7 +825,9 @@ If you encounter an error missing from this list, please file an issue or a PR!" "should not have already associated an item with the given id" ); - let old_named_ty = self.type_params.insert(definition, id.as_type_id_unchecked()); + let old_named_ty = self + .type_params + .insert(definition, id.as_type_id_unchecked()); assert!( old_named_ty.is_none(), "should not have already associated a named type with this id" @@ -841,61 +852,16 @@ If you encounter an error missing from this list, please file an issue or a PR!" name.contains("?") || name.contains("$") || match name { - "abstract" | - "alignof" | - "as" | - "async" | - "become" | - "box" | - "break" | - "const" | - "continue" | - "crate" | - "do" | - "else" | - "enum" | - "extern" | - "false" | - "final" | - "fn" | - "for" | - "if" | - "impl" | - "in" | - "let" | - "loop" | - "macro" | - "match" | - "mod" | - "move" | - "mut" | - "offsetof" | - "override" | - "priv" | - "proc" | - "pub" | - "pure" | - "ref" | - "return" | - "Self" | - "self" | - "sizeof" | - "static" | - "struct" | - "super" | - "trait" | - "true" | - "type" | - "typeof" | - "unsafe" | - "unsized" | - "use" | - "virtual" | - "where" | - "while" | - "yield" | - "bool" | - "_" => true, + "abstract" | "alignof" | "as" | "async" | "become" | + "box" | "break" | "const" | "continue" | "crate" | "do" | + "else" | "enum" | "extern" | "false" | "final" | "fn" | + "for" | "if" | "impl" | "in" | "let" | "loop" | "macro" | + "match" | "mod" | "move" | "mut" | "offsetof" | + "override" | "priv" | "proc" | "pub" | "pure" | "ref" | + "return" | "Self" | "self" | "sizeof" | "static" | + "struct" | "super" | "trait" | "true" | "type" | "typeof" | + "unsafe" | "unsized" | "use" | "virtual" | "where" | + "while" | "yield" | "bool" | "_" => true, _ => false, } { @@ -912,7 +878,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// Returns a mangled name as a rust identifier. pub fn rust_ident(&self, name: S) -> Ident where - S: AsRef + S: AsRef, { self.rust_ident_raw(self.rust_mangle(name.as_ref())) } @@ -920,20 +886,17 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// Returns a mangled name as a rust identifier. pub fn rust_ident_raw(&self, name: T) -> Ident where - T: AsRef + T: AsRef, { Ident::new(name.as_ref(), Span::call_site()) } /// Iterate over all items that have been defined. pub fn items(&self) -> impl Iterator { - self.items - .iter() - .enumerate() - .filter_map(|(index, item)| { - let item = item.as_ref()?; - Some((ItemId(index), item)) - }) + self.items.iter().enumerate().filter_map(|(index, item)| { + let item = item.as_ref()?; + Some((ItemId(index), item)) + }) } /// Have we collected all unresolved type references yet? @@ -971,19 +934,20 @@ If you encounter an error missing from this list, please file an issue or a PR!" 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[id.0].as_mut().unwrap(); - *item.kind_mut().as_type_mut().unwrap().kind_mut() = - TypeKind::ResolvedTypeRef(resolved); - resolved - }; + let item = self.items[id.0].as_mut().unwrap(); + *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. @@ -1008,7 +972,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// closure is made. fn with_loaned_item(&mut self, id: ItemId, f: F) -> T where - F: (FnOnce(&BindgenContext, &mut Item) -> T) + F: (FnOnce(&BindgenContext, &mut Item) -> T), { let mut item = self.items[id.0].take().unwrap(); @@ -1043,7 +1007,8 @@ If you encounter an error missing from this list, please file an issue or a PR!" fn deanonymize_fields(&mut self) { let _t = self.timer("deanonymize_fields"); - let comp_item_ids: Vec = self.items() + let comp_item_ids: Vec = self + .items() .filter_map(|(id, item)| { if item.kind().as_type()?.is_comp() { return Some(id); @@ -1108,7 +1073,10 @@ If you encounter an error missing from this list, please file an issue or a PR!" // We set this just after parsing the annotation. It's // very unlikely, but this can happen. if self.resolve_item_fallible(*replacement).is_some() { - replacements.push((id.expect_type_id(self), replacement.expect_type_id(self))); + replacements.push(( + id.expect_type_id(self), + replacement.expect_type_id(self), + )); } } } @@ -1157,15 +1125,14 @@ If you encounter an error missing from this list, please file an issue or a PR!" }) }) }; - 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; - new_parent.ancestors(immut_self).find(|id| { - immut_self.resolve_item(*id).is_module() - }) + new_parent + .ancestors(immut_self) + .find(|id| immut_self.resolve_item(*id).is_module()) }; let new_module = new_module.unwrap_or(self.root_module.into()); @@ -1274,26 +1241,25 @@ If you encounter an error missing from this list, please file an issue or a PR!" assert!( { - let id = id.into_resolver() + let id = id + .into_resolver() .through_type_refs() .through_type_aliases() .resolve(self) .id(); - id.ancestors(self).chain(Some(self.root_module.into())).any( - |ancestor| { + id.ancestors(self) + .chain(Some(self.root_module.into())) + .any(|ancestor| { debug!( "Checking if {:?} is a child of {:?}", - id, - ancestor + id, ancestor ); - self.resolve_item(ancestor).as_module().map_or( - false, - |m| { + self.resolve_item(ancestor) + .as_module() + .map_or(false, |m| { m.children().contains(&id) - }, - ) - }, - ) + }) + }) }, "{:?} should be in some ancestor module's children set", id @@ -1377,7 +1343,10 @@ If you encounter an error missing from this list, please file an issue or a PR!" let mut used_params = HashMap::default(); for &id in self.whitelisted_items() { used_params.entry(id).or_insert( - id.self_template_params(self).into_iter().map(|p| p.into()).collect() + id.self_template_params(self) + .into_iter() + .map(|p| p.into()) + .collect(), ); } self.used_template_parameters = Some(used_params); @@ -1493,12 +1462,16 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// /// Panics if the id resolves to an item that is not a type. pub fn safe_resolve_type(&self, type_id: TypeId) -> Option<&Type> { - self.resolve_item_fallible(type_id).map(|t| t.kind().expect_type()) + self.resolve_item_fallible(type_id) + .map(|t| t.kind().expect_type()) } /// Resolve the given `ItemId` into an `Item`, or `None` if no such item /// exists. - pub fn resolve_item_fallible>(&self, id: Id) -> Option<&Item> { + pub fn resolve_item_fallible>( + &self, + id: Id, + ) -> Option<&Item> { self.items.get(id.into().0)?.as_ref() } @@ -1537,12 +1510,11 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// Returns a known semantic parent for a given definition. pub fn known_semantic_parent( &self, - definition: clang::Cursor + definition: clang::Cursor, ) -> Option { self.semantic_parents.get(&definition).cloned() } - /// Given a cursor pointing to the location of a template instantiation, /// return a tuple of the form `(declaration_cursor, declaration_id, /// num_expected_template_args)`. @@ -1560,7 +1532,8 @@ If you encounter an error missing from this list, please file an issue or a PR!" .and_then(|canon_decl| { self.get_resolved_type(&canon_decl).and_then( |template_decl_id| { - let num_params = template_decl_id.num_self_template_params(self); + let num_params = + template_decl_id.num_self_template_params(self); if num_params == 0 { None } else { @@ -1590,7 +1563,8 @@ If you encounter an error missing from this list, please file an issue or a PR!" .cloned() }) .and_then(|template_decl| { - let num_template_params = template_decl.num_self_template_params(self); + let num_template_params = + template_decl.num_self_template_params(self); if num_template_params == 0 { None } else { @@ -1644,11 +1618,12 @@ If you encounter an error missing from this list, please file an issue or a PR!" ty: &clang::Type, location: clang::Cursor, ) -> Option { - let num_expected_args = self.resolve_type(template).num_self_template_params(self); + let num_expected_args = + self.resolve_type(template).num_self_template_params(self); if num_expected_args == 0 { warn!( "Tried to instantiate a template for which we could not \ - determine any template parameters" + determine any template parameters" ); return None; } @@ -1668,13 +1643,14 @@ If you encounter an error missing from this list, please file an issue or a PR!" // 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(); } @@ -1701,8 +1677,13 @@ If you encounter an error missing from this list, please file an issue or a PR!" args.push(ty); } clang_sys::CXCursor_TemplateRef => { - let (template_decl_cursor, template_decl_id, num_expected_template_args) = - self.get_declaration_info_for_template_instantiation(child)?; + let ( + template_decl_cursor, + template_decl_id, + num_expected_template_args, + ) = self.get_declaration_info_for_template_instantiation( + child, + )?; if num_expected_template_args == 0 || child.has_at_least_num_children( @@ -1727,7 +1708,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" if args_len < num_expected_template_args { warn!( "Found a template instantiation without \ - enough template arguments" + enough template arguments" ); return None; } @@ -1767,7 +1748,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" // Bypass all the validations in add_item explicitly. debug!( "instantiate_template: inserting nested \ - instantiation item: {:?}", + instantiation item: {:?}", sub_item ); self.add_item_to_module(&sub_item); @@ -1795,7 +1776,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" // situation... warn!( "Found template instantiated with a const value; \ - bindgen can't handle this kind of template instantiation!" + bindgen can't handle this kind of template instantiation!" ); return None; } @@ -1803,7 +1784,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" if args.len() != num_expected_args { warn!( "Found a template with an unexpected number of template \ - arguments" + arguments" ); return None; } @@ -1845,9 +1826,9 @@ If you encounter an error missing from this list, please file an issue or a PR!" 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() } @@ -1864,19 +1845,14 @@ If you encounter an error missing from this list, please file an issue or a PR!" use clang_sys::{CXCursor_TypeAliasTemplateDecl, CXCursor_TypeRef}; debug!( "builtin_or_resolved_ty: {:?}, {:?}, {:?}", - ty, - location, - parent_id + 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 + id, decl, ty, location ); // If the declaration already exists, then either: // @@ -1908,7 +1884,8 @@ If you encounter an error missing from this list, please file an issue or a PR!" return None; } - return self.instantiate_template(with_id, id, ty, location) + return self + .instantiate_template(with_id, id, ty, location) .or_else(|| Some(id)); } @@ -1935,13 +1912,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" parent_id: Option, ty: &clang::Type, ) -> TypeId { - self.build_wrapper( - with_id, - wrapped_id, - parent_id, - ty, - ty.is_const(), - ) + self.build_wrapper(with_id, wrapped_id, parent_id, ty, ty.is_const()) } /// A wrapper over a type that adds a const qualifier explicitly. @@ -1955,11 +1926,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" ty: &clang::Type, ) -> TypeId { self.build_wrapper( - with_id, - wrapped_id, - parent_id, - ty, - /* is_const = */ true, + with_id, wrapped_id, parent_id, ty, /* is_const = */ true, ) } @@ -2001,12 +1968,8 @@ If you encounter an error missing from this list, please file an issue or a PR!" 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), @@ -2032,13 +1995,10 @@ If you encounter an error missing from this list, please file an issue or a PR!" CXType_Double => FloatKind::Double, CXType_LongDouble => FloatKind::LongDouble, CXType_Float128 => FloatKind::Float128, - _ => { - panic!( - "Non floating-type complex? {:?}, {:?}", - ty, - float_type, - ) - }, + _ => panic!( + "Non floating-type complex? {:?}, {:?}", + ty, float_type, + ), }; TypeKind::Complex(float_kind) } @@ -2050,8 +2010,13 @@ If you encounter an error missing from this list, please file an issue or a PR!" let layout = ty.fallible_layout(self).ok(); let ty = Type::new(Some(spelling), layout, type_kind, is_const); let id = self.next_item_id(); - let item = - Item::new(id, None, None, self.root_module.into(), ItemKind::Type(ty)); + let item = Item::new( + id, + None, + None, + self.root_module.into(), + ItemKind::Type(ty), + ); self.add_builtin_item(item); Some(id.as_type_id_unchecked()) } @@ -2067,7 +2032,9 @@ If you encounter an error missing from this list, please file an issue or a PR!" } /// Get the currently parsed macros. - pub fn parsed_macros(&self) -> &StdHashMap, cexpr::expr::EvalResult> { + pub fn parsed_macros( + &self, + ) -> &StdHashMap, cexpr::expr::EvalResult> { debug_assert!(!self.in_codegen_phase()); &self.parsed_macros } @@ -2096,15 +2063,14 @@ If you encounter an error missing from this list, please file an issue or a PR!" Entry::Vacant(entry) => { debug!( "Defining replacement for {:?} as {:?}", - name, - potential_ty + name, potential_ty ); entry.insert(potential_ty); } Entry::Occupied(occupied) => { warn!( "Replacement for {:?} already defined as {:?}; \ - ignoring duplicate replacement definition as {:?}", + ignoring duplicate replacement definition as {:?}", name, occupied.get(), potential_ty @@ -2115,7 +2081,11 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// Has the item with the given `name` and `id` been replaced by another /// type? - pub fn is_replaced_type>(&self, path: &[String], id: Id) -> bool { + pub fn is_replaced_type>( + &self, + path: &[String], + id: Id, + ) -> bool { let id = id.into(); match self.replacements.get(path) { Some(replaced_by) if *replaced_by != id => true, @@ -2185,7 +2155,8 @@ If you encounter an error missing from this list, please file an issue or a PR!" } name if found_namespace_keyword => { if module_name.is_none() { - module_name = Some(String::from_utf8_lossy(name).into_owned()); + module_name = + Some(String::from_utf8_lossy(name).into_owned()); } break; } @@ -2273,7 +2244,8 @@ If you encounter an error missing from this list, please file an issue or a PR!" let _t = self.timer("compute_whitelisted_and_codegen_items"); let roots = { - let mut roots = self.items() + let mut roots = self + .items() // Only consider roots that are enabled for codegen. .filter(|&(_, item)| item.is_enabled_for_codegen(self)) .filter(|&(_, item)| { @@ -2281,9 +2253,10 @@ If you encounter an error missing from this list, please file an issue or a PR!" // game. if self.options().whitelisted_types.is_empty() && self.options().whitelisted_functions.is_empty() && - self.options().whitelisted_vars.is_empty() { - return true; - } + self.options().whitelisted_vars.is_empty() + { + return true; + } // If this is a type that explicitly replaces another, we assume // you know what you're doing. @@ -2324,7 +2297,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" TypeKind::ResolvedTypeRef(..) | TypeKind::Opaque | TypeKind::TypeParam => return true, - _ => {}, + _ => {} }; } @@ -2338,7 +2311,6 @@ If you encounter an error missing from this list, please file an issue or a PR!" return false; } - let enum_ = match *ty.kind() { TypeKind::Enum(ref e) => e, _ => return false, @@ -2354,9 +2326,7 @@ If you encounter an error missing from this list, please file an issue or a PR!" prefix_path.push(variant.name().into()); let name = prefix_path[1..].join("::"); prefix_path.pop().unwrap(); - self.options() - .whitelisted_vars - .matches(&name) + self.options().whitelisted_vars.matches(&name) }) } } @@ -2386,14 +2356,16 @@ If you encounter an error missing from this list, please file an issue or a PR!" self, roots.clone(), whitelisted_items_predicate, - ).collect::(); + ) + .collect::(); let codegen_items = if self.options().whitelist_recursively { WhitelistedItemsTraversal::new( self, roots.clone(), traversal::codegen_edges, - ).collect::() + ) + .collect::() } else { whitelisted.clone() }; @@ -2439,7 +2411,11 @@ If you encounter an error missing from this list, please file an issue or a PR!" let _t = self.timer("compute_cannot_derive_debug"); assert!(self.cannot_derive_debug.is_none()); if self.options.derive_debug { - self.cannot_derive_debug = Some(as_cannot_derive_set(analyze::((self, DeriveTrait::Debug)))); + self.cannot_derive_debug = + Some(as_cannot_derive_set(analyze::(( + self, + DeriveTrait::Debug, + )))); } } @@ -2463,7 +2439,10 @@ If you encounter an error missing from this list, please file an issue or a PR!" assert!(self.cannot_derive_default.is_none()); if self.options.derive_default { self.cannot_derive_default = - Some(as_cannot_derive_set(analyze::((self, DeriveTrait::Default)))); + Some(as_cannot_derive_set(analyze::(( + self, + DeriveTrait::Default, + )))); } } @@ -2485,7 +2464,11 @@ If you encounter an error missing from this list, please file an issue or a PR!" fn compute_cannot_derive_copy(&mut self) { let _t = self.timer("compute_cannot_derive_copy"); assert!(self.cannot_derive_copy.is_none()); - self.cannot_derive_copy = Some(as_cannot_derive_set(analyze::((self, DeriveTrait::Copy)))); + self.cannot_derive_copy = + Some(as_cannot_derive_set(analyze::(( + self, + DeriveTrait::Copy, + )))); } /// Compute whether we can derive hash. @@ -2493,7 +2476,11 @@ If you encounter an error missing from this list, please file an issue or a PR!" let _t = self.timer("compute_cannot_derive_hash"); assert!(self.cannot_derive_hash.is_none()); if self.options.derive_hash { - self.cannot_derive_hash = Some(as_cannot_derive_set(analyze::((self, DeriveTrait::Hash)))); + self.cannot_derive_hash = + Some(as_cannot_derive_set(analyze::(( + self, + DeriveTrait::Hash, + )))); } } @@ -2515,13 +2502,23 @@ If you encounter an error missing from this list, please file an issue or a PR!" fn compute_cannot_derive_partialord_partialeq_or_eq(&mut self) { let _t = self.timer("compute_cannot_derive_partialord_partialeq_or_eq"); assert!(self.cannot_derive_partialeq_or_partialord.is_none()); - if self.options.derive_partialord || self.options.derive_partialeq || self.options.derive_eq { - self.cannot_derive_partialeq_or_partialord = Some(analyze::((self, DeriveTrait::PartialEqOrPartialOrd))); + if self.options.derive_partialord || + self.options.derive_partialeq || + self.options.derive_eq + { + self.cannot_derive_partialeq_or_partialord = + Some(analyze::(( + self, + DeriveTrait::PartialEqOrPartialOrd, + ))); } } /// Look up whether the item with `id` can derive `Partial{Eq,Ord}`. - pub fn lookup_can_derive_partialeq_or_partialord>(&self, id: Id) -> CanDerive { + pub fn lookup_can_derive_partialeq_or_partialord>( + &self, + id: Id, + ) -> CanDerive { let id = id.into(); assert!( self.in_codegen_phase(), @@ -2530,7 +2527,8 @@ If you encounter an error missing from this list, please file an issue or a PR!" // Look up the computed value for whether the item with `id` can // derive partialeq or not. - self.cannot_derive_partialeq_or_partialord.as_ref() + self.cannot_derive_partialeq_or_partialord + .as_ref() .unwrap() .get(&id) .cloned() @@ -2561,7 +2559,10 @@ If you encounter an error missing from this list, please file an issue or a PR!" } /// Look up whether the item with `id` has type parameter in array or not. - pub fn lookup_has_type_param_in_array>(&self, id: Id) -> bool { + pub fn lookup_has_type_param_in_array>( + &self, + id: Id, + ) -> bool { assert!( self.in_codegen_phase(), "We only compute has array when we enter codegen" @@ -2569,7 +2570,10 @@ If you encounter an error missing from this list, please file an issue or a PR!" // Look up the computed value for whether the item with `id` has // type parameter in array or not. - self.has_type_param_in_array.as_ref().unwrap().contains(&id.into()) + self.has_type_param_in_array + .as_ref() + .unwrap() + .contains(&id.into()) } /// Compute whether the type has float. @@ -2583,8 +2587,10 @@ If you encounter an error missing from this list, please file an issue or a PR!" /// Look up whether the item with `id` has array or not. pub fn lookup_has_float>(&self, id: Id) -> bool { - assert!(self.in_codegen_phase(), - "We only compute has float when we enter codegen"); + assert!( + self.in_codegen_phase(), + "We only compute has float when we enter codegen" + ); // Look up the computed value for whether the item with `id` has // float or not. @@ -2627,7 +2633,7 @@ impl ItemId { impl From for ItemResolver where - T: Into + T: Into, { fn from(id: T) -> ItemResolver { ItemResolver::new(id) @@ -2667,14 +2673,16 @@ impl ItemResolver { let ty_kind = item.as_type().map(|t| t.kind()); match ty_kind { Some(&TypeKind::ResolvedTypeRef(next_id)) - if self.through_type_refs => { + if self.through_type_refs => + { id = next_id.into(); } // 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 => { + if self.through_type_aliases => + { id = next_id.into(); } _ => return item, @@ -2696,10 +2704,7 @@ impl PartialType { /// Construct a new `PartialType`. pub fn new(decl: Cursor, id: ItemId) -> PartialType { // assert!(decl == decl.canonical()); - PartialType { - decl: decl, - id: id, - } + PartialType { decl: decl, id: id } } /// The cursor pointing to this partial type's declaration location. @@ -2715,10 +2720,7 @@ impl PartialType { } impl TemplateParameters for PartialType { - fn self_template_params( - &self, - _ctx: &BindgenContext, - ) -> Vec { + fn self_template_params(&self, _ctx: &BindgenContext) -> Vec { // Maybe at some point we will eagerly parse named types, but for now we // don't and this information is unavailable. vec![] diff --git a/src/ir/derive.rs b/src/ir/derive.rs index d434b0a0fe..254072ddcb 100644 --- a/src/ir/derive.rs +++ b/src/ir/derive.rs @@ -123,7 +123,7 @@ impl cmp::PartialOrd for CanDerive { (_, No) => cmp::Ordering::Less, (Manually, _) => cmp::Ordering::Greater, (_, Manually) => cmp::Ordering::Less, - _ => unreachable!() + _ => unreachable!(), }; Some(ordering) } diff --git a/src/ir/dot.rs b/src/ir/dot.rs index 6caca78153..d56902321d 100644 --- a/src/ir/dot.rs +++ b/src/ir/dot.rs @@ -60,11 +60,7 @@ where id.as_usize(), sub_id.as_usize(), edge_kind, - if is_whitelisted { - "black" - } else { - "gray" - } + if is_whitelisted { "black" } else { "gray" } ) { Ok(_) => {} Err(e) => err = Some(Err(e)), diff --git a/src/ir/enum_ty.rs b/src/ir/enum_ty.rs index be33ed4b76..442b5e2e37 100644 --- a/src/ir/enum_ty.rs +++ b/src/ir/enum_ty.rs @@ -1,8 +1,8 @@ //! Intermediate representation for C/C++ enumerations. +use super::super::codegen::EnumVariation; use super::context::{BindgenContext, TypeId}; use super::item::Item; -use super::super::codegen::EnumVariation; use super::ty::TypeKind; use clang; use ir::annotations::Annotations; @@ -38,10 +38,7 @@ pub struct Enum { impl Enum { /// Construct a new `Enum` with the given representation and variants. pub fn new(repr: Option, variants: Vec) -> Self { - Enum { - repr, - variants, - } + Enum { repr, variants } } /// Get this enumeration's representation. @@ -67,15 +64,15 @@ 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() { + 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) @@ -101,9 +98,11 @@ impl Enum { if let Some(val) = value { let name = cursor.spelling(); let annotations = Annotations::new(&cursor); - let custom_behavior = ctx.parse_callbacks() + let custom_behavior = ctx + .parse_callbacks() .and_then(|callbacks| { - callbacks.enum_variant_behavior(type_name, &name, val) + callbacks + .enum_variant_behavior(type_name, &name, val) }) .or_else(|| { let annotations = annotations.as_ref()?; @@ -116,12 +115,17 @@ impl Enum { } }); - let name = ctx.parse_callbacks() + let name = ctx + .parse_callbacks() .and_then(|callbacks| { callbacks.enum_variant_name(type_name, &name, val) }) .or_else(|| { - annotations.as_ref()?.use_instead_of()?.last().cloned() + annotations + .as_ref()? + .use_instead_of()? + .last() + .cloned() }) .unwrap_or(name); @@ -139,7 +143,12 @@ impl Enum { Ok(Enum::new(repr, variants)) } - fn is_matching_enum(&self, ctx: &BindgenContext, enums: &RegexSet, item: &Item) -> bool { + fn is_matching_enum( + &self, + ctx: &BindgenContext, + enums: &RegexSet, + item: &Item, + ) -> bool { let path = item.canonical_path(ctx); let enum_ty = item.expect_type(); @@ -156,18 +165,46 @@ impl Enum { } /// Returns the final representation of the enum. - pub fn computed_enum_variation(&self, ctx: &BindgenContext, item: &Item) -> EnumVariation { + pub fn computed_enum_variation( + &self, + ctx: &BindgenContext, + item: &Item, + ) -> EnumVariation { // ModuleConsts has higher precedence before Rust in order to avoid // problems with overlapping match patterns. - if self.is_matching_enum(ctx, &ctx.options().constified_enum_modules, item) { + if self.is_matching_enum( + ctx, + &ctx.options().constified_enum_modules, + item, + ) { EnumVariation::ModuleConsts - } else if self.is_matching_enum(ctx, &ctx.options().bitfield_enums, item) { + } else if self.is_matching_enum( + ctx, + &ctx.options().bitfield_enums, + item, + ) { EnumVariation::Bitfield - } else if self.is_matching_enum(ctx, &ctx.options().rustified_enums, item) { - EnumVariation::Rust { non_exhaustive: false } - } else if self.is_matching_enum(ctx, &ctx.options().rustified_non_exhaustive_enums, item) { - EnumVariation::Rust { non_exhaustive: true } - } else if self.is_matching_enum(ctx, &ctx.options().constified_enums, item) { + } else if self.is_matching_enum( + ctx, + &ctx.options().rustified_enums, + item, + ) { + EnumVariation::Rust { + non_exhaustive: false, + } + } else if self.is_matching_enum( + ctx, + &ctx.options().rustified_non_exhaustive_enums, + item, + ) { + EnumVariation::Rust { + non_exhaustive: true, + } + } else if self.is_matching_enum( + ctx, + &ctx.options().constified_enums, + item, + ) { EnumVariation::Consts } else { ctx.options().default_enum_style @@ -235,16 +272,14 @@ 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 b8af92130e..9ccf4e14c2 100644 --- a/src/ir/function.rs +++ b/src/ir/function.rs @@ -9,9 +9,9 @@ use super::ty::TypeKind; use clang; use clang_sys::{self, CXCallingConv}; use parse::{ClangItemParser, ClangSubItemParser, ParseError, ParseResult}; +use proc_macro2; use quote; use quote::TokenStreamExt; -use proc_macro2; use std::io; const RUST_DERIVE_FUNPTR_LIMIT: usize = 12; @@ -30,18 +30,18 @@ impl FunctionKind { // FIXME(emilio): Deduplicate logic with `ir::comp`. Some(match cursor.kind() { clang_sys::CXCursor_FunctionDecl => FunctionKind::Function, - clang_sys::CXCursor_Constructor => FunctionKind::Method( - MethodKind::Constructor, - ), - clang_sys::CXCursor_Destructor => FunctionKind::Method( - if cursor.method_is_virtual() { + clang_sys::CXCursor_Constructor => { + FunctionKind::Method(MethodKind::Constructor) + } + clang_sys::CXCursor_Destructor => { + FunctionKind::Method(if cursor.method_is_virtual() { MethodKind::VirtualDestructor { pure_virtual: cursor.method_is_pure_virtual(), } } else { MethodKind::Destructor - } - ), + }) + } clang_sys::CXCursor_CXXMethod => { if cursor.method_is_virtual() { FunctionKind::Method(MethodKind::Virtual { @@ -64,7 +64,7 @@ pub enum Linkage { /// Externally visible and can be linked against External, /// Not exposed externally. 'static inline' functions will have this kind of linkage - Internal + Internal, } /// A function declaration, with a signature, arguments, and argument names. @@ -100,7 +100,7 @@ impl Function { signature: TypeId, comment: Option, kind: FunctionKind, - linkage: Linkage + linkage: Linkage, ) -> Self { Function { name, @@ -136,7 +136,6 @@ impl Function { pub fn linkage(&self) -> Linkage { self.linkage } - } impl DotAttributes for Function { @@ -325,16 +324,16 @@ fn args_from_ty_and_cursor( cursor_args .map(Some) .chain(std::iter::repeat(None)) - .zip( - type_args - .map(Some) - .chain(std::iter::repeat(None)) - ) + .zip(type_args.map(Some).chain(std::iter::repeat(None))) .take_while(|(cur, ty)| cur.is_some() || ty.is_some()) .map(|(arg_cur, arg_ty)| { - let name = arg_cur - .map(|a| a.spelling()) - .and_then(|name| if name.is_empty() { None} else { Some(name) }); + let name = arg_cur.map(|a| a.spelling()).and_then(|name| { + if name.is_empty() { + None + } else { + Some(name) + } + }); let cursor = arg_cur.unwrap_or(*cursor); let ty = arg_ty.unwrap_or(cursor.cur_type()); @@ -404,7 +403,7 @@ impl FunctionSig { CXCursor_ObjCInstanceMethodDecl | CXCursor_ObjCClassMethodDecl => { args_from_ty_and_cursor(&ty, &cursor, ctx) - }, + } _ => { // For non-CXCursor_FunctionDecl, visiting the cursor's children // is the only reliable way to get parameter names. @@ -424,8 +423,7 @@ impl FunctionSig { } }; - let must_use = - ctx.options().enable_function_attribute_detection && + let must_use = ctx.options().enable_function_attribute_detection && cursor.has_simple_attr("warn_unused_result"); let is_method = kind == CXCursor_CXXMethod; let is_constructor = kind == CXCursor_Constructor; @@ -475,9 +473,9 @@ impl FunctionSig { let ty_ret_type = if kind == CXCursor_ObjCInstanceMethodDecl || kind == CXCursor_ObjCClassMethodDecl { - ty.ret_type().or_else(|| cursor.ret_type()).ok_or( - ParseError::Continue, - )? + ty.ret_type() + .or_else(|| cursor.ret_type()) + .ok_or(ParseError::Continue)? } else { ty.ret_type().ok_or(ParseError::Continue)? }; @@ -583,12 +581,11 @@ impl ClangSubItemParser for Function { let linkage = match linkage { CXLinkage_External | CXLinkage_UniqueExternal => Linkage::External, CXLinkage_Internal => Linkage::Internal, - _ => return Err(ParseError::Continue) + _ => return Err(ParseError::Continue), }; // Grab the signature using Item::from_ty. - let sig = - Item::from_ty(&cursor.cur_type(), cursor, None, context)?; + let sig = Item::from_ty(&cursor.cur_type(), cursor, None, context)?; let mut name = cursor.spelling(); assert!(!name.is_empty(), "Empty function name?"); @@ -610,7 +607,8 @@ impl ClangSubItemParser for Function { let mangled_name = cursor_mangling(context, &cursor); let comment = cursor.raw_comment(); - let function = Self::new(name, mangled_name, sig, comment, kind, linkage); + let function = + Self::new(name, mangled_name, sig, comment, kind, linkage); Ok(ParseResult::New(function, Some(cursor))) } } diff --git a/src/ir/int.rs b/src/ir/int.rs index dd3f0bef84..22838e897c 100644 --- a/src/ir/int.rs +++ b/src/ir/int.rs @@ -101,9 +101,7 @@ impl IntKind { Char { is_signed } => is_signed, - Custom { - is_signed, .. - } => is_signed, + Custom { is_signed, .. } => is_signed, } } @@ -113,14 +111,7 @@ 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 5a0bd8c988..7b4f3e8348 100644 --- a/src/ir/item.rs +++ b/src/ir/item.rs @@ -1,19 +1,20 @@ //! Bindgen's core intermediate representation type. +use super::super::codegen::{EnumVariation, CONSTIFIED_ENUM_MODULE_REPR_NAME}; use super::analysis::{HasVtable, HasVtableResult, Sizedness, SizednessResult}; use super::annotations::Annotations; use super::comment; use super::comp::MethodKind; use super::context::{BindgenContext, ItemId, PartialType, TypeId}; -use super::derive::{CanDeriveCopy, CanDeriveDebug, CanDeriveDefault, - CanDeriveHash, CanDerivePartialOrd, CanDeriveOrd, - CanDerivePartialEq, CanDeriveEq}; +use super::derive::{ + CanDeriveCopy, CanDeriveDebug, CanDeriveDefault, CanDeriveEq, + CanDeriveHash, CanDeriveOrd, CanDerivePartialEq, CanDerivePartialOrd, +}; 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, EnumVariation}; use super::template::{AsTemplateParam, TemplateParameters}; use super::traversal::{EdgeKind, Trace, Tracer}; use super::ty::{Type, TypeKind}; @@ -94,10 +95,7 @@ pub trait HasFloat { /// up to (but not including) the implicit root module. pub trait ItemAncestors { /// Get an iterable over this item's ancestors. - fn ancestors<'a>( - &self, - ctx: &'a BindgenContext, - ) -> ItemAncestorsIter<'a>; + fn ancestors<'a>(&self, ctx: &'a BindgenContext) -> ItemAncestorsIter<'a>; } cfg_if! { @@ -158,7 +156,8 @@ impl<'a> Iterator for ItemAncestorsIter<'a> { impl AsTemplateParam for T where - T: Copy + Into { + T: Copy + Into, +{ type Extra = (); fn as_template_param( @@ -201,7 +200,7 @@ impl AsTemplateParam for ItemKind { impl ItemCanonicalName for T where - T: Copy + Into + T: Copy + Into, { fn canonical_name(&self, ctx: &BindgenContext) -> String { debug_assert!( @@ -213,8 +212,8 @@ where } impl ItemCanonicalPath for T - where - T: Copy + Into +where + T: Copy + Into, { fn namespace_aware_canonical_path( &self, @@ -238,28 +237,22 @@ impl ItemCanonicalPath for T impl ItemAncestors for T where - T: Copy + Into + T: Copy + Into, { - fn ancestors<'a>( - &self, - ctx: &'a BindgenContext, - ) -> ItemAncestorsIter<'a> { + fn ancestors<'a>(&self, ctx: &'a BindgenContext) -> ItemAncestorsIter<'a> { ItemAncestorsIter::new(ctx, *self) } } impl ItemAncestors for Item { - fn ancestors<'a>( - &self, - ctx: &'a BindgenContext, - ) -> ItemAncestorsIter<'a> { + fn ancestors<'a>(&self, ctx: &'a BindgenContext) -> ItemAncestorsIter<'a> { self.id().ancestors(ctx) } } impl Trace for Id where - Id: Copy + Into + Id: Copy + Into, { type Extra = (); @@ -495,10 +488,10 @@ impl Item { ctx.options().conservative_inline_namespaces }) }) - .count() + 1 + .count() + + 1 } - /// Get this `Item`'s comment, if it has any, already preprocessed and with /// the right indentation. pub fn comment(&self, ctx: &BindgenContext) -> Option { @@ -567,7 +560,8 @@ impl Item { pub fn is_toplevel(&self, ctx: &BindgenContext) -> bool { // FIXME: Workaround for some types falling behind when parsing weird // stl classes, for example. - if ctx.options().enable_cxx_namespaces && self.kind().is_module() && + if ctx.options().enable_cxx_namespaces && + self.kind().is_module() && self.id() != ctx.root_module() { return false; @@ -583,7 +577,7 @@ 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; } @@ -638,18 +632,17 @@ impl Item { let path = self.path_for_whitelisting(ctx); let name = path[1..].join("::"); ctx.options().blacklisted_items.matches(&name) || - match self.kind { - ItemKind::Type(..) => { - ctx.options().blacklisted_types.matches(&name) || - ctx.is_replaced_type(&path, self.id) - } - ItemKind::Function(..) => { - ctx.options().blacklisted_functions.matches(&name) + match self.kind { + ItemKind::Type(..) => { + ctx.options().blacklisted_types.matches(&name) || + ctx.is_replaced_type(&path, self.id) + } + ItemKind::Function(..) => { + ctx.options().blacklisted_functions.matches(&name) + } + // TODO: Add constant / namespace blacklisting? + ItemKind::Var(..) | ItemKind::Module(..) => false, } - // TODO: Add constant / namespace blacklisting? - ItemKind::Var(..) | - ItemKind::Module(..) => false, - } } /// Is this a reference to another type? @@ -666,10 +659,7 @@ impl Item { } /// Take out item NameOptions - pub fn name<'a>( - &'a self, - ctx: &'a BindgenContext, - ) -> NameOptions<'a> { + pub fn name<'a>(&'a self, ctx: &'a BindgenContext) -> NameOptions<'a> { NameOptions::new(self, ctx) } @@ -687,17 +677,15 @@ impl Item { } match *item.kind() { - ItemKind::Type(ref ty) => { - match *ty.kind() { - TypeKind::ResolvedTypeRef(inner) => { - item = ctx.resolve_item(inner); - } - TypeKind::TemplateInstantiation(ref inst) => { - item = ctx.resolve_item(inst.template_definition()); - } - _ => return item.id(), + ItemKind::Type(ref ty) => match *ty.kind() { + TypeKind::ResolvedTypeRef(inner) => { + item = ctx.resolve_item(inner); } - } + TypeKind::TemplateInstantiation(ref inst) => { + item = ctx.resolve_item(inst.template_definition()); + } + _ => return item.id(), + }, _ => return item.id(), } } @@ -752,7 +740,8 @@ impl Item { if let TypeKind::Comp(ref ci) = *ty.kind() { // All the constructors have the same name, so no need to // resolve and check. - return ci.constructors() + return ci + .constructors() .iter() .position(|c| *c == self.id()) .or_else(|| { @@ -937,7 +926,8 @@ impl Item { match *type_.kind() { TypeKind::Enum(ref enum_) => { - enum_.computed_enum_variation(ctx, self) == EnumVariation::ModuleConsts + enum_.computed_enum_variation(ctx, self) == + EnumVariation::ModuleConsts } TypeKind::Alias(inner_id) => { // TODO(emilio): Make this "hop through type aliases that aren't @@ -962,17 +952,21 @@ impl Item { ItemKind::Module(..) => true, ItemKind::Var(_) => cc.vars(), ItemKind::Type(_) => cc.types(), - ItemKind::Function(ref f) => { - match f.kind() { - FunctionKind::Function => cc.functions(), - FunctionKind::Method(MethodKind::Constructor) => cc.constructors(), - FunctionKind::Method(MethodKind::Destructor) | - FunctionKind::Method(MethodKind::VirtualDestructor { .. }) => cc.destructors(), - FunctionKind::Method(MethodKind::Static) | - FunctionKind::Method(MethodKind::Normal) | - FunctionKind::Method(MethodKind::Virtual { .. }) => cc.methods(), + ItemKind::Function(ref f) => match f.kind() { + FunctionKind::Function => cc.functions(), + FunctionKind::Method(MethodKind::Constructor) => { + cc.constructors() } - } + FunctionKind::Method(MethodKind::Destructor) | + FunctionKind::Method(MethodKind::VirtualDestructor { + .. + }) => cc.destructors(), + FunctionKind::Method(MethodKind::Static) | + FunctionKind::Method(MethodKind::Normal) | + FunctionKind::Method(MethodKind::Virtual { .. }) => { + cc.methods() + } + }, } } @@ -982,7 +976,11 @@ impl Item { self.compute_path(ctx, UserMangled::No) } - fn compute_path(&self, ctx: &BindgenContext, mangled: UserMangled) -> Vec { + fn compute_path( + &self, + ctx: &BindgenContext, + mangled: UserMangled, + ) -> Vec { if let Some(path) = self.annotations().use_instead_of() { let mut ret = vec![ctx.resolve_item(ctx.root_module()).name(ctx).get()]; @@ -1017,7 +1015,7 @@ impl Item { impl IsOpaque for T where - T: Copy + Into + T: Copy + Into, { type Extra = (); @@ -1046,7 +1044,7 @@ impl IsOpaque for Item { impl HasVtable for T where - T: Copy + Into + T: Copy + Into, { fn has_vtable(&self, ctx: &BindgenContext) -> bool { let id: ItemId = (*self).into(); @@ -1079,7 +1077,7 @@ impl HasVtable for Item { impl Sizedness for T where - T: Copy + Into + T: Copy + Into, { fn sizedness(&self, ctx: &BindgenContext) -> SizednessResult { let id: ItemId = (*self).into(); @@ -1096,7 +1094,7 @@ impl Sizedness for Item { impl HasTypeParamInArray for T where - T: Copy + Into + T: Copy + Into, { fn has_type_param_in_array(&self, ctx: &BindgenContext) -> bool { debug_assert!( @@ -1119,19 +1117,23 @@ impl HasTypeParamInArray for Item { impl HasFloat for T where - T: Copy + Into + T: Copy + Into, { fn has_float(&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_has_float(*self) } } impl HasFloat for Item { fn has_float(&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_has_float(self.id()) } } @@ -1166,40 +1168,30 @@ impl DotAttributes for Item { impl TemplateParameters for T where - T: Copy + Into + T: Copy + Into, { - fn self_template_params( - &self, - ctx: &BindgenContext, - ) -> Vec { - ctx.resolve_item_fallible(*self).map_or(vec![], |item| { - item.self_template_params(ctx) - }) + fn self_template_params(&self, ctx: &BindgenContext) -> Vec { + ctx.resolve_item_fallible(*self) + .map_or(vec![], |item| item.self_template_params(ctx)) } } impl TemplateParameters for Item { - fn self_template_params( - &self, - ctx: &BindgenContext, - ) -> Vec { + fn self_template_params(&self, ctx: &BindgenContext) -> Vec { self.kind.self_template_params(ctx) } } impl TemplateParameters for ItemKind { - fn self_template_params( - &self, - ctx: &BindgenContext, - ) -> Vec { + fn self_template_params(&self, ctx: &BindgenContext) -> Vec { match *self { ItemKind::Type(ref ty) => ty.self_template_params(ctx), // If we start emitting bindings to explicitly instantiated // functions, then we'll need to check ItemKind::Function for // template params. - ItemKind::Function(_) | - ItemKind::Module(_) | - ItemKind::Var(_) => vec![], + ItemKind::Function(_) | ItemKind::Module(_) | ItemKind::Var(_) => { + vec![] + } } } } @@ -1256,14 +1248,13 @@ impl ClangItemParser for Item { id.as_type_id_unchecked() } - fn parse( cursor: clang::Cursor, parent_id: Option, ctx: &mut BindgenContext, ) -> Result { - use ir::var::Var; use clang_sys::*; + use ir::var::Var; if !cursor.is_valid() { return Err(ParseError::Continue); @@ -1281,20 +1272,28 @@ impl ClangItemParser for Item { Ok(ParseResult::New(item, declaration)) => { let id = ctx.next_item_id(); - ctx.add_item(Item::new(id, comment, annotations, - relevant_parent_id, - ItemKind::$what(item)), - declaration, - Some(cursor)); + ctx.add_item( + Item::new( + id, + comment, + annotations, + relevant_parent_id, + ItemKind::$what(item), + ), + declaration, + Some(cursor), + ); return Ok(id); } Ok(ParseResult::AlreadyResolved(id)) => { return Ok(id); } - Err(ParseError::Recurse) => return Err(ParseError::Recurse), - Err(ParseError::Continue) => {}, + Err(ParseError::Recurse) => { + return Err(ParseError::Recurse) + } + Err(ParseError::Continue) => {} } - } + }; } try_parse!(Module); @@ -1315,7 +1314,6 @@ impl ClangItemParser for Item { let definition = cursor.definition(); let applicable_cursor = definition.unwrap_or(cursor); - let relevant_parent_id = match definition { Some(definition) => { if definition != cursor { @@ -1325,7 +1323,8 @@ impl ClangItemParser for Item { cursor, parent_id, ctx, - ).into()); + ) + .into()); } ctx.known_semantic_parent(definition) .or(parent_id) @@ -1412,10 +1411,7 @@ impl ClangItemParser for Item { ) -> TypeId { debug!( "from_ty_or_ref_with_id: {:?} {:?}, {:?}, {:?}", - potential_id, - ty, - location, - parent_id + potential_id, ty, location, parent_id ); if ctx.collected_typerefs() { @@ -1426,9 +1422,8 @@ impl ClangItemParser for Item { location, parent_id, ctx, - ).unwrap_or_else( - |_| Item::new_opaque_type(potential_id, &ty, ctx), - ); + ) + .unwrap_or_else(|_| Item::new_opaque_type(potential_id, &ty, ctx)); } if let Some(ty) = ctx.builtin_or_resolved_ty( @@ -1436,8 +1431,7 @@ impl ClangItemParser for Item { parent_id, &ty, Some(location), - ) - { + ) { debug!("{:?} already resolved: {:?}", ty, location); return ty; } @@ -1491,17 +1485,14 @@ impl ClangItemParser for Item { debug!( "Item::from_ty_with_id: {:?}\n\ - \tty = {:?},\n\ - \tlocation = {:?}", - id, - ty, - location + \tty = {:?},\n\ + \tlocation = {:?}", + id, ty, location ); if ty.kind() == clang_sys::CXType_Unexposed || location.cur_type().kind() == clang_sys::CXType_Unexposed { - if ty.is_associated_type() || location.cur_type().is_associated_type() { @@ -1528,12 +1519,8 @@ 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); } @@ -1550,11 +1537,10 @@ 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); // Unchecked because we haven't finished this type yet. @@ -1571,7 +1557,9 @@ impl ClangItemParser for Item { let result = Type::from_clang_ty(id, ty, location, parent_id, ctx); let relevant_parent_id = parent_id.unwrap_or(current_module); let ret = match result { - Ok(ParseResult::AlreadyResolved(ty)) => Ok(ty.as_type_id_unchecked()), + Ok(ParseResult::AlreadyResolved(ty)) => { + Ok(ty.as_type_id_unchecked()) + } Ok(ParseResult::New(item, declaration)) => { ctx.add_item( Item::new( @@ -1619,7 +1607,7 @@ impl ClangItemParser for Item { if let Err(ParseError::Recurse) = result { warn!( "Unknown type, assuming named template type: \ - id = {:?}; spelling = {}", + id = {:?}; spelling = {}", id, ty.spelling() ); @@ -1652,9 +1640,9 @@ impl ClangItemParser for Item { debug!( "Item::type_param:\n\ - \twith_id = {:?},\n\ - \tty = {} {:?},\n\ - \tlocation: {:?}", + \twith_id = {:?},\n\ + \tty = {} {:?},\n\ + \tlocation: {:?}", with_id, ty.spelling(), ty, @@ -1735,50 +1723,51 @@ 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, + 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 } - } else { - // Situation (3) - let mut definition = None; + _ => 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; - } - _ => {} + 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 @@ -1789,9 +1778,12 @@ impl ClangItemParser for Item { 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); } diff --git a/src/ir/item_kind.rs b/src/ir/item_kind.rs index 1e755e242a..4a12fef40d 100644 --- a/src/ir/item_kind.rs +++ b/src/ir/item_kind.rs @@ -135,11 +135,7 @@ impl DotAttributes for ItemKind { where W: io::Write, { - writeln!( - out, - "kind{}", - self.kind_name() - )?; + 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 8438d2c46f..1c61b2ad2f 100644 --- a/src/ir/layout.rs +++ b/src/ir/layout.rs @@ -1,9 +1,9 @@ //! Intermediate representation for the physical layout of some type. use super::derive::CanDerive; -use super::ty::{RUST_DERIVE_IN_ARRAY_LIMIT, Type, TypeKind}; -use ir::context::BindgenContext; +use super::ty::{Type, TypeKind, RUST_DERIVE_IN_ARRAY_LIMIT}; use clang; +use ir::context::BindgenContext; use std::cmp; /// A type that represents the struct layout of a type. @@ -107,7 +107,10 @@ impl Opaque { /// Return the known rust type we should use to create a correctly-aligned /// field with this layout. - pub fn known_rust_type_for_array(&self,ctx: &BindgenContext) -> Option<&'static str> { + pub fn known_rust_type_for_array( + &self, + ctx: &BindgenContext, + ) -> Option<&'static str> { Layout::known_type_for_size(ctx, self.0.align) } @@ -124,10 +127,14 @@ impl Opaque { /// Return `true` if this opaque layout's array size will fit within the /// maximum number of array elements that Rust allows deriving traits /// with. Return `false` otherwise. - pub fn array_size_within_derive_limit(&self, ctx: &BindgenContext) -> CanDerive { - if self.array_size(ctx).map_or(false, |size| { - size <= RUST_DERIVE_IN_ARRAY_LIMIT - }) { + pub fn array_size_within_derive_limit( + &self, + ctx: &BindgenContext, + ) -> CanDerive { + if self + .array_size(ctx) + .map_or(false, |size| size <= RUST_DERIVE_IN_ARRAY_LIMIT) + { CanDerive::Yes } else { CanDerive::Manually diff --git a/src/ir/mod.rs b/src/ir/mod.rs index 93894f94db..8f6a2dac88 100644 --- a/src/ir/mod.rs +++ b/src/ir/mod.rs @@ -3,10 +3,10 @@ //! Parsing C/C++ generates the IR, while code generation outputs Rust code from //! the IR. -pub mod annotations; pub mod analysis; -pub mod comp; +pub mod annotations; pub mod comment; +pub mod comp; pub mod context; pub mod derive; pub mod dot; @@ -17,8 +17,8 @@ pub mod item; pub mod item_kind; pub mod layout; pub mod module; +pub mod objc; pub mod template; pub mod traversal; pub mod ty; pub mod var; -pub mod objc; diff --git a/src/ir/module.rs b/src/ir/module.rs index af46d4acae..7a22106617 100644 --- a/src/ir/module.rs +++ b/src/ir/module.rs @@ -82,9 +82,9 @@ impl ClangSubItemParser for Module { CXCursor_Namespace => { let module_id = ctx.module(cursor); ctx.with_module(module_id, |ctx| { - cursor.visit( - |cursor| parse_one(ctx, cursor, Some(module_id.into())), - ) + cursor.visit(|cursor| { + parse_one(ctx, cursor, Some(module_id.into())) + }) }); Ok(ParseResult::AlreadyResolved(module_id.into())) diff --git a/src/ir/objc.rs b/src/ir/objc.rs index c7801df101..0b75e55ab4 100644 --- a/src/ir/objc.rs +++ b/src/ir/objc.rs @@ -12,7 +12,7 @@ use clang_sys::CXCursor_ObjCClassRef; use clang_sys::CXCursor_ObjCInstanceMethodDecl; use clang_sys::CXCursor_ObjCProtocolDecl; use clang_sys::CXCursor_ObjCProtocolRef; -use proc_macro2::{TokenStream, Ident, Span}; +use proc_macro2::{Ident, Span, TokenStream}; /// Objective C interface as used in TypeKind /// @@ -212,7 +212,8 @@ impl ObjCMethod { /// Formats the method call pub fn format_method_call(&self, args: &[TokenStream]) -> TokenStream { - let split_name: Vec<_> = self.name + let split_name: Vec<_> = self + .name .split(':') .filter(|p| !p.is_empty()) .map(|name| Ident::new(name, Span::call_site())) @@ -242,7 +243,7 @@ impl ObjCMethod { let name_and_sig: Vec<&str> = arg.split(' ').collect(); let name = name_and_sig[0]; args_without_types.push(Ident::new(name, Span::call_site())) - }; + } let args = split_name .into_iter() diff --git a/src/ir/template.rs b/src/ir/template.rs index 14deb6c545..30c578ced3 100644 --- a/src/ir/template.rs +++ b/src/ir/template.rs @@ -99,7 +99,7 @@ use parse::ClangItemParser; /// ... |Wtf | ... | [T] | /// ... |Qux | ... | [] | /// ----+------+-----+----------------------+ -pub trait TemplateParameters : Sized { +pub trait TemplateParameters: Sized { /// Get the set of `ItemId`s that make up this template declaration's free /// template parameters. /// @@ -135,9 +135,11 @@ pub trait TemplateParameters : Sized { Self: ItemAncestors, { let ancestors: Vec<_> = self.ancestors(ctx).collect(); - ancestors.into_iter().rev().flat_map(|id| { - id.self_template_params(ctx).into_iter() - }).collect() + ancestors + .into_iter() + .rev() + .flat_map(|id| id.self_template_params(ctx).into_iter()) + .collect() } /// Get only the set of template parameters that this item uses. This is a @@ -153,10 +155,11 @@ pub trait TemplateParameters : Sized { ); let id = *self.as_ref(); - ctx.resolve_item(id).all_template_params(ctx) - .into_iter() - .filter(|p| ctx.uses_template_parameter(id, *p)) - .collect() + ctx.resolve_item(id) + .all_template_params(ctx) + .into_iter() + .filter(|p| ctx.uses_template_parameter(id, *p)) + .collect() } } @@ -221,34 +224,33 @@ impl TemplateInstantiation { ) -> Option { use clang_sys::*; - let template_args = ty.template_args() - .map_or(vec![], |args| { - match ty.canonical_type().template_args() { - Some(canonical_args) => { - let arg_count = args.len(); - args.chain(canonical_args.skip(arg_count)) - .filter(|t| t.kind() != CXType_Invalid) - .map(|t| { - Item::from_ty_or_ref(t, t.declaration(), None, ctx) - }).collect() - } - None => { - args.filter(|t| t.kind() != CXType_Invalid) - .map(|t| { - Item::from_ty_or_ref(t, t.declaration(), None, ctx) - }).collect() - } - } - }); + let template_args = ty.template_args().map_or(vec![], |args| match ty + .canonical_type() + .template_args() + { + Some(canonical_args) => { + let arg_count = args.len(); + args.chain(canonical_args.skip(arg_count)) + .filter(|t| t.kind() != CXType_Invalid) + .map(|t| { + Item::from_ty_or_ref(t, t.declaration(), None, ctx) + }) + .collect() + } + None => args + .filter(|t| t.kind() != CXType_Invalid) + .map(|t| Item::from_ty_or_ref(t, t.declaration(), None, ctx)) + .collect(), + }); let declaration = ty.declaration(); - let definition = - if declaration.kind() == CXCursor_TypeAliasTemplateDecl { - Some(declaration) - } else { - declaration.specialized().or_else(|| { - let mut template_ref = None; - ty.declaration().visit(|child| { + 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; @@ -261,9 +263,9 @@ impl TemplateInstantiation { CXChildVisit_Recurse }); - template_ref.and_then(|cur| cur.referenced()) - }) - }; + template_ref.and_then(|cur| cur.referenced()) + }) + }; let definition = match definition { Some(def) => def, @@ -271,7 +273,7 @@ impl TemplateInstantiation { if !ty.declaration().is_builtin() { warn!( "Could not find template definition for template \ - instantiation" + instantiation" ); } return None; @@ -305,7 +307,8 @@ impl IsOpaque for TemplateInstantiation { // arguments properly. let mut path = item.canonical_path(ctx); - let args: Vec<_> = self.template_arguments() + let args: Vec<_> = self + .template_arguments() .iter() .map(|arg| { let arg_path = arg.canonical_path(ctx); @@ -330,7 +333,8 @@ impl Trace for TemplateInstantiation { where T: Tracer, { - tracer.visit_kind(self.definition.into(), EdgeKind::TemplateDeclaration); + tracer + .visit_kind(self.definition.into(), EdgeKind::TemplateDeclaration); for arg in self.template_arguments() { tracer.visit_kind(arg.into(), EdgeKind::TemplateArgument); } diff --git a/src/ir/traversal.rs b/src/ir/traversal.rs index cb4c6f16a8..e4a447032b 100644 --- a/src/ir/traversal.rs +++ b/src/ir/traversal.rs @@ -20,10 +20,7 @@ pub struct Edge { impl Edge { /// Construct a new edge whose referent is `to` and is of the given `kind`. pub fn new(to: ItemId, kind: EdgeKind) -> Edge { - Edge { - to, - kind, - } + Edge { to, kind } } } @@ -236,7 +233,7 @@ pub fn codegen_edges(ctx: &BindgenContext, edge: Edge) -> bool { EdgeKind::InnerVar => cc.vars(), EdgeKind::Method => cc.methods(), EdgeKind::Constructor => cc.constructors(), - EdgeKind::Destructor => cc.destructors() + EdgeKind::Destructor => cc.destructors(), } } @@ -269,10 +266,7 @@ impl<'ctx> TraversalStorage<'ctx> for ItemSet { /// each item. This is useful for providing debug assertions with meaningful /// diagnostic messages about dangling items. #[derive(Debug)] -pub struct Paths<'ctx>( - BTreeMap, - &'ctx BindgenContext -); +pub struct Paths<'ctx>(BTreeMap, &'ctx BindgenContext); impl<'ctx> TraversalStorage<'ctx> for Paths<'ctx> { fn new(ctx: &'ctx BindgenContext) -> Self { @@ -289,7 +283,7 @@ impl<'ctx> TraversalStorage<'ctx> for Paths<'ctx> { loop { let predecessor = *self.0.get(¤t).expect( "We know we found this item id, so it must have a \ - predecessor", + predecessor", ); if predecessor == current { break; @@ -300,8 +294,7 @@ impl<'ctx> TraversalStorage<'ctx> for Paths<'ctx> { path.reverse(); panic!( "Found reference to dangling id = {:?}\nvia path = {:?}", - item, - path + item, path ); } @@ -495,13 +488,12 @@ where /// /// See `BindgenContext::assert_no_dangling_item_traversal` for more /// information. -pub type AssertNoDanglingItemsTraversal<'ctx> = - ItemTraversal< - 'ctx, - Paths<'ctx>, - VecDeque, - for<'a> fn(&'a BindgenContext, Edge) -> bool, - >; +pub type AssertNoDanglingItemsTraversal<'ctx> = ItemTraversal< + 'ctx, + Paths<'ctx>, + 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 625b5f8741..0144bdbad1 100644 --- a/src/ir/ty.rs +++ b/src/ir/ty.rs @@ -9,8 +9,9 @@ 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}; @@ -235,7 +236,11 @@ impl Type { pub fn is_incomplete_array(&self, ctx: &BindgenContext) -> Option { match self.kind { TypeKind::Array(item, len) => { - if len == 0 { Some(item.into()) } else { None } + if len == 0 { + Some(item.into()) + } else { + None + } } TypeKind::ResolvedTypeRef(inner) => { ctx.resolve_type(inner).is_incomplete_array(ctx) @@ -249,20 +254,15 @@ impl Type { self.layout.or_else(|| { match self.kind { TypeKind::Comp(ref ci) => ci.layout(ctx), - TypeKind::Array(inner, length) if length == 0 => { - Some(Layout::new( - 0, - ctx.resolve_type(inner).layout(ctx)?.align, - )) - } + TypeKind::Array(inner, length) if length == 0 => Some( + Layout::new(0, ctx.resolve_type(inner).layout(ctx)?.align), + ), // FIXME(emilio): This is a hack for anonymous union templates. // Use the actual pointer size! - TypeKind::Pointer(..) => { - Some(Layout::new( - ctx.target_pointer_size(), - ctx.target_pointer_size(), - )) - } + TypeKind::Pointer(..) => Some(Layout::new( + ctx.target_pointer_size(), + ctx.target_pointer_size(), + )), TypeKind::ResolvedTypeRef(inner) => { ctx.resolve_type(inner).layout(ctx) } @@ -301,8 +301,12 @@ impl Type { ctx: &BindgenContext, ) -> Option> { let name_info = match *self.kind() { - TypeKind::Pointer(inner) => Some((inner.into(), Cow::Borrowed("ptr"))), - TypeKind::Reference(inner) => Some((inner.into(), Cow::Borrowed("ref"))), + TypeKind::Pointer(inner) => { + Some((inner.into(), Cow::Borrowed("ptr"))) + } + TypeKind::Reference(inner) => { + Some((inner.into(), Cow::Borrowed("ref"))) + } TypeKind::Array(inner, length) => { Some((inner, format!("array{}", length).into())) } @@ -323,9 +327,8 @@ impl Type { &'tr self, ctx: &'tr BindgenContext, ) -> &'tr Type { - self.safe_canonical_type(ctx).expect( - "Should have been resolved after parsing!", - ) + self.safe_canonical_type(ctx) + .expect("Should have been resolved after parsing!") } /// Returns the canonical type of this type, that is, the "inner type". @@ -362,10 +365,9 @@ impl Type { TypeKind::TemplateAlias(inner, _) => { ctx.resolve_type(inner).safe_canonical_type(ctx) } - TypeKind::TemplateInstantiation(ref inst) => { - ctx.resolve_type(inst.template_definition()) - .safe_canonical_type(ctx) - } + TypeKind::TemplateInstantiation(ref inst) => ctx + .resolve_type(inst.template_definition()) + .safe_canonical_type(ctx), TypeKind::UnresolvedTypeRef(..) => None, } @@ -445,8 +447,7 @@ impl DotAttributes for Type { out, "size{} align{}", - layout.size, - layout.align + layout.size, layout.align )?; if layout.packed { writeln!(out, "packedtrue")?; @@ -470,7 +471,11 @@ impl DotAttributes for TypeKind { where W: io::Write, { - writeln!(out, "type kind{}", self.kind_name())?; + writeln!( + out, + "type kind{}", + self.kind_name() + )?; if let TypeKind::Comp(ref comp) = *self { comp.dot_attributes(ctx, out)?; @@ -559,19 +564,13 @@ fn is_invalid_type_param_empty_name() { } impl TemplateParameters for Type { - fn self_template_params( - &self, - ctx: &BindgenContext, - ) -> Vec { + fn self_template_params(&self, ctx: &BindgenContext) -> Vec { self.kind.self_template_params(ctx) } } impl TemplateParameters for TypeKind { - fn self_template_params( - &self, - ctx: &BindgenContext, - ) -> Vec { + fn self_template_params(&self, ctx: &BindgenContext) -> Vec { match *self { TypeKind::ResolvedTypeRef(id) => { ctx.resolve_type(id).self_template_params(ctx) @@ -687,7 +686,7 @@ pub enum TypeKind { clang::Type, clang::Cursor, /* parent_id */ - Option + Option, ), /// An indirection to another type. @@ -742,9 +741,7 @@ impl Type { debug!( "from_clang_ty: {:?}, ty: {:?}, loc: {:?}", - potential_id, - ty, - location + potential_id, ty, location ); debug!("currently_parsed_types: {:?}", ctx.currently_parsed_types()); @@ -753,8 +750,9 @@ impl Type { // Parse objc protocols as if they were interfaces let mut ty_kind = ty.kind(); match location.kind() { - CXCursor_ObjCProtocolDecl | - CXCursor_ObjCCategoryDecl => ty_kind = CXType_ObjCInterface, + CXCursor_ObjCProtocolDecl | CXCursor_ObjCCategoryDecl => { + ty_kind = CXType_ObjCInterface + } _ => {} } @@ -764,10 +762,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 { @@ -775,19 +773,19 @@ impl Type { // To keep it simple, just name them ids name = "id".to_owned(); } - } if location.kind() == CXCursor_ClassTemplatePartialSpecialization { // Sorry! (Not sorry) 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, ctx), None), + support partial template specialization! Constructing \ + opaque type instead." ); + return Ok(ParseResult::New( + Opaque::from_clang_ty(&canonical_ty, ctx), + None, + )); } let kind = if location.kind() == CXCursor_TemplateRef || @@ -800,7 +798,8 @@ impl Type { } } else { match ty_kind { - CXType_Unexposed if *ty != canonical_ty && + CXType_Unexposed + if *ty != canonical_ty && canonical_ty.kind() != CXType_Invalid && ty.ret_type().is_none() && // Sometime clang desugars some types more than @@ -815,13 +814,16 @@ impl Type { // => { ... } // // etc. - !canonical_ty.spelling().contains("type-parameter") => { + !canonical_ty.spelling().contains("type-parameter") => + { debug!("Looking for canonical type: {:?}", canonical_ty); - return Self::from_clang_ty(potential_id, - &canonical_ty, - location, - parent_id, - ctx); + return Self::from_clang_ty( + potential_id, + &canonical_ty, + location, + parent_id, + ctx, + ); } CXType_Unexposed | CXType_Invalid => { // For some reason Clang doesn't give us any hint in some @@ -837,23 +839,21 @@ impl Type { } else if ty.is_fully_instantiated_template() { debug!( "Template specialization: {:?}, {:?} {:?}", - ty, - location, - canonical_ty + ty, location, canonical_ty ); let complex = CompInfo::from_ty( potential_id, ty, Some(location), ctx, - ).expect("C'mon"); + ) + .expect("C'mon"); TypeKind::Comp(complex) } else { match location.kind() { CXCursor_CXXBaseSpecifier | CXCursor_ClassTemplate => { - if location.kind() == - CXCursor_CXXBaseSpecifier + if location.kind() == CXCursor_CXXBaseSpecifier { // In the case we're parsing a base specifier // inside an unexposed or invalid type, it means @@ -896,8 +896,7 @@ impl Type { // [4]: inherit-namespaced.hpp if location.spelling().chars().all(|c| { c.is_alphanumeric() || c == '_' - }) - { + }) { return Err(ParseError::Recurse); } } else { @@ -915,13 +914,14 @@ impl Type { Err(_) => { warn!( "Could not create complex type \ - from class template or base \ - specifier, using opaque blob" - ); - let opaque = Opaque::from_clang_ty(ty, ctx); - return Ok( - ParseResult::New(opaque, None), + from class template or base \ + specifier, using opaque blob" ); + let opaque = + Opaque::from_clang_ty(ty, ctx); + return Ok(ParseResult::New( + opaque, None, + )); } } } @@ -944,7 +944,8 @@ impl Type { name = current.spelling(); - let inner_ty = cur.typedef_type() + let inner_ty = cur + .typedef_type() .expect("Not valid Type?"); inner = Ok(Item::from_ty_or_ref( inner_ty, @@ -954,13 +955,14 @@ impl Type { )); } CXCursor_TemplateTypeParameter => { - let param = - Item::type_param(None, - cur, - ctx) - .expect("Item::type_param shouldn't \ - ever fail if we are looking \ - at a TemplateTypeParameter"); + let param = Item::type_param( + None, cur, ctx, + ) + .expect( + "Item::type_param shouldn't \ + ever fail if we are looking \ + at a TemplateTypeParameter", + ); args.push(param); } _ => {} @@ -973,7 +975,7 @@ impl Type { Err(..) => { error!( "Failed to parse template alias \ - {:?}", + {:?}", location ); return Err(ParseError::Continue); @@ -1009,10 +1011,8 @@ impl Type { debug!( "TypeRef: location = {:?}; referenced = \ - {:?}; referenced_ty = {:?}", - location, - referenced, - referenced_ty + {:?}; referenced_ty = {:?}", + location, referenced, referenced_ty ); let id = Item::from_ty_or_ref_with_id( @@ -1022,7 +1022,9 @@ impl Type { parent_id, ctx, ); - return Ok(ParseResult::AlreadyResolved(id.into())); + return Ok(ParseResult::AlreadyResolved( + id.into(), + )); } CXCursor_NamespaceRef => { return Err(ParseError::Continue); @@ -1078,11 +1080,10 @@ impl Type { let inner = Item::from_ty_or_ref(pointee, location, None, ctx); TypeKind::BlockPointer(inner) - }, + } // XXX: RValueReference is most likely wrong, but I don't think we // can even add bindings for that, so huh. - CXType_RValueReference | - CXType_LValueReference => { + CXType_RValueReference | CXType_LValueReference => { let inner = Item::from_ty_or_ref( ty.pointee_type().unwrap(), location, @@ -1092,14 +1093,14 @@ impl Type { TypeKind::Reference(inner) } // XXX DependentSizedArray is wrong - CXType_VariableArray | - CXType_DependentSizedArray => { + 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?"); + ) + .expect("Not able to resolve array element?"); TypeKind::Pointer(inner) } CXType_IncompleteArray => { @@ -1108,13 +1109,12 @@ impl Type { location, None, ctx, - ).expect("Not able to resolve array element?"); + ) + .expect("Not able to resolve array element?"); TypeKind::Array(inner, 0) } - CXType_FunctionNoProto | - CXType_FunctionProto => { - let signature = - FunctionSig::from_ty(ty, &location, ctx)?; + CXType_FunctionNoProto | CXType_FunctionProto => { + let signature = FunctionSig::from_ty(ty, &location, ctx)?; TypeKind::Function(signature) } CXType_Typedef => { @@ -1141,7 +1141,8 @@ impl Type { ty, Some(location), ctx, - ).expect("Not a complex type?"); + ) + .expect("Not a complex type?"); if name.is_empty() { // The pretty-printed name may contain typedefed name, @@ -1160,7 +1161,8 @@ impl Type { location, None, ctx, - ).expect("Not able to resolve vector element?"); + ) + .expect("Not able to resolve vector element?"); TypeKind::Vector(inner, ty.num_elements().unwrap()) } CXType_ConstantArray => { @@ -1169,7 +1171,8 @@ impl Type { location, None, ctx, - ).expect("Not able to resolve array element?"); + ) + .expect("Not able to resolve array element?"); TypeKind::Array(inner, ty.num_elements().unwrap()) } CXType_Elaborated => { @@ -1183,8 +1186,7 @@ impl Type { } CXType_ObjCId => TypeKind::ObjCId, CXType_ObjCSel => TypeKind::ObjCSel, - CXType_ObjCClass | - CXType_ObjCInterface => { + CXType_ObjCClass | CXType_ObjCInterface => { let interface = ObjCInterface::from_ty(&location, ctx) .expect("Not a valid objc interface?"); name = interface.rust_name(); diff --git a/src/ir/var.rs b/src/ir/var.rs index 2180a1b8e1..921dcf98c7 100644 --- a/src/ir/var.rs +++ b/src/ir/var.rs @@ -1,12 +1,12 @@ //! Intermediate representation of variables. -use callbacks::MacroParsingBehavior; use super::context::{BindgenContext, TypeId}; use super::dot::DotAttributes; use super::function::cursor_mangling; use super::int::IntKind; use super::item::Item; use super::ty::{FloatKind, TypeKind}; +use callbacks::MacroParsingBehavior; use cexpr; use clang; use parse::{ClangItemParser, ClangSubItemParser, ParseError, ParseResult}; @@ -133,9 +133,9 @@ impl ClangSubItemParser for Var { cursor: clang::Cursor, ctx: &mut BindgenContext, ) -> Result, ParseError> { - use clang_sys::*; use cexpr::expr::EvalResult; use cexpr::literal::CChar; + use clang_sys::*; match cursor.kind() { CXCursor_MacroDefinition => { if let Some(callbacks) = ctx.parse_callbacks() { @@ -205,9 +205,12 @@ impl ClangSubItemParser for Var { (TypeKind::Pointer(char_ty), VarType::String(val)) } EvalResult::Int(Wrapping(value)) => { - let kind = ctx.parse_callbacks() + let kind = ctx + .parse_callbacks() .and_then(|c| c.int_macro(&name, value)) - .unwrap_or_else(|| default_macro_constant_type(value)); + .unwrap_or_else(|| { + default_macro_constant_type(value) + }); (TypeKind::Int(kind), VarType::Int(value)) } @@ -239,7 +242,7 @@ impl ClangSubItemParser for Var { ty.kind(), CXType_Auto, "Couldn't resolve constant type, and it \ - wasn't an nondeductible auto type!" + wasn't an nondeductible auto type!" ); return Err(e); } @@ -249,9 +252,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()); @@ -266,27 +269,29 @@ impl ClangSubItemParser for Var { _ => unreachable!(), }; - let mut val = cursor - .evaluate() - .and_then(|v| v.as_int()); + let mut val = cursor.evaluate().and_then(|v| v.as_int()); if val.is_none() || !kind.signedness_matches(val.unwrap()) { let tu = ctx.translation_unit(); val = get_integer_literal_from_cursor(&cursor, tu); } - val.map(|val| if kind == IntKind::Bool { - VarType::Bool(val != 0) - } else { - VarType::Int(val) + val.map(|val| { + if kind == IntKind::Bool { + VarType::Bool(val != 0) + } else { + 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); @@ -355,8 +360,7 @@ fn get_integer_literal_from_cursor( let mut value = None; cursor.visit(|c| { match c.kind() { - CXCursor_IntegerLiteral | - CXCursor_UnaryOperator => { + CXCursor_IntegerLiteral | CXCursor_UnaryOperator => { value = parse_int_literal_tokens(&c); } CXCursor_UnexposedExpr => { diff --git a/src/lib.rs b/src/lib.rs index 722e53e9e5..7d8499efe2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -14,7 +14,7 @@ // constant. #![allow(non_upper_case_globals)] // `quote!` nests quite deeply. -#![recursion_limit="128"] +#![recursion_limit = "128"] #[macro_use] extern crate bitflags; @@ -82,26 +82,26 @@ doc_mod!(ir, ir_docs); doc_mod!(parse, parse_docs); doc_mod!(regex_set, regex_set_docs); -pub use features::{LATEST_STABLE_RUST, RUST_TARGET_STRINGS, RustTarget}; +pub use codegen::EnumVariation; use features::RustFeatures; +pub use features::{RustTarget, LATEST_STABLE_RUST, RUST_TARGET_STRINGS}; use ir::context::{BindgenContext, ItemId}; use ir::item::Item; use parse::{ClangItemParser, ParseError}; use regex_set::RegexSet; -pub use codegen::EnumVariation; use std::borrow::Cow; use std::fs::{File, OpenOptions}; use std::io::{self, Write}; -use std::{env, iter}; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::sync::Arc; +use std::{env, iter}; // Some convenient typedefs for a fast hash map and hash set. type HashMap = ::fxhash::FxHashMap; type HashSet = ::fxhash::FxHashSet; -pub(crate) use ::std::collections::hash_map::Entry; +pub(crate) use std::collections::hash_map::Entry; fn args_are_cpp(clang_args: &[String]) -> bool { return clang_args @@ -226,13 +226,20 @@ impl Builder { if self.options.default_enum_style != Default::default() { output_vector.push("--default-enum-style=".into()); - output_vector.push(match self.options.default_enum_style { - codegen::EnumVariation::Rust { non_exhaustive: false } => "rust", - codegen::EnumVariation::Rust { non_exhaustive: true } => "rust_non_exhaustive", - codegen::EnumVariation::Bitfield => "bitfield", - codegen::EnumVariation::Consts => "consts", - codegen::EnumVariation::ModuleConsts => "moduleconsts", - }.into()) + output_vector.push( + match self.options.default_enum_style { + codegen::EnumVariation::Rust { + non_exhaustive: false, + } => "rust", + codegen::EnumVariation::Rust { + non_exhaustive: true, + } => "rust_non_exhaustive", + codegen::EnumVariation::Bitfield => "bitfield", + codegen::EnumVariation::Consts => "consts", + codegen::EnumVariation::ModuleConsts => "moduleconsts", + } + .into(), + ) } self.options @@ -539,7 +546,8 @@ impl Builder { output_vector.push("--no-rustfmt-bindings".into()); } - if let Some(path) = self.options + if let Some(path) = self + .options .rustfmt_configuration_file .as_ref() .and_then(|f| f.to_str()) @@ -612,9 +620,8 @@ 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 } @@ -801,7 +808,10 @@ impl Builder { } /// Set the default style of code to generate for enums - pub fn default_enum_style(mut self, arg: codegen::EnumVariation) -> Builder { + pub fn default_enum_style( + mut self, + arg: codegen::EnumVariation, + ) -> Builder { self.options.default_enum_style = arg; self } @@ -835,7 +845,10 @@ impl Builder { /// /// This makes bindgen generate enums instead of constants. Regular /// expressions are supported. - pub fn rustified_non_exhaustive_enum>(mut self, arg: T) -> Builder { + pub fn rustified_non_exhaustive_enum>( + mut self, + arg: T, + ) -> Builder { self.options.rustified_non_exhaustive_enums.insert(arg); self } @@ -1201,7 +1214,9 @@ impl Builder { /// Generate the Rust bindings using the options built up thus far. pub fn generate(mut self) -> Result { // Add any extra arguments from the environment to the clang command line. - if let Some(extra_clang_args) = env::var("BINDGEN_EXTRA_CLANG_ARGS").ok() { + if let Some(extra_clang_args) = + env::var("BINDGEN_EXTRA_CLANG_ARGS").ok() + { // Try to parse it with shell quoting. If we fail, make it one single big argument. if let Some(strings) = shlex::split(&extra_clang_args) { self.options.clang_args.extend(strings); @@ -1212,18 +1227,18 @@ impl Builder { // Transform input headers to arguments on the clang command line. 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.options + .clang_args + .extend(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) @@ -1236,14 +1251,19 @@ impl Builder { /// `__bindgen.ii` pub fn dump_preprocessed_input(&self) -> io::Result<()> { fn check_is_cpp(name_file: &str) -> bool { - name_file.ends_with(".hpp") || name_file.ends_with(".hxx") - || name_file.ends_with(".hh") - || name_file.ends_with(".h++") + name_file.ends_with(".hpp") || + name_file.ends_with(".hxx") || + name_file.ends_with(".hh") || + name_file.ends_with(".h++") } - 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. @@ -1566,7 +1586,6 @@ struct BindgenOptions { /// The absolute path to the rustfmt configuration file, if None, the standard rustfmt /// options are used. - rustfmt_configuration_file: Option, /// The set of types that we should not derive `PartialEq` for. @@ -1710,9 +1729,10 @@ fn ensure_libclang_is_loaded() { lazy_static! { static ref LIBCLANG: Arc = { clang_sys::load().expect("Unable to find libclang"); - clang_sys::get_library() - .expect("We just loaded libclang and it had better still be \ - here!") + clang_sys::get_library().expect( + "We just loaded libclang and it had better still be \ + here!", + ) }; } @@ -1733,7 +1753,10 @@ impl Bindings { ) -> Result { ensure_libclang_is_loaded(); - debug!("Generating bindings, libclang at {}", clang_sys::get_library().unwrap().path().display()); + debug!( + "Generating bindings, libclang at {}", + clang_sys::get_library().unwrap().path().display() + ); options.build(); @@ -1746,32 +1769,45 @@ impl Bindings { // promote them to `-isystem`. let clang_args_for_clang_sys = { let mut last_was_include_prefix = false; - options.clang_args.iter().filter(|arg| { - if last_was_include_prefix { - last_was_include_prefix = false; - return false; - } + options + .clang_args + .iter() + .filter(|arg| { + if last_was_include_prefix { + last_was_include_prefix = false; + return false; + } - let arg = &**arg; + let arg = &**arg; - // https://clang.llvm.org/docs/ClangCommandLineReference.html - // -isystem and -isystem-after are harmless. - if arg == "-I" || arg == "--include-directory" { - last_was_include_prefix = true; - return false; - } + // https://clang.llvm.org/docs/ClangCommandLineReference.html + // -isystem and -isystem-after are harmless. + if arg == "-I" || arg == "--include-directory" { + last_was_include_prefix = true; + return false; + } - if arg.starts_with("-I") || arg.starts_with("--include-directory=") { - return false; - } + if arg.starts_with("-I") || + arg.starts_with("--include-directory=") + { + return false; + } - true - }).cloned().collect::>() + true + }) + .cloned() + .collect::>() }; - debug!("Trying to find clang with flags: {:?}", clang_args_for_clang_sys); + debug!( + "Trying to find clang with flags: {:?}", + clang_args_for_clang_sys + ); - let clang = match clang_sys::support::Clang::find(None, &clang_args_for_clang_sys) { + let clang = match clang_sys::support::Clang::find( + None, + &clang_args_for_clang_sys, + ) { None => return, Some(clang) => clang, }; @@ -1781,9 +1817,9 @@ impl Bindings { // Whether we are working with C or C++ inputs. let is_cpp = args_are_cpp(&options.clang_args); let search_paths = if is_cpp { - clang.cpp_search_paths + clang.cpp_search_paths } else { - clang.c_search_paths + clang.c_search_paths }; if let Some(search_paths) = search_paths { @@ -1816,7 +1852,10 @@ impl Bindings { return Err(()); } if !can_read(&md.permissions()) { - eprintln!("error: insufficient permissions to read '{}'", h); + eprintln!( + "error: insufficient permissions to read '{}'", + h + ); return Err(()); } options.clang_args.push(h.clone()) @@ -1836,8 +1875,7 @@ impl Bindings { let mut context = BindgenContext::new(options); { - let _t = time::Timer::new("parse") - .with_output(time_phases); + let _t = time::Timer::new("parse").with_output(time_phases); parse(&mut context)?; } @@ -1847,7 +1885,7 @@ impl Bindings { options: options, module: quote! { #( #items )* - } + }, }) } @@ -1891,11 +1929,14 @@ impl Bindings { match self.rustfmt_generated_string(&bindings) { Ok(rustfmt_bindings) => { writer.write(rustfmt_bindings.as_bytes())?; - }, + } Err(err) => { - eprintln!("Failed to run rustfmt: {} (non-fatal, continuing)", err); + eprintln!( + "Failed to run rustfmt: {} (non-fatal, continuing)", + err + ); writer.write(bindings.as_bytes())?; - }, + } } Ok(()) } @@ -1912,10 +1953,15 @@ impl Bindings { #[cfg(feature = "which-rustfmt")] match which::which("rustfmt") { Ok(p) => Ok(Cow::Owned(p)), - Err(e) => Err(io::Error::new(io::ErrorKind::Other, format!("{}", e))), + Err(e) => { + Err(io::Error::new(io::ErrorKind::Other, format!("{}", e))) + } } #[cfg(not(feature = "which-rustfmt"))] - Err(io::Error::new(io::ErrorKind::Other, "which wasn't enabled, and no rustfmt binary specified")) + Err(io::Error::new( + io::ErrorKind::Other, + "which wasn't enabled, and no rustfmt binary specified", + )) } /// Checks if rustfmt_bindings is set and runs rustfmt on the string @@ -1933,11 +1979,10 @@ impl Bindings { let rustfmt = self.rustfmt_path()?; let mut cmd = Command::new(&*rustfmt); - cmd - .stdin(Stdio::piped()) - .stdout(Stdio::piped()); + cmd.stdin(Stdio::piped()).stdout(Stdio::piped()); - if let Some(path) = self.options + if let Some(path) = self + .options .rustfmt_configuration_file .as_ref() .and_then(|f| f.to_str()) @@ -1963,29 +2008,28 @@ impl Bindings { io::copy(&mut child_stdout, &mut output)?; let status = child.wait()?; - let source = stdin_handle.join() - .expect("The thread writing to rustfmt's stdin doesn't do \ - anything that could panic"); + let source = stdin_handle.join().expect( + "The thread writing to rustfmt's stdin doesn't do \ + anything that could panic", + ); match String::from_utf8(output) { - Ok(bindings) => { - match status.code() { - Some(0) => Ok(Cow::Owned(bindings)), - Some(2) => Err(io::Error::new( - io::ErrorKind::Other, - "Rustfmt parsing errors.".to_string(), - )), - Some(3) => { - warn!("Rustfmt could not format some lines."); - Ok(Cow::Owned(bindings)) - } - _ => Err(io::Error::new( - io::ErrorKind::Other, - "Internal rustfmt error".to_string(), - )), + Ok(bindings) => match status.code() { + Some(0) => Ok(Cow::Owned(bindings)), + Some(2) => Err(io::Error::new( + io::ErrorKind::Other, + "Rustfmt parsing errors.".to_string(), + )), + Some(3) => { + warn!("Rustfmt could not format some lines."); + Ok(Cow::Owned(bindings)) } + _ => Err(io::Error::new( + io::ErrorKind::Other, + "Internal rustfmt error".to_string(), + )), }, - _ => Ok(Cow::Owned(source)) + _ => Ok(Cow::Owned(source)), } } } @@ -2036,7 +2080,6 @@ fn parse(context: &mut BindgenContext) -> Result<(), ()> { let cursor = context.translation_unit().cursor(); if context.options().emit_ast { - fn dump_if_not_builtin(cur: &clang::Cursor) -> CXChildVisitResult { if !cur.is_builtin() { clang::ast_dump(&cur, 0) @@ -2076,9 +2119,10 @@ 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 { @@ -2115,13 +2159,14 @@ fn commandline_flag_unit_test_function() { "--no-derive-default", "--generate", "functions,types,vars,methods,constructors,destructors", - ].iter() - .map(|&x| x.into()) - .collect::>(); + ] + .iter() + .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() @@ -2140,13 +2185,13 @@ fn commandline_flag_unit_test_function() { "Distinct_Type", "--whitelist-function", "safe_function", - ].iter() - .map(|&x| x.into()) - .collect::>(); + ] + .iter() + .map(|&x| x.into()) + .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 3d3867a73a..5e22b1e6bc 100644 --- a/src/main.rs +++ b/src/main.rs @@ -45,7 +45,6 @@ pub fn main() { match builder_from_flags(bind_args.into_iter()) { Ok((builder, output, verbose)) => { - let builder_result = panic::catch_unwind(|| { builder.generate().expect("Unable to generate bindings") }); @@ -71,12 +70,12 @@ fn print_verbose_err() { println!("Bindgen unexpectedly panicked"); println!( "This may be caused by one of the known-unsupported \ - things (https://rust-lang.github.io/rust-bindgen/cpp.html), \ - please modify the bindgen flags to work around it as \ - described in https://rust-lang.github.io/rust-bindgen/cpp.html" + things (https://rust-lang.github.io/rust-bindgen/cpp.html), \ + please modify the bindgen flags to work around it as \ + described in https://rust-lang.github.io/rust-bindgen/cpp.html" ); println!( "Otherwise, please file an issue at \ - https://github.com/rust-lang/rust-bindgen/issues/new" + https://github.com/rust-lang/rust-bindgen/issues/new" ); } diff --git a/src/options.rs b/src/options.rs index d15cba8172..6ead924141 100644 --- a/src/options.rs +++ b/src/options.rs @@ -1,14 +1,12 @@ -use bindgen::{Builder, CodegenConfig, RUST_TARGET_STRINGS, RustTarget, builder, EnumVariation}; +use bindgen::{builder, Builder, CodegenConfig, EnumVariation, RustTarget, RUST_TARGET_STRINGS}; use clap::{App, Arg}; use std::fs::File; -use std::io::{self, Error, ErrorKind, Write, stderr}; +use std::io::{self, stderr, Error, ErrorKind, Write}; use std::path::PathBuf; use std::str::FromStr; /// Construct a new [`Builder`](./struct.Builder.html) from command line flags. -pub fn builder_from_flags( - args: I, -) -> Result<(Builder, Box, bool), io::Error> +pub fn builder_from_flags(args: I) -> Result<(Builder, Box, bool), io::Error> where I: Iterator, { @@ -31,12 +29,20 @@ where .help("The default style of code used to generate enums.") .value_name("variant") .default_value("consts") - .possible_values(&["consts", "moduleconsts", "bitfield", "rust", "rust_non_exhaustive"]) + .possible_values(&[ + "consts", + "moduleconsts", + "bitfield", + "rust", + "rust_non_exhaustive", + ]) .multiple(false), Arg::with_name("bitfield-enum") .long("bitfield-enum") - .help("Mark any enum whose name matches as a set of \ - bitfield flags.") + .help( + "Mark any enum whose name matches as a set of \ + bitfield flags.", + ) .value_name("regex") .takes_value(true) .multiple(true) @@ -50,16 +56,20 @@ where .number_of_values(1), Arg::with_name("constified-enum") .long("constified-enum") - .help("Mark any enum whose name matches as a series of \ - constants.") + .help( + "Mark any enum whose name matches as a series of \ + constants.", + ) .value_name("regex") .takes_value(true) .multiple(true) .number_of_values(1), Arg::with_name("constified-enum-module") .long("constified-enum-module") - .help("Mark any enum whose name matches as a module of \ - constants.") + .help( + "Mark any enum whose name matches as a module of \ + constants.", + ) .value_name("regex") .takes_value(true) .multiple(true) @@ -98,14 +108,16 @@ where .long("no-derive-default") .hidden(true) .help("Avoid deriving Default on any type."), - Arg::with_name("impl-debug") - .long("impl-debug") - .help("Create Debug implementation, if it can not be derived \ - automatically."), + Arg::with_name("impl-debug").long("impl-debug").help( + "Create Debug implementation, if it can not be derived \ + automatically.", + ), Arg::with_name("impl-partialeq") .long("impl-partialeq") - .help("Create PartialEq implementation, if it can not be derived \ - automatically."), + .help( + "Create PartialEq implementation, if it can not be derived \ + automatically.", + ), Arg::with_name("with-derive-default") .long("with-derive-default") .help("Derive Default on any type."), @@ -120,22 +132,30 @@ where .help("Derive partialord on any type."), Arg::with_name("with-derive-eq") .long("with-derive-eq") - .help("Derive eq on any type. Enable this option also \ - enables --with-derive-partialeq"), + .help( + "Derive eq on any type. Enable this option also \ + enables --with-derive-partialeq", + ), Arg::with_name("with-derive-ord") .long("with-derive-ord") - .help("Derive ord on any type. Enable this option also \ - enables --with-derive-partialord"), + .help( + "Derive ord on any type. Enable this option also \ + enables --with-derive-partialord", + ), Arg::with_name("no-doc-comments") .long("no-doc-comments") - .help("Avoid including doc comments in the output, see: \ - https://github.com/rust-lang/rust-bindgen/issues/426"), + .help( + "Avoid including doc comments in the output, see: \ + https://github.com/rust-lang/rust-bindgen/issues/426", + ), Arg::with_name("no-recursive-whitelist") .long("no-recursive-whitelist") - .help("Disable whitelisting types recursively. This will cause \ - bindgen to emit Rust code that won't compile! See the \ - `bindgen::Builder::whitelist_recursively` method's \ - documentation for details."), + .help( + "Disable whitelisting types recursively. This will cause \ + bindgen to emit Rust code that won't compile! See the \ + `bindgen::Builder::whitelist_recursively` method's \ + documentation for details.", + ), Arg::with_name("objc-extern-crate") .long("objc-extern-crate") .help("Use extern crate instead of use for objc."), @@ -148,23 +168,23 @@ where Arg::with_name("distrust-clang-mangling") .long("distrust-clang-mangling") .help("Do not trust the libclang-provided mangling"), - Arg::with_name("builtins") - .long("builtins") - .help("Output bindings for builtin definitions, e.g. \ - __builtin_va_list."), + Arg::with_name("builtins").long("builtins").help( + "Output bindings for builtin definitions, e.g. \ + __builtin_va_list.", + ), Arg::with_name("ctypes-prefix") .long("ctypes-prefix") - .help("Use the given prefix before raw types instead of \ - ::std::os::raw.") + .help( + "Use the given prefix before raw types instead of \ + ::std::os::raw.", + ) .value_name("prefix") .takes_value(true), Arg::with_name("time-phases") .long("time-phases") .help("Time the different bindgen phases and print to stderr"), // All positional arguments after the end of options marker, `--` - Arg::with_name("clang-args") - .last(true) - .multiple(true), + Arg::with_name("clang-args").last(true).multiple(true), Arg::with_name("emit-clang-ast") .long("emit-clang-ast") .help("Output the Clang AST for debugging purposes."), @@ -181,18 +201,24 @@ where .help("Enable support for C++ namespaces."), Arg::with_name("disable-name-namespacing") .long("disable-name-namespacing") - .help("Disable namespacing via mangling, causing bindgen to \ - generate names like \"Baz\" instead of \"foo_bar_Baz\" \ - for an input name \"foo::bar::Baz\"."), + .help( + "Disable namespacing via mangling, causing bindgen to \ + generate names like \"Baz\" instead of \"foo_bar_Baz\" \ + for an input name \"foo::bar::Baz\".", + ), Arg::with_name("ignore-functions") .long("ignore-functions") - .help("Do not generate bindings for functions or methods. This \ - is useful when you only care about struct layouts."), + .help( + "Do not generate bindings for functions or methods. This \ + is useful when you only care about struct layouts.", + ), Arg::with_name("generate") .long("generate") - .help("Generate only given items, split by commas. \ - Valid values are \"functions\",\"types\", \"vars\", \ - \"methods\", \"constructors\" and \"destructors\".") + .help( + "Generate only given items, split by commas. \ + Valid values are \"functions\",\"types\", \"vars\", \ + \"methods\", \"constructors\" and \"destructors\".", + ) .takes_value(true), Arg::with_name("ignore-methods") .long("ignore-methods") @@ -237,16 +263,20 @@ where .help("Use types from Rust core instead of std."), Arg::with_name("conservative-inline-namespaces") .long("conservative-inline-namespaces") - .help("Conservatively generate inline namespaces to avoid name \ - conflicts."), + .help( + "Conservatively generate inline namespaces to avoid name \ + conflicts.", + ), Arg::with_name("use-msvc-mangling") .long("use-msvc-mangling") .help("MSVC C++ ABI mangling. DEPRECATED: Has no effect."), Arg::with_name("whitelist-function") .long("whitelist-function") - .help("Whitelist all the free-standing functions matching \ - . Other non-whitelisted functions will not be \ - generated.") + .help( + "Whitelist all the free-standing functions matching \ + . Other non-whitelisted functions will not be \ + generated.", + ) .value_name("regex") .takes_value(true) .multiple(true) @@ -256,17 +286,21 @@ where .help("Generate inline functions."), Arg::with_name("whitelist-type") .long("whitelist-type") - .help("Only generate types matching . Other non-whitelisted types will \ - not be generated.") + .help( + "Only generate types matching . Other non-whitelisted types will \ + not be generated.", + ) .value_name("regex") .takes_value(true) .multiple(true) .number_of_values(1), Arg::with_name("whitelist-var") .long("whitelist-var") - .help("Whitelist all the free-standing variables matching \ - . Other non-whitelisted variables will not be \ - generated.") + .help( + "Whitelist all the free-standing variables matching \ + . Other non-whitelisted variables will not be \ + generated.", + ) .value_name("regex") .takes_value(true) .multiple(true) @@ -276,27 +310,35 @@ where .help("Print verbose error messages."), Arg::with_name("dump-preprocessed-input") .long("dump-preprocessed-input") - .help("Preprocess and dump the input header files to disk. \ - Useful when debugging bindgen, using C-Reduce, or when \ - filing issues. The resulting file will be named \ - something like `__bindgen.i` or `__bindgen.ii`."), + .help( + "Preprocess and dump the input header files to disk. \ + Useful when debugging bindgen, using C-Reduce, or when \ + filing issues. The resulting file will be named \ + something like `__bindgen.i` or `__bindgen.ii`.", + ), Arg::with_name("no-record-matches") .long("no-record-matches") - .help("Do not record matching items in the regex sets. \ - This disables reporting of unused items."), + .help( + "Do not record matching items in the regex sets. \ + This disables reporting of unused items.", + ), Arg::with_name("no-rustfmt-bindings") .long("no-rustfmt-bindings") .help("Do not format the generated bindings with rustfmt."), Arg::with_name("rustfmt-bindings") .long("rustfmt-bindings") - .help("Format the generated bindings with rustfmt. DEPRECATED: \ - --rustfmt-bindings is now enabled by default. Disable \ - with --no-rustfmt-bindings."), + .help( + "Format the generated bindings with rustfmt. DEPRECATED: \ + --rustfmt-bindings is now enabled by default. Disable \ + with --no-rustfmt-bindings.", + ), Arg::with_name("rustfmt-configuration-file") .long("rustfmt-configuration-file") - .help("The absolute path to the rustfmt configuration file. \ - The configuration file will be used for formatting the bindings. \ - This parameter is incompatible with --no-rustfmt-bindings.") + .help( + "The absolute path to the rustfmt configuration file. \ + The configuration file will be used for formatting the bindings. \ + This parameter is incompatible with --no-rustfmt-bindings.", + ) .value_name("path") .takes_value(true) .multiple(false) @@ -324,8 +366,10 @@ where .number_of_values(1), Arg::with_name("enable-function-attribute-detection") .long("enable-function-attribute-detection") - .help("Enables detecting unexposed attributes in functions (slow). - Used to generate #[must_use] annotations."), + .help( + "Enables detecting unexposed attributes in functions (slow). + Used to generate #[must_use] annotations.", + ), Arg::with_name("use-array-pointers-in-arguments") .long("use-array-pointers-in-arguments") .help("Use `*const [T; size]` instead of `*const T` for C arrays"), @@ -345,7 +389,8 @@ where writeln!( &mut stderr(), "warning: the `--unstable-rust` option is deprecated" - ).expect("Unable to write error message"); + ) + .expect("Unable to write error message"); } if let Some(rust_target) = matches.value_of("rust-target") { @@ -624,7 +669,7 @@ where if no_rustfmt_bindings { return Err(Error::new( ErrorKind::Other, - "Cannot supply both --rustfmt-configuration-file and --no-rustfmt-bindings" + "Cannot supply both --rustfmt-configuration-file and --no-rustfmt-bindings", )); } diff --git a/src/time.rs b/src/time.rs index 5bd0da8d61..c13a640c46 100644 --- a/src/time.rs +++ b/src/time.rs @@ -1,6 +1,5 @@ use std::io::{self, Write}; -use std::time::{Instant, Duration}; - +use std::time::{Duration, Instant}; /// RAII timer to measure how long phases take. #[derive(Debug)] @@ -10,7 +9,6 @@ pub struct Timer<'a> { start: Instant, } - impl<'a> Timer<'a> { /// Creates a Timer with the given name, and starts it. By default, /// will print to stderr when it is `drop`'d @@ -18,7 +16,7 @@ impl<'a> Timer<'a> { Timer { output: true, name, - start: Instant::now() + start: Instant::now(), } } @@ -37,19 +35,16 @@ impl<'a> Timer<'a> { fn print_elapsed(&mut self) { if self.output { let elapsed = self.elapsed(); - let time = (elapsed.as_secs() as f64) * 1e3 - + (elapsed.subsec_nanos() as f64) / 1e6; + let time = (elapsed.as_secs() as f64) * 1e3 + + (elapsed.subsec_nanos() as f64) / 1e6; let stderr = io::stderr(); // Arbitrary output format, subject to change. - writeln!(stderr.lock(), - " time: {:>9.3} ms.\t{}", - time, self.name) - .expect("timer write should not fail"); + writeln!(stderr.lock(), " time: {:>9.3} ms.\t{}", time, self.name) + .expect("timer write should not fail"); } } } - impl<'a> Drop for Timer<'a> { fn drop(&mut self) { self.print_elapsed(); diff --git a/tests/stylo_sanity.rs b/tests/stylo_sanity.rs index d2d2e841b5..41d614a829 100755 --- a/tests/stylo_sanity.rs +++ b/tests/stylo_sanity.rs @@ -14,11 +14,15 @@ extern crate bindgen; /// 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"))] +#[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; diff --git a/tests/tests.rs b/tests/tests.rs index ee4783ebd9..14729c80c0 100644 --- a/tests/tests.rs +++ b/tests/tests.rs @@ -1,11 +1,11 @@ -#[cfg(feature = "logging")] -extern crate env_logger; +extern crate bindgen; extern crate clap; extern crate diff; -extern crate bindgen; +#[cfg(feature = "logging")] +extern crate env_logger; extern crate shlex; -use bindgen::{Builder, clang_version}; +use bindgen::{clang_version, Builder}; use std::env; use std::fs; use std::io::{self, BufRead, BufReader, Error, ErrorKind, Read, Write}; @@ -35,13 +35,15 @@ fn rustfmt(source: String) -> (String, String) { .map_or(false, |status| status.success()); if !have_working_rustfmt { - panic!(" + panic!( + " The latest `rustfmt` is required to run the `bindgen` test suite. Install `rustfmt` with: $ rustup update nightly $ rustup run nightly cargo install -f rustfmt-nightly -"); +" + ); } }); @@ -51,7 +53,7 @@ The latest `rustfmt` is required to run the `bindgen` test suite. Install "nightly", "rustfmt", "--config-path", - concat!(env!("CARGO_MANIFEST_DIR"), "/tests/rustfmt.toml") + concat!(env!("CARGO_MANIFEST_DIR"), "/tests/rustfmt.toml"), ]) .stdin(process::Stdio::piped()) .stdout(process::Stdio::piped()) @@ -66,43 +68,37 @@ The latest `rustfmt` is required to run the `bindgen` test suite. Install // Write to stdin in a new thread, so that we can read from stdout on this // thread. This keeps the child from blocking on writing to its stdout which // might block us from writing to its stdin. - let stdin_handle = ::std::thread::spawn(move || { - stdin.write_all(source.as_bytes()) - }); + let stdin_handle = ::std::thread::spawn(move || stdin.write_all(source.as_bytes())); // Read stderr on a new thread for similar reasons. let stderr_handle = ::std::thread::spawn(move || { let mut output = vec![]; - io::copy(&mut stderr, &mut output) - .map(|_| String::from_utf8_lossy(&output).to_string()) + io::copy(&mut stderr, &mut output).map(|_| String::from_utf8_lossy(&output).to_string()) }); let mut output = vec![]; - io::copy(&mut stdout, &mut output) - .expect("Should copy stdout into vec OK"); + io::copy(&mut stdout, &mut output).expect("Should copy stdout into vec OK"); // Ignore actual rustfmt status because it is often non-zero for trivial // things. let _ = child.wait().expect("should wait on rustfmt child OK"); - stdin_handle.join() + stdin_handle + .join() .expect("writer thread should not have panicked") .expect("should have written to child rustfmt's stdin OK"); - let bindings = String::from_utf8(output) - .expect("rustfmt should only emit valid utf-8"); + let bindings = String::from_utf8(output).expect("rustfmt should only emit valid utf-8"); - let stderr = stderr_handle.join() + let stderr = stderr_handle + .join() .expect("stderr reader thread should not have panicked") .expect("should have read child rustfmt's stderr OK"); (bindings, stderr) } -fn compare_generated_header( - header: &PathBuf, - builder: Builder, -) -> Result<(), Error> { +fn compare_generated_header(header: &PathBuf, builder: Builder) -> Result<(), Error> { let file_name = header.file_name().ok_or(Error::new( ErrorKind::Other, "compare_generated_header expects a file", @@ -152,7 +148,7 @@ fn compare_generated_header( if !expectation.is_file() { panic!( "missing test expectation file and/or 'testing_only_libclang_$VERSION' \ - feature for header '{}'; looking for expectation file at '{}'", + feature for header '{}'; looking for expectation file at '{}'", header.display(), expectation.display() ); @@ -236,7 +232,8 @@ fn create_bindgen_builder(header: &PathBuf) -> Result, Error> { } if line.contains("bindgen-flags: ") { - let extra_flags = line.split("bindgen-flags: ") + let extra_flags = line + .split("bindgen-flags: ") .last() .and_then(shlex::split) .unwrap(); @@ -248,8 +245,8 @@ fn create_bindgen_builder(header: &PathBuf) -> Result, Error> { .map(ToString::to_string) .chain(flags) .collect(); - } else if line.contains("bindgen-generate-bindings-on-linux-only") && - !cfg!(target_os = "linux") + } else if line.contains("bindgen-generate-bindings-on-linux-only") + && !cfg!(target_os = "linux") { return Ok(None); } @@ -269,10 +266,9 @@ 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 = header.to_str().ok_or(Error::new( - ErrorKind::Other, - "Invalid header file name", - ))?; + let header_str = header + .to_str() + .ok_or(Error::new(ErrorKind::Other, "Invalid header file name"))?; let prepend = [ "bindgen", @@ -289,33 +285,32 @@ fn create_bindgen_builder(header: &PathBuf) -> Result, Error> { "", ]; - let args = prepend.into_iter().map(ToString::to_string).chain( - flags - .into_iter(), - ); + 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 { - ($function:ident, $header:expr) => ( + ($function:ident, $header:expr) => { #[test] fn $function() { let header = PathBuf::from($header); - let result = create_bindgen_builder(&header) - .and_then(|builder| { - if let Some(builder) = builder { - compare_generated_header(&header, builder) - } else { - Ok(()) - } - }); + let result = create_bindgen_builder(&header).and_then(|builder| { + if let Some(builder) = builder { + compare_generated_header(&header, builder) + } else { + Ok(()) + } + }); if let Err(err) = result { panic!("{}", err); } } - ) + }; } // This file is generated by build.rs @@ -323,12 +318,17 @@ include!(concat!(env!("OUT_DIR"), "/tests.rs")); #[test] fn test_clang_env_args() { - std::env::set_var("BINDGEN_EXTRA_CLANG_ARGS", "-D_ENV_ONE=1 -D_ENV_TWO=\"2 -DNOT_THREE=1\""); + std::env::set_var( + "BINDGEN_EXTRA_CLANG_ARGS", + "-D_ENV_ONE=1 -D_ENV_TWO=\"2 -DNOT_THREE=1\"", + ); let actual = builder() - .header_contents("test.hpp", - "#ifdef _ENV_ONE\nextern const int x[] = { 42 };\n#endif\n\ - #ifdef _ENV_TWO\nextern const int y[] = { 42 };\n#endif\n\ - #ifdef NOT_THREE\nextern const int z[] = { 42 };\n#endif\n") + .header_contents( + "test.hpp", + "#ifdef _ENV_ONE\nextern const int x[] = { 42 };\n#endif\n\ + #ifdef _ENV_TWO\nextern const int y[] = { 42 };\n#endif\n\ + #ifdef NOT_THREE\nextern const int z[] = { 42 };\n#endif\n", + ) .generate() .unwrap() .to_string(); @@ -336,7 +336,8 @@ fn test_clang_env_args() { let (actual, stderr) = rustfmt(actual); println!("{}", stderr); - let (expected, _) = rustfmt("/* automatically generated by rust-bindgen */ + let (expected, _) = rustfmt( + "/* automatically generated by rust-bindgen */ extern \"C\" { pub static mut x: [::std::os::raw::c_int; 1usize]; @@ -344,12 +345,11 @@ extern \"C\" { extern \"C\" { pub static mut y: [::std::os::raw::c_int; 1usize]; } -".to_string()); - - assert_eq!( - expected, - actual +" + .to_string(), ); + + assert_eq!(expected, actual); } #[test] @@ -364,17 +364,17 @@ fn test_header_contents() { let (actual, stderr) = rustfmt(actual); println!("{}", stderr); - let (expected, _) = rustfmt("/* automatically generated by rust-bindgen */ + let (expected, _) = rustfmt( + "/* automatically generated by rust-bindgen */ extern \"C\" { pub fn foo(a: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int; } -".to_string()); - - assert_eq!( - expected, - actual +" + .to_string(), ); + + assert_eq!(expected, actual); } #[test] @@ -420,21 +420,18 @@ 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") - .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() - ); + 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()); } #[test] fn dump_preprocessed_input() { - let arg_keyword = - concat!(env!("CARGO_MANIFEST_DIR"), "/tests/headers/arg_keyword.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"