From 00e9d471d9cc025c761979d69456efa7c798effd Mon Sep 17 00:00:00 2001 From: Markus Reiter Date: Sat, 17 Jun 2023 22:38:23 +0200 Subject: [PATCH] Revert some `try_into` calls. --- bindgen/clang.rs | 176 +++++++++++++++++++++++---------------------- bindgen/ir/comp.rs | 2 +- 2 files changed, 90 insertions(+), 88 deletions(-) diff --git a/bindgen/clang.rs b/bindgen/clang.rs index 6c7da0fb76..476b0d12c6 100644 --- a/bindgen/clang.rs +++ b/bindgen/clang.rs @@ -7,13 +7,13 @@ use crate::ir::context::BindgenContext; use clang_sys::*; use std::cmp; -use std::convert::TryFrom; + use std::convert::TryInto; use std::ffi::{CStr, CString}; use std::fmt; use std::hash::Hash; use std::hash::Hasher; -use std::os::raw::c_char; +use std::os::raw::{c_char, c_int, c_uint}; use std::{mem, ptr, slice}; /// Type representing a clang attribute. @@ -71,6 +71,16 @@ impl fmt::Debug for Cursor { } } +trait ToUsize { + fn to_usize(self) -> usize; +} + +impl ToUsize for c_uint { + fn to_usize(self) -> usize { + self.try_into().expect("`c_uint` does not fit in `usize`") + } +} + impl Cursor { /// Get the Unified Symbol Resolution for this cursor's referent, if /// available. @@ -122,13 +132,14 @@ impl Cursor { if manglings.is_null() { return Err(()); } - let count = (*manglings).Count.try_into().unwrap(); - - let mut result = Vec::with_capacity(count); - for i in 0..count { - let string_ptr = (*manglings).Strings.add(i); - result.push(cxstring_to_string_leaky(*string_ptr)); - } + let string_set = slice::from_raw_parts( + (*manglings).Strings, + (*manglings).Count.to_usize(), + ); + let result = string_set + .iter() + .map(|string_ptr| cxstring_to_string_leaky(*string_ptr)) + .collect(); clang_disposeStringSet(manglings); Ok(result) } @@ -195,7 +206,7 @@ impl Cursor { /// /// NOTE: This may not return `Some` for partial template specializations, /// see #193 and #194. - pub(crate) fn num_template_args(&self) -> Option { + pub(crate) fn num_template_args(&self) -> Option { // XXX: `clang_Type_getNumTemplateArguments` is sort of reliable, while // `clang_Cursor_getNumTemplateArguments` is totally unreliable. // Therefore, try former first, and only fallback to the latter if we @@ -203,9 +214,10 @@ impl Cursor { self.cur_type() .num_template_args() .or_else(|| { - let n = unsafe { clang_Cursor_getNumTemplateArguments(self.x) }; + let n: c_int = + unsafe { clang_Cursor_getNumTemplateArguments(self.x) }; if n >= 0 { - Some(n.try_into().unwrap()) + Some(n as c_uint) } else { debug_assert_eq!(n, -1); None @@ -706,9 +718,9 @@ impl Cursor { } unsafe { - let w = clang_getFieldDeclBitWidth(self.x); + let w: c_int = clang_getFieldDeclBitWidth(self.x); if w >= 0 { - Some(w.try_into().unwrap()) + Some((w as c_uint).to_usize()) } else { debug_assert_eq!(w, -1); None @@ -847,9 +859,7 @@ impl Cursor { self.num_args().ok().map(|num| { (0..num) .map(|i| Cursor { - x: unsafe { - clang_Cursor_getArgument(self.x, i.try_into().unwrap()) - }, + x: unsafe { clang_Cursor_getArgument(self.x, i) }, }) .collect() }) @@ -860,11 +870,11 @@ impl Cursor { /// /// Returns Err if the cursor's referent is not a function/method call or /// declaration. - pub(crate) fn num_args(&self) -> Result { + pub(crate) fn num_args(&self) -> Result { unsafe { - let n = clang_Cursor_getNumArguments(self.x); + let n: c_int = clang_Cursor_getNumArguments(self.x); if n >= 0 { - Ok(n.try_into().unwrap()) + Ok(n as c_uint) } else { debug_assert_eq!(n, -1); @@ -896,11 +906,10 @@ impl Cursor { /// Get the offset of the field represented by the Cursor. pub(crate) fn offset_of_field(&self) -> Result { let offset = unsafe { clang_Cursor_getOffsetOfField(self.x) }; - if offset < 0 { - Err(LayoutError::from(i32::try_from(offset).unwrap())) + Err(LayoutError::from(offset)) } else { - Ok(offset.try_into().unwrap()) + Ok(offset.try_into().expect("offset does not fit in `usize`")) } } @@ -979,7 +988,7 @@ pub(crate) struct RawTokens<'a> { cursor: &'a Cursor, tu: CXTranslationUnit, tokens: *mut CXToken, - token_count: usize, + token_count: c_uint, } impl<'a> RawTokens<'a> { @@ -993,7 +1002,7 @@ impl<'a> RawTokens<'a> { cursor, tu, tokens, - token_count: token_count.try_into().unwrap(), + token_count, } } @@ -1001,7 +1010,9 @@ impl<'a> RawTokens<'a> { if self.tokens.is_null() { return &[]; } - unsafe { slice::from_raw_parts(self.tokens, self.token_count) } + unsafe { + slice::from_raw_parts(self.tokens, self.token_count.to_usize()) + } } /// Get an iterator over these tokens. @@ -1017,11 +1028,7 @@ 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.try_into().unwrap(), - ); + clang_disposeTokens(self.tu, self.tokens, self.token_count); } } } @@ -1195,15 +1202,21 @@ pub(crate) enum LayoutError { impl From for LayoutError { fn from(val: i32) -> Self { + Self::from(i64::from(val)) + } +} + +impl From for LayoutError { + fn from(val: i64) -> Self { use self::LayoutError::*; - match val { - CXTypeLayoutError_Invalid => Invalid, - CXTypeLayoutError_Incomplete => Incomplete, - CXTypeLayoutError_Dependent => Dependent, - CXTypeLayoutError_NotConstantSize => NotConstantSize, - CXTypeLayoutError_InvalidFieldName => InvalidFieldName, - CXTypeLayoutError_Undeduced => Undeduced, + match val.try_into() { + Ok(CXTypeLayoutError_Invalid) => Invalid, + Ok(CXTypeLayoutError_Incomplete) => Incomplete, + Ok(CXTypeLayoutError_Dependent) => Dependent, + Ok(CXTypeLayoutError_NotConstantSize) => NotConstantSize, + Ok(CXTypeLayoutError_InvalidFieldName) => InvalidFieldName, + Ok(CXTypeLayoutError_Undeduced) => Undeduced, _ => Unknown, } } @@ -1298,9 +1311,11 @@ impl Type { _ => { let size = unsafe { clang_Type_getSizeOf(self.x) }; if size < 0 { - Err(LayoutError::from(i32::try_from(size).unwrap())) + Err(LayoutError::from(size)) } else { - Ok(size.try_into().unwrap()) + Ok(size + .try_into() + .expect("type size does not fit in `usize`")) } } } @@ -1329,9 +1344,11 @@ impl Type { _ => { let alignment = unsafe { clang_Type_getAlignOf(self.x) }; if alignment < 0 { - Err(LayoutError::from(i32::try_from(alignment).unwrap())) + Err(LayoutError::from(alignment)) } else { - Ok(alignment.try_into().unwrap()) + Ok(alignment + .try_into() + .expect("type alignment does not fit in `usize`")) } } } @@ -1351,10 +1368,10 @@ impl Type { /// Get the number of template arguments this type has, or `None` if it is /// not some kind of template. - pub(crate) fn num_template_args(&self) -> Option { - let n = unsafe { clang_Type_getNumTemplateArguments(self.x) }; + pub(crate) fn num_template_args(&self) -> Option { + let n: c_int = unsafe { clang_Type_getNumTemplateArguments(self.x) }; if n >= 0 { - Some(n.try_into().unwrap()) + Some(n as c_uint) } else { debug_assert_eq!(n, -1); None @@ -1378,9 +1395,7 @@ impl Type { self.num_args().ok().map(|num| { (0..num) .map(|i| Type { - x: unsafe { - clang_getArgType(self.x, i.try_into().unwrap()) - }, + x: unsafe { clang_getArgType(self.x, i) }, }) .collect() }) @@ -1389,11 +1404,11 @@ impl Type { /// Given that this type is a function prototype, return the number of arguments it takes. /// /// Returns Err if the type is not a function prototype. - pub(crate) fn num_args(&self) -> Result { + pub(crate) fn num_args(&self) -> Result { unsafe { - let n = clang_getNumArgTypes(self.x); + let n: c_int = clang_getNumArgTypes(self.x); if n >= 0 { - Ok(n.try_into().unwrap()) + Ok(n as c_uint) } else { debug_assert_eq!(n, -1); Err(()) @@ -1439,7 +1454,7 @@ impl Type { pub(crate) fn num_elements(&self) -> Option { let n = unsafe { clang_getNumElements(self.x) }; if n >= 0 { - Some(n.try_into().unwrap()) + Some(n.try_into().expect("array size does not fit in `usize`")) } else { debug_assert_eq!(n, -1); None @@ -1566,8 +1581,8 @@ impl CanonicalTypeDeclaration { /// An iterator for a type's template arguments. pub(crate) struct TypeTemplateArgIterator { x: CXType, - length: usize, - index: usize, + length: c_uint, + index: c_uint, } impl Iterator for TypeTemplateArgIterator { @@ -1577,12 +1592,7 @@ impl Iterator for TypeTemplateArgIterator { let idx = self.index; self.index += 1; Some(Type { - x: unsafe { - clang_Type_getTemplateArgumentAsType( - self.x, - idx.try_into().unwrap(), - ) - }, + x: unsafe { clang_Type_getTemplateArgumentAsType(self.x, idx) }, }) } else { None @@ -1593,7 +1603,7 @@ impl Iterator for TypeTemplateArgIterator { impl ExactSizeIterator for TypeTemplateArgIterator { fn len(&self) -> usize { assert!(self.index <= self.length); - self.length - self.index + (self.length - self.index).to_usize() } } @@ -1617,9 +1627,9 @@ impl SourceLocation { ); ( File { x: file }, - line.try_into().unwrap(), - col.try_into().unwrap(), - off.try_into().unwrap(), + line.to_usize(), + col.to_usize(), + off.to_usize(), ) } } @@ -1659,9 +1669,7 @@ impl Comment { pub(crate) fn get_children(&self) -> CommentChildrenIterator { CommentChildrenIterator { parent: self.x, - length: unsafe { - clang_Comment_getNumChildren(self.x).try_into().unwrap() - }, + length: unsafe { clang_Comment_getNumChildren(self.x) }, index: 0, } } @@ -1676,9 +1684,7 @@ impl Comment { pub(crate) fn get_tag_attrs(&self) -> CommentAttributesIterator { CommentAttributesIterator { x: self.x, - length: unsafe { - clang_HTMLStartTag_getNumAttrs(self.x).try_into().unwrap() - }, + length: unsafe { clang_HTMLStartTag_getNumAttrs(self.x) }, index: 0, } } @@ -1687,8 +1693,8 @@ impl Comment { /// An iterator for a comment's children pub(crate) struct CommentChildrenIterator { parent: CXComment, - length: usize, - index: usize, + length: c_uint, + index: c_uint, } impl Iterator for CommentChildrenIterator { @@ -1698,9 +1704,7 @@ impl Iterator for CommentChildrenIterator { let idx = self.index; self.index += 1; Some(Comment { - x: unsafe { - clang_Comment_getChild(self.parent, idx.try_into().unwrap()) - }, + x: unsafe { clang_Comment_getChild(self.parent, idx) }, }) } else { None @@ -1719,15 +1723,15 @@ pub(crate) struct CommentAttribute { /// An iterator for a comment's attributes pub(crate) struct CommentAttributesIterator { x: CXComment, - length: usize, - index: usize, + length: c_uint, + index: c_uint, } impl Iterator for CommentAttributesIterator { type Item = CommentAttribute; fn next(&mut self) -> Option { if self.index < self.length { - let idx = self.index.try_into().unwrap(); + let idx = self.index; self.index += 1; Some(CommentAttribute { name: unsafe { @@ -1792,10 +1796,7 @@ impl Index { pub(crate) fn new(pch: bool, diag: bool) -> Index { unsafe { Index { - x: clang_createIndex( - pch.try_into().unwrap(), - diag.try_into().unwrap(), - ), + x: clang_createIndex(pch.into(), diag.into()), } } } @@ -1849,9 +1850,9 @@ impl TranslationUnit { ix.x, fname.as_ptr(), c_args.as_ptr(), - c_args.len().try_into().unwrap(), + c_args.len().try_into().expect("too many arguments"), c_unsaved.as_mut_ptr(), - c_unsaved.len().try_into().unwrap(), + c_unsaved.len().try_into().expect("too many unsaved files"), opts, ) }; @@ -1870,7 +1871,7 @@ impl TranslationUnit { let mut diags = vec![]; for i in 0..num { diags.push(Diagnostic { - x: clang_getDiagnostic(self.x, i.try_into().unwrap()), + x: clang_getDiagnostic(self.x, i), }); } diags @@ -2318,7 +2319,7 @@ impl TargetInfo { /// Tries to obtain target information from libclang. pub(crate) fn new(tu: &TranslationUnit) -> Self { let triple; - let pointer_width; + let pointer_width: c_int; unsafe { let ti = clang_getTranslationUnitTargetInfo(tu.x); triple = cxstring_into_string(clang_TargetInfo_getTriple(ti)); @@ -2327,9 +2328,10 @@ impl TargetInfo { } assert!(pointer_width > 0); assert_eq!(pointer_width % 8, 0); + let pointer_width = pointer_width as c_uint; TargetInfo { triple, - pointer_width: pointer_width.try_into().unwrap(), + pointer_width: pointer_width.to_usize(), } } } diff --git a/bindgen/ir/comp.rs b/bindgen/ir/comp.rs index 30030cae00..33bcee4109 100644 --- a/bindgen/ir/comp.rs +++ b/bindgen/ir/comp.rs @@ -591,7 +591,7 @@ where const is_ms_struct: bool = false; for bitfield in raw_bitfields { - let bitfield_width = bitfield.bitfield_width().unwrap() as usize; + let bitfield_width = bitfield.bitfield_width().unwrap(); let bitfield_layout = ctx.resolve_type(bitfield.ty()).layout(ctx).ok_or(())?; let bitfield_size = bitfield_layout.size;