2 mod cast_possible_truncation;
3 mod cast_possible_wrap;
4 mod cast_precision_loss;
5 mod cast_ptr_alignment;
8 mod cast_slice_different_sizes;
10 mod fn_to_numeric_cast;
11 mod fn_to_numeric_cast_any;
12 mod fn_to_numeric_cast_with_truncation;
17 use clippy_utils::is_hir_ty_cfg_dependant;
18 use rustc_hir::{Expr, ExprKind};
19 use rustc_lint::{LateContext, LateLintPass, LintContext};
20 use rustc_middle::lint::in_external_macro;
21 use rustc_semver::RustcVersion;
22 use rustc_session::{declare_tool_lint, impl_lint_pass};
24 declare_clippy_lint! {
26 /// Checks for casts from any numerical to a float type where
27 /// the receiving type cannot store all values from the original type without
28 /// rounding errors. This possible rounding is to be expected, so this lint is
29 /// `Allow` by default.
31 /// Basically, this warns on casting any integer with 32 or more bits to `f32`
32 /// or any 64-bit integer to `f64`.
34 /// ### Why is this bad?
35 /// It's not bad at all. But in some applications it can be
36 /// helpful to know where precision loss can take place. This lint can help find
37 /// those places in the code.
44 #[clippy::version = "pre 1.29.0"]
45 pub CAST_PRECISION_LOSS,
47 "casts that cause loss of precision, e.g., `x as f32` where `x: u64`"
50 declare_clippy_lint! {
52 /// Checks for casts from a signed to an unsigned numerical
53 /// type. In this case, negative values wrap around to large positive values,
54 /// which can be quite surprising in practice. However, as the cast works as
55 /// defined, this lint is `Allow` by default.
57 /// ### Why is this bad?
58 /// Possibly surprising results. You can activate this lint
59 /// as a one-time check to see where numerical wrapping can arise.
64 /// y as u128; // will return 18446744073709551615
66 #[clippy::version = "pre 1.29.0"]
69 "casts from signed types to unsigned types, e.g., `x as u32` where `x: i32`"
72 declare_clippy_lint! {
74 /// Checks for casts between numerical types that may
75 /// truncate large values. This is expected behavior, so the cast is `Allow` by
78 /// ### Why is this bad?
79 /// In some problem domains, it is good practice to avoid
80 /// truncation. This lint can be activated to help assess where additional
81 /// checks could be beneficial.
85 /// fn as_u8(x: u64) -> u8 {
89 #[clippy::version = "pre 1.29.0"]
90 pub CAST_POSSIBLE_TRUNCATION,
92 "casts that may cause truncation of the value, e.g., `x as u8` where `x: u32`, or `x as i32` where `x: f32`"
95 declare_clippy_lint! {
97 /// Checks for casts from an unsigned type to a signed type of
98 /// the same size. Performing such a cast is a 'no-op' for the compiler,
99 /// i.e., nothing is changed at the bit level, and the binary representation of
100 /// the value is reinterpreted. This can cause wrapping if the value is too big
101 /// for the target signed type. However, the cast works as defined, so this lint
102 /// is `Allow` by default.
104 /// ### Why is this bad?
105 /// While such a cast is not bad in itself, the results can
106 /// be surprising when this is not the intended behavior, as demonstrated by the
111 /// u32::MAX as i32; // will yield a value of `-1`
113 #[clippy::version = "pre 1.29.0"]
114 pub CAST_POSSIBLE_WRAP,
116 "casts that may cause wrapping around the value, e.g., `x as i32` where `x: u32` and `x > i32::MAX`"
119 declare_clippy_lint! {
121 /// Checks for casts between numerical types that may
122 /// be replaced by safe conversion functions.
124 /// ### Why is this bad?
125 /// Rust's `as` keyword will perform many kinds of
126 /// conversions, including silently lossy conversions. Conversion functions such
127 /// as `i32::from` will only perform lossless conversions. Using the conversion
128 /// functions prevents conversions from turning into silent lossy conversions if
129 /// the types of the input expressions ever change, and make it easier for
130 /// people reading the code to know that the conversion is lossless.
134 /// fn as_u64(x: u8) -> u64 {
139 /// Using `::from` would look like this:
142 /// fn as_u64(x: u8) -> u64 {
146 #[clippy::version = "pre 1.29.0"]
149 "casts using `as` that are known to be lossless, e.g., `x as u64` where `x: u8`"
152 declare_clippy_lint! {
154 /// Checks for casts to the same type, casts of int literals to integer types
155 /// and casts of float literals to float types.
157 /// ### Why is this bad?
158 /// It's just unnecessary.
162 /// let _ = 2i32 as i32;
163 /// let _ = 0.5 as f32;
172 #[clippy::version = "pre 1.29.0"]
173 pub UNNECESSARY_CAST,
175 "cast to the same type, e.g., `x as i32` where `x: i32`"
178 declare_clippy_lint! {
180 /// Checks for casts, using `as` or `pointer::cast`,
181 /// from a less-strictly-aligned pointer to a more-strictly-aligned pointer
183 /// ### Why is this bad?
184 /// Dereferencing the resulting pointer may be undefined
187 /// ### Known problems
188 /// Using `std::ptr::read_unaligned` and `std::ptr::write_unaligned` or similar
189 /// on the resulting pointer is fine. Is over-zealous: Casts with manual alignment checks or casts like
190 /// u64-> u8 -> u16 can be fine. Miri is able to do a more in-depth analysis.
194 /// let _ = (&1u8 as *const u8) as *const u16;
195 /// let _ = (&mut 1u8 as *mut u8) as *mut u16;
197 /// (&1u8 as *const u8).cast::<u16>();
198 /// (&mut 1u8 as *mut u8).cast::<u16>();
200 #[clippy::version = "pre 1.29.0"]
201 pub CAST_PTR_ALIGNMENT,
203 "cast from a pointer to a more-strictly-aligned pointer"
206 declare_clippy_lint! {
208 /// Checks for casts of function pointers to something other than usize
210 /// ### Why is this bad?
211 /// Casting a function pointer to anything other than usize/isize is not portable across
212 /// architectures, because you end up losing bits if the target type is too small or end up with a
213 /// bunch of extra bits that waste space and add more instructions to the final binary than
214 /// strictly necessary for the problem
216 /// Casting to isize also doesn't make sense since there are no signed addresses.
221 /// fn fun() -> i32 { 1 }
222 /// let a = fun as i64;
225 /// fn fun2() -> i32 { 1 }
226 /// let a = fun2 as usize;
228 #[clippy::version = "pre 1.29.0"]
229 pub FN_TO_NUMERIC_CAST,
231 "casting a function pointer to a numeric type other than usize"
234 declare_clippy_lint! {
236 /// Checks for casts of a function pointer to a numeric type not wide enough to
239 /// ### Why is this bad?
240 /// Such a cast discards some bits of the function's address. If this is intended, it would be more
241 /// clearly expressed by casting to usize first, then casting the usize to the intended type (with
242 /// a comment) to perform the truncation.
247 /// fn fn1() -> i16 {
250 /// let _ = fn1 as i32;
252 /// // Better: Cast to usize first, then comment with the reason for the truncation
253 /// fn fn2() -> i16 {
256 /// let fn_ptr = fn2 as usize;
257 /// let fn_ptr_truncated = fn_ptr as i32;
259 #[clippy::version = "pre 1.29.0"]
260 pub FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
262 "casting a function pointer to a numeric type not wide enough to store the address"
265 declare_clippy_lint! {
267 /// Checks for casts of a function pointer to any integer type.
269 /// ### Why is this bad?
270 /// Casting a function pointer to an integer can have surprising results and can occur
271 /// accidentally if parantheses are omitted from a function call. If you aren't doing anything
272 /// low-level with function pointers then you can opt-out of casting functions to integers in
273 /// order to avoid mistakes. Alternatively, you can use this lint to audit all uses of function
274 /// pointer casts in your code.
278 /// // Bad: fn1 is cast as `usize`
279 /// fn fn1() -> u16 {
282 /// let _ = fn1 as usize;
284 /// // Good: maybe you intended to call the function?
285 /// fn fn2() -> u16 {
288 /// let _ = fn2() as usize;
290 /// // Good: maybe you intended to cast it to a function type?
291 /// fn fn3() -> u16 {
294 /// let _ = fn3 as fn() -> u16;
296 #[clippy::version = "1.58.0"]
297 pub FN_TO_NUMERIC_CAST_ANY,
299 "casting a function pointer to any integer type"
302 declare_clippy_lint! {
304 /// Checks for casts of `&T` to `&mut T` anywhere in the code.
306 /// ### Why is this bad?
307 /// It’s basically guaranteed to be undefined behaviour.
308 /// `UnsafeCell` is the only way to obtain aliasable data that is considered
315 /// *(r as *const _ as *mut _) += 1;
320 /// Instead consider using interior mutability types.
323 /// use std::cell::UnsafeCell;
325 /// fn x(r: &UnsafeCell<i32>) {
331 #[clippy::version = "1.33.0"]
334 "a cast of reference to a mutable pointer"
337 declare_clippy_lint! {
339 /// Checks for expressions where a character literal is cast
340 /// to `u8` and suggests using a byte literal instead.
342 /// ### Why is this bad?
343 /// In general, casting values to smaller types is
344 /// error-prone and should be avoided where possible. In the particular case of
345 /// converting a character literal to u8, it is easy to avoid by just using a
346 /// byte literal instead. As an added bonus, `b'a'` is even slightly shorter
347 /// than `'a' as u8`.
354 /// A better version, using the byte literal:
359 #[clippy::version = "pre 1.29.0"]
362 "casting a character literal to `u8` truncates"
365 declare_clippy_lint! {
367 /// Checks for `as` casts between raw pointers without changing its mutability,
368 /// namely `*const T` to `*const U` and `*mut T` to `*mut U`.
370 /// ### Why is this bad?
371 /// Though `as` casts between raw pointers is not terrible, `pointer::cast` is safer because
372 /// it cannot accidentally change the pointer's mutability nor cast the pointer to other types like `usize`.
376 /// let ptr: *const u32 = &42_u32;
377 /// let mut_ptr: *mut u32 = &mut 42_u32;
378 /// let _ = ptr as *const i32;
379 /// let _ = mut_ptr as *mut i32;
383 /// let ptr: *const u32 = &42_u32;
384 /// let mut_ptr: *mut u32 = &mut 42_u32;
385 /// let _ = ptr.cast::<i32>();
386 /// let _ = mut_ptr.cast::<i32>();
388 #[clippy::version = "1.51.0"]
391 "casting using `as` from and to raw pointers that doesn't change its mutability, where `pointer::cast` could take the place of `as`"
394 declare_clippy_lint! {
396 /// Checks for casts from an enum type to an integral type which will definitely truncate the
399 /// ### Why is this bad?
400 /// The resulting integral value will not match the value of the variant it came from.
404 /// enum E { X = 256 };
405 /// let _ = E::X as u8;
407 #[clippy::version = "1.60.0"]
408 pub CAST_ENUM_TRUNCATION,
410 "casts from an enum type to an integral type which will truncate the value"
413 declare_clippy_lint! {
414 /// Checks for `as` casts between raw pointers to slices with differently sized elements.
416 /// ### Why is this bad?
417 /// The produced raw pointer to a slice does not update its length metadata. The produced
418 /// pointer will point to a different number of bytes than the original pointer because the
419 /// length metadata of a raw slice pointer is in elements rather than bytes.
420 /// Producing a slice reference from the raw pointer will either create a slice with
421 /// less data (which can be surprising) or create a slice with more data and cause Undefined Behavior.
426 /// let a = [1_i32, 2, 3, 4];
427 /// let p = &a as *const [i32] as *const [u8];
429 /// println!("{:?}", &*p);
432 /// // Undefined Behavior (note: also potential alignment issues)
434 /// let a = [1_u8, 2, 3, 4];
435 /// let p = &a as *const [u8] as *const [u32];
437 /// println!("{:?}", &*p);
440 /// Instead use `ptr::slice_from_raw_parts` to construct a slice from a data pointer and the correct length
442 /// let a = [1_i32, 2, 3, 4];
443 /// let old_ptr = &a as *const [i32];
444 /// // The data pointer is cast to a pointer to the target `u8` not `[u8]`
445 /// // The length comes from the known length of 4 i32s times the 4 bytes per i32
446 /// let new_ptr = core::ptr::slice_from_raw_parts(old_ptr as *const u8, 16);
448 /// println!("{:?}", &*new_ptr);
451 #[clippy::version = "1.60.0"]
452 pub CAST_SLICE_DIFFERENT_SIZES,
454 "casting using `as` between raw pointers to slices of types with different sizes"
458 msrv: Option<RustcVersion>,
463 pub fn new(msrv: Option<RustcVersion>) -> Self {
468 impl_lint_pass!(Casts => [
471 CAST_POSSIBLE_TRUNCATION,
476 CAST_SLICE_DIFFERENT_SIZES,
478 FN_TO_NUMERIC_CAST_ANY,
480 FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
483 CAST_ENUM_TRUNCATION,
486 impl<'tcx> LateLintPass<'tcx> for Casts {
487 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
488 if !in_external_macro(cx.sess(), expr.span) {
489 ptr_as_ptr::check(cx, expr, &self.msrv);
492 if expr.span.from_expansion() {
496 if let ExprKind::Cast(cast_expr, cast_to) = expr.kind {
497 if is_hir_ty_cfg_dependant(cx, cast_to) {
500 let (cast_from, cast_to) = (
501 cx.typeck_results().expr_ty(cast_expr),
502 cx.typeck_results().expr_ty(expr),
505 if unnecessary_cast::check(cx, expr, cast_expr, cast_from, cast_to) {
509 fn_to_numeric_cast_any::check(cx, expr, cast_expr, cast_from, cast_to);
510 fn_to_numeric_cast::check(cx, expr, cast_expr, cast_from, cast_to);
511 fn_to_numeric_cast_with_truncation::check(cx, expr, cast_expr, cast_from, cast_to);
513 if cast_to.is_numeric() && !in_external_macro(cx.sess(), expr.span) {
514 cast_possible_truncation::check(cx, expr, cast_expr, cast_from, cast_to);
515 if cast_from.is_numeric() {
516 cast_possible_wrap::check(cx, expr, cast_from, cast_to);
517 cast_precision_loss::check(cx, expr, cast_from, cast_to);
518 cast_sign_loss::check(cx, expr, cast_expr, cast_from, cast_to);
520 cast_lossless::check(cx, expr, cast_expr, cast_from, cast_to, &self.msrv);
524 cast_ref_to_mut::check(cx, expr);
525 cast_ptr_alignment::check(cx, expr);
526 char_lit_as_u8::check(cx, expr);
527 ptr_as_ptr::check(cx, expr, &self.msrv);
528 cast_slice_different_sizes::check(cx, expr, &self.msrv);
531 extract_msrv_attr!(LateContext);