1 use clippy_utils::diagnostics::span_lint;
2 use clippy_utils::expr_or_init;
3 use clippy_utils::ty::is_isize_or_usize;
4 use rustc_hir::{Expr, ExprKind};
5 use rustc_lint::LateContext;
6 use rustc_middle::ty::{self, FloatTy, Ty};
8 use super::{utils, CAST_POSSIBLE_TRUNCATION};
10 pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_expr: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
11 // do not lint if cast comes from a `signum` function
12 if let ExprKind::MethodCall(path, ..) = expr_or_init(cx, cast_expr).kind {
13 if path.ident.name.as_str() == "signum" {
18 let msg = match (cast_from.is_integral(), cast_to.is_integral()) {
20 let from_nbits = utils::int_ty_to_nbits(cast_from, cx.tcx);
21 let to_nbits = utils::int_ty_to_nbits(cast_to, cx.tcx);
23 let (should_lint, suffix) = match (is_isize_or_usize(cast_from), is_isize_or_usize(cast_to)) {
24 (true, true) | (false, false) => (to_nbits < from_nbits, ""),
28 " on targets with 64-bit wide pointers"
33 (false, true) => (from_nbits == 64, " on targets with 32-bit wide pointers"),
41 "casting `{}` to `{}` may truncate the value{}",
42 cast_from, cast_to, suffix,
47 format!("casting `{}` to `{}` may truncate the value", cast_from, cast_to)
51 if matches!(cast_from.kind(), &ty::Float(FloatTy::F64))
52 && matches!(cast_to.kind(), &ty::Float(FloatTy::F32))
54 "casting `f64` to `f32` may truncate the value".to_string()
61 span_lint(cx, CAST_POSSIBLE_TRUNCATION, expr.span, &msg);