Skip to content

Commit 44d3c93

Browse files
authored
Merge pull request rust-lang#4329 from RalfJung/no-casts
enable clippy::as_conversions to fully rule out as-casts
2 parents d5240cc + 446fa22 commit 44d3c93

File tree

24 files changed

+83
-68
lines changed

24 files changed

+83
-68
lines changed

src/tools/miri/src/alloc_addresses/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,7 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> {
168168
AllocKind::Dead => unreachable!(),
169169
};
170170
// We don't have to expose this pointer yet, we do that in `prepare_for_native_call`.
171-
return interp_ok(base_ptr.addr().try_into().unwrap());
171+
return interp_ok(base_ptr.addr().to_u64());
172172
}
173173
// We are not in native lib mode, so we control the addresses ourselves.
174174
if let Some((reuse_addr, clock)) = global_state.reuse.take_addr(

src/tools/miri/src/alloc_addresses/reuse_pool.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ use rand::Rng;
44
use rustc_abi::{Align, Size};
55

66
use crate::concurrency::VClock;
7+
use crate::helpers::ToUsize as _;
78
use crate::{MemoryKind, MiriConfig, ThreadId};
89

910
const MAX_POOL_SIZE: usize = 64;
@@ -46,7 +47,7 @@ impl ReusePool {
4647
}
4748

4849
fn subpool(&mut self, align: Align) -> &mut Vec<(u64, Size, ThreadId, VClock)> {
49-
let pool_idx: usize = align.bytes().trailing_zeros().try_into().unwrap();
50+
let pool_idx: usize = align.bytes().trailing_zeros().to_usize();
5051
if self.pool.len() <= pool_idx {
5152
self.pool.resize(pool_idx + 1, Vec::new());
5253
}

src/tools/miri/src/alloc_bytes.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ use std::{alloc, slice};
55
use rustc_abi::{Align, Size};
66
use rustc_middle::mir::interpret::AllocBytes;
77

8+
use crate::helpers::ToU64 as _;
9+
810
/// Allocation bytes that explicitly handle the layout of the data they're storing.
911
/// This is necessary to interface with native code that accesses the program store in Miri.
1012
#[derive(Debug)]
@@ -21,7 +23,7 @@ pub struct MiriAllocBytes {
2123
impl Clone for MiriAllocBytes {
2224
fn clone(&self) -> Self {
2325
let bytes: Cow<'_, [u8]> = Cow::Borrowed(self);
24-
let align = Align::from_bytes(self.layout.align().try_into().unwrap()).unwrap();
26+
let align = Align::from_bytes(self.layout.align().to_u64()).unwrap();
2527
MiriAllocBytes::from_bytes(bytes, align)
2628
}
2729
}
@@ -90,7 +92,7 @@ impl AllocBytes for MiriAllocBytes {
9092
let align = align.bytes();
9193
// SAFETY: `alloc_fn` will only be used with `size != 0`.
9294
let alloc_fn = |layout| unsafe { alloc::alloc(layout) };
93-
let alloc_bytes = MiriAllocBytes::alloc_with(size.try_into().unwrap(), align, alloc_fn)
95+
let alloc_bytes = MiriAllocBytes::alloc_with(size.to_u64(), align, alloc_fn)
9496
.unwrap_or_else(|()| {
9597
panic!("Miri ran out of memory: cannot create allocation of {size} bytes")
9698
});

src/tools/miri/src/borrow_tracker/tree_borrows/unimap.rs

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ use std::mem;
1717

1818
use rustc_data_structures::fx::FxHashMap;
1919

20+
use crate::helpers::ToUsize;
21+
2022
/// Intermediate key between a UniKeyMap and a UniValMap.
2123
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2224
pub struct UniIndex {
@@ -158,7 +160,7 @@ where
158160
impl<V> UniValMap<V> {
159161
/// Whether this index has an associated value.
160162
pub fn contains_idx(&self, idx: UniIndex) -> bool {
161-
self.data.get(idx.idx as usize).and_then(Option::as_ref).is_some()
163+
self.data.get(idx.idx.to_usize()).and_then(Option::as_ref).is_some()
162164
}
163165

164166
/// Reserve enough space to insert the value at the right index.
@@ -174,29 +176,29 @@ impl<V> UniValMap<V> {
174176

175177
/// Assign a value to the index. Permanently overwrites any previous value.
176178
pub fn insert(&mut self, idx: UniIndex, val: V) {
177-
self.extend_to_length(idx.idx as usize + 1);
178-
self.data[idx.idx as usize] = Some(val)
179+
self.extend_to_length(idx.idx.to_usize() + 1);
180+
self.data[idx.idx.to_usize()] = Some(val)
179181
}
180182

181183
/// Get the value at this index, if it exists.
182184
pub fn get(&self, idx: UniIndex) -> Option<&V> {
183-
self.data.get(idx.idx as usize).and_then(Option::as_ref)
185+
self.data.get(idx.idx.to_usize()).and_then(Option::as_ref)
184186
}
185187

186188
/// Get the value at this index mutably, if it exists.
187189
pub fn get_mut(&mut self, idx: UniIndex) -> Option<&mut V> {
188-
self.data.get_mut(idx.idx as usize).and_then(Option::as_mut)
190+
self.data.get_mut(idx.idx.to_usize()).and_then(Option::as_mut)
189191
}
190192

191193
/// Delete any value associated with this index.
192194
/// Returns None if the value was not present, otherwise
193195
/// returns the previously stored value.
194196
pub fn remove(&mut self, idx: UniIndex) -> Option<V> {
195-
if idx.idx as usize >= self.data.len() {
197+
if idx.idx.to_usize() >= self.data.len() {
196198
return None;
197199
}
198200
let mut res = None;
199-
mem::swap(&mut res, &mut self.data[idx.idx as usize]);
201+
mem::swap(&mut res, &mut self.data[idx.idx.to_usize()]);
200202
res
201203
}
202204
}
@@ -209,8 +211,8 @@ pub struct UniEntry<'a, V> {
209211
impl<'a, V> UniValMap<V> {
210212
/// Get a wrapper around a mutable access to the value corresponding to `idx`.
211213
pub fn entry(&'a mut self, idx: UniIndex) -> UniEntry<'a, V> {
212-
self.extend_to_length(idx.idx as usize + 1);
213-
UniEntry { inner: &mut self.data[idx.idx as usize] }
214+
self.extend_to_length(idx.idx.to_usize() + 1);
215+
UniEntry { inner: &mut self.data[idx.idx.to_usize()] }
214216
}
215217
}
216218

src/tools/miri/src/concurrency/cpu_affinity.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ impl CpuAffinityMask {
2525
let mut this = Self([0; Self::CPU_MASK_BYTES]);
2626

2727
// the default affinity mask includes only the available CPUs
28-
for i in 0..cpu_count as usize {
28+
for i in 0..cpu_count.to_usize() {
2929
this.set(cx, i);
3030
}
3131

src/tools/miri/src/concurrency/vector_clock.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ use rustc_span::{DUMMY_SP, Span, SpanData};
77
use smallvec::SmallVec;
88

99
use super::data_race::NaReadType;
10+
use crate::helpers::ToUsize;
1011

1112
/// A vector clock index, this is associated with a thread id
1213
/// but in some cases one vector index may be shared with
@@ -157,7 +158,7 @@ impl VClock {
157158

158159
#[inline]
159160
pub(super) fn index_mut(&mut self, index: VectorIdx) -> &mut VTimestamp {
160-
self.0.as_mut_slice().get_mut(index.to_u32() as usize).unwrap()
161+
self.0.as_mut_slice().get_mut(index.to_u32().to_usize()).unwrap()
161162
}
162163

163164
/// Get a mutable slice to the internal vector with minimum `min_len`
@@ -420,7 +421,7 @@ impl Index<VectorIdx> for VClock {
420421

421422
#[inline]
422423
fn index(&self, index: VectorIdx) -> &VTimestamp {
423-
self.as_slice().get(index.to_u32() as usize).unwrap_or(&VTimestamp::ZERO)
424+
self.as_slice().get(index.to_u32().to_usize()).unwrap_or(&VTimestamp::ZERO)
424425
}
425426
}
426427

src/tools/miri/src/helpers.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1412,3 +1412,26 @@ pub(crate) fn windows_check_buffer_size((success, len): (bool, u64)) -> u32 {
14121412
u32::try_from(len).unwrap()
14131413
}
14141414
}
1415+
1416+
/// We don't support 16-bit systems, so let's have ergonomic conversion from `u32` to `usize`.
1417+
pub trait ToUsize {
1418+
fn to_usize(self) -> usize;
1419+
}
1420+
1421+
impl ToUsize for u32 {
1422+
fn to_usize(self) -> usize {
1423+
self.try_into().unwrap()
1424+
}
1425+
}
1426+
1427+
/// Similarly, a maximum address size of `u64` is assumed widely here, so let's have ergonomic
1428+
/// converion from `usize` to `u64`.
1429+
pub trait ToU64 {
1430+
fn to_u64(self) -> u64;
1431+
}
1432+
1433+
impl ToU64 for usize {
1434+
fn to_u64(self) -> u64 {
1435+
self.try_into().unwrap()
1436+
}
1437+
}

src/tools/miri/src/intrinsics/simd.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -634,7 +634,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
634634
let index_len = index.len();
635635

636636
assert_eq!(left_len, right_len);
637-
assert_eq!(index_len as u64, dest_len);
637+
assert_eq!(u64::try_from(index_len).unwrap(), dest_len);
638638

639639
for i in 0..dest_len {
640640
let src_index: u64 =

src/tools/miri/src/lib.rs

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -41,14 +41,7 @@
4141
rustc::potential_query_instability,
4242
rustc::untranslatable_diagnostic,
4343
)]
44-
#![warn(
45-
rust_2018_idioms,
46-
unqualified_local_imports,
47-
clippy::cast_possible_wrap, // unsigned -> signed
48-
clippy::cast_sign_loss, // signed -> unsigned
49-
clippy::cast_lossless,
50-
clippy::cast_possible_truncation,
51-
)]
44+
#![warn(rust_2018_idioms, unqualified_local_imports, clippy::as_conversions)]
5245
// Needed for rustdoc from bootstrap (with `-Znormalize-docs`).
5346
#![recursion_limit = "256"]
5447

@@ -140,7 +133,7 @@ pub use crate::eval::{
140133
AlignmentCheck, BacktraceStyle, IsolatedOp, MiriConfig, MiriEntryFnType, RejectOpWith,
141134
ValidationMode, create_ecx, eval_entry,
142135
};
143-
pub use crate::helpers::{AccessKind, EvalContextExt as _};
136+
pub use crate::helpers::{AccessKind, EvalContextExt as _, ToU64 as _, ToUsize as _};
144137
pub use crate::intrinsics::EvalContextExt as _;
145138
pub use crate::machine::{
146139
AllocExtra, DynMachineCallback, FrameExtra, MachineCallback, MemoryKind, MiriInterpCx,

src/tools/miri/src/shims/backtrace.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
2525

2626
let frame_count = this.active_thread_stack().len();
2727

28-
this.write_scalar(Scalar::from_target_usize(frame_count.try_into().unwrap(), this), dest)
28+
this.write_scalar(Scalar::from_target_usize(frame_count.to_u64(), this), dest)
2929
}
3030

3131
fn handle_miri_get_backtrace(
@@ -70,7 +70,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
7070
}
7171
1 =>
7272
for (i, ptr) in ptrs.into_iter().enumerate() {
73-
let offset = ptr_layout.size.checked_mul(i.try_into().unwrap(), this).unwrap();
73+
let offset = ptr_layout.size.checked_mul(i.to_u64(), this).unwrap();
7474

7575
let op_place = buf_place.offset(offset, ptr_layout, this)?;
7676

@@ -158,11 +158,11 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
158158
}
159159
1 => {
160160
this.write_scalar(
161-
Scalar::from_target_usize(name.len().try_into().unwrap(), this),
161+
Scalar::from_target_usize(name.len().to_u64(), this),
162162
&this.project_field(dest, 0)?,
163163
)?;
164164
this.write_scalar(
165-
Scalar::from_target_usize(filename.len().try_into().unwrap(), this),
165+
Scalar::from_target_usize(filename.len().to_u64(), this),
166166
&this.project_field(dest, 1)?,
167167
)?;
168168
}

src/tools/miri/src/shims/foreign_items.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -639,7 +639,7 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> {
639639
let val = this.read_scalar(val)?.to_i32()?;
640640
let num = this.read_target_usize(num)?;
641641
// The docs say val is "interpreted as unsigned char".
642-
#[expect(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
642+
#[expect(clippy::as_conversions)]
643643
let val = val as u8;
644644

645645
// C requires that this must always be a valid pointer (C18 §7.1.4).
@@ -665,7 +665,7 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> {
665665
let val = this.read_scalar(val)?.to_i32()?;
666666
let num = this.read_target_usize(num)?;
667667
// The docs say val is "interpreted as unsigned char".
668-
#[expect(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
668+
#[expect(clippy::as_conversions)]
669669
let val = val as u8;
670670

671671
// C requires that this must always be a valid pointer (C18 §7.1.4).
@@ -676,7 +676,7 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> {
676676
.iter()
677677
.position(|&c| c == val);
678678
if let Some(idx) = idx {
679-
let new_ptr = ptr.wrapping_offset(Size::from_bytes(idx as u64), this);
679+
let new_ptr = ptr.wrapping_offset(Size::from_bytes(idx), this);
680680
this.write_pointer(new_ptr, dest)?;
681681
} else {
682682
this.write_null(dest)?;

src/tools/miri/src/shims/native_lib.rs

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -94,14 +94,10 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> {
9494
// Try getting the function from the shared library.
9595
// On windows `_lib_path` will be unused, hence the name starting with `_`.
9696
let (lib, _lib_path) = this.machine.native_lib.as_ref().unwrap();
97-
let func: libloading::Symbol<'_, unsafe extern "C" fn()> = unsafe {
98-
match lib.get(link_name.as_str().as_bytes()) {
99-
Ok(x) => x,
100-
Err(_) => {
101-
return None;
102-
}
103-
}
104-
};
97+
let func: libloading::Symbol<'_, unsafe extern "C" fn()> =
98+
unsafe { lib.get(link_name.as_str().as_bytes()).ok()? };
99+
#[expect(clippy::as_conversions)] // fn-ptr to raw-ptr cast needs `as`.
100+
let fn_ptr = *func.deref() as *mut std::ffi::c_void;
105101

106102
// FIXME: this is a hack!
107103
// The `libloading` crate will automatically load system libraries like `libc`.
@@ -116,7 +112,7 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> {
116112
// using the `libc` crate where this interface is public.
117113
let mut info = std::mem::MaybeUninit::<libc::Dl_info>::uninit();
118114
unsafe {
119-
if libc::dladdr(*func.deref() as *const _, info.as_mut_ptr()) != 0 {
115+
if libc::dladdr(fn_ptr, info.as_mut_ptr()) != 0 {
120116
let info = info.assume_init();
121117
#[cfg(target_os = "cygwin")]
122118
let fname_ptr = info.dli_fname.as_ptr();
@@ -129,8 +125,9 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> {
129125
}
130126
}
131127
}
128+
132129
// Return a pointer to the function.
133-
Some(CodePtr(*func.deref() as *mut _))
130+
Some(CodePtr(fn_ptr))
134131
}
135132
}
136133

src/tools/miri/src/shims/unix/android/thread.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use crate::helpers::check_min_vararg_count;
77
use crate::shims::unix::thread::{EvalContextExt as _, ThreadNameResult};
88
use crate::*;
99

10-
const TASK_COMM_LEN: usize = 16;
10+
const TASK_COMM_LEN: u64 = 16;
1111

1212
pub fn prctl<'tcx>(
1313
ecx: &mut MiriInterpCx<'tcx>,
@@ -38,7 +38,7 @@ pub fn prctl<'tcx>(
3838
let [name] = check_min_vararg_count("prctl(PR_GET_NAME, ...)", varargs)?;
3939
let name = ecx.read_scalar(name)?;
4040
let thread = ecx.pthread_self()?;
41-
let len = Scalar::from_target_usize(TASK_COMM_LEN as u64, ecx);
41+
let len = Scalar::from_target_usize(TASK_COMM_LEN, ecx);
4242
ecx.check_ptr_access(
4343
name.to_pointer(ecx)?,
4444
Size::from_bytes(TASK_COMM_LEN),

src/tools/miri/src/shims/unix/freebsd/foreign_items.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
2424
// Threading
2525
"pthread_setname_np" => {
2626
let [thread, name] = this.check_shim(abi, Conv::C, link_name, args)?;
27-
let max_len = usize::MAX; // FreeBSD does not seem to have a limit.
27+
let max_len = u64::MAX; // FreeBSD does not seem to have a limit.
2828
let res = match this.pthread_setname_np(
2929
this.read_scalar(thread)?,
3030
this.read_scalar(name)?,

src/tools/miri/src/shims/unix/fs.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -121,13 +121,13 @@ impl UnixFileDescription for FileHandle {
121121
use std::os::windows::io::AsRawHandle;
122122

123123
use windows_sys::Win32::Foundation::{
124-
ERROR_IO_PENDING, ERROR_LOCK_VIOLATION, FALSE, HANDLE, TRUE,
124+
ERROR_IO_PENDING, ERROR_LOCK_VIOLATION, FALSE, TRUE,
125125
};
126126
use windows_sys::Win32::Storage::FileSystem::{
127127
LOCKFILE_EXCLUSIVE_LOCK, LOCKFILE_FAIL_IMMEDIATELY, LockFileEx, UnlockFile,
128128
};
129129

130-
let fh = self.file.as_raw_handle() as HANDLE;
130+
let fh = self.file.as_raw_handle();
131131

132132
use FlockOp::*;
133133
let (ret, lock_nb) = match op {

src/tools/miri/src/shims/unix/linux/foreign_items.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use crate::*;
1414
// The documentation of glibc complains that the kernel never exposes
1515
// TASK_COMM_LEN through the headers, so it's assumed to always be 16 bytes
1616
// long including a null terminator.
17-
const TASK_COMM_LEN: usize = 16;
17+
const TASK_COMM_LEN: u64 = 16;
1818

1919
pub fn is_dyn_sym(name: &str) -> bool {
2020
matches!(name, "statx")
@@ -96,7 +96,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
9696
// In case of glibc, the length of the output buffer must
9797
// be not shorter than TASK_COMM_LEN.
9898
let len = this.read_scalar(len)?;
99-
let res = if len.to_target_usize(this)? >= TASK_COMM_LEN as u64 {
99+
let res = if len.to_target_usize(this)? >= TASK_COMM_LEN {
100100
match this.pthread_getname_np(
101101
this.read_scalar(thread)?,
102102
this.read_scalar(name)?,

src/tools/miri/src/shims/unix/macos/foreign_items.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
186186
let res = match this.pthread_setname_np(
187187
thread,
188188
this.read_scalar(name)?,
189-
this.eval_libc("MAXTHREADNAMESIZE").to_target_usize(this)?.try_into().unwrap(),
189+
this.eval_libc("MAXTHREADNAMESIZE").to_target_usize(this)?,
190190
/* truncate */ false,
191191
)? {
192192
ThreadNameResult::Ok => Scalar::from_u32(0),

0 commit comments

Comments
 (0)