]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/casts/cast_possible_truncation.rs
Auto merge of #6907 - camsteffen:ty-utils, r=flip1995
[rust.git] / clippy_lints / src / casts / cast_possible_truncation.rs
1 use clippy_utils::ty::is_isize_or_usize;
2 use rustc_hir::Expr;
3 use rustc_lint::LateContext;
4 use rustc_middle::ty::{self, FloatTy, Ty};
5
6 use crate::utils::span_lint;
7
8 use super::{utils, CAST_POSSIBLE_TRUNCATION};
9
10 pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
11     let msg = match (cast_from.is_integral(), cast_to.is_integral()) {
12         (true, true) => {
13             let from_nbits = utils::int_ty_to_nbits(cast_from, cx.tcx);
14             let to_nbits = utils::int_ty_to_nbits(cast_to, cx.tcx);
15
16             let (should_lint, suffix) = match (is_isize_or_usize(cast_from), is_isize_or_usize(cast_to)) {
17                 (true, true) | (false, false) => (to_nbits < from_nbits, ""),
18                 (true, false) => (
19                     to_nbits <= 32,
20                     if to_nbits == 32 {
21                         " on targets with 64-bit wide pointers"
22                     } else {
23                         ""
24                     },
25                 ),
26                 (false, true) => (from_nbits == 64, " on targets with 32-bit wide pointers"),
27             };
28
29             if !should_lint {
30                 return;
31             }
32
33             format!(
34                 "casting `{}` to `{}` may truncate the value{}",
35                 cast_from, cast_to, suffix,
36             )
37         },
38
39         (false, true) => {
40             format!("casting `{}` to `{}` may truncate the value", cast_from, cast_to)
41         },
42
43         (_, _) => {
44             if matches!(cast_from.kind(), &ty::Float(FloatTy::F64))
45                 && matches!(cast_to.kind(), &ty::Float(FloatTy::F32))
46             {
47                 "casting `f64` to `f32` may truncate the value".to_string()
48             } else {
49                 return;
50             }
51         },
52     };
53
54     span_lint(cx, CAST_POSSIBLE_TRUNCATION, expr.span, &msg);
55 }