1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::in_constant;
3 use clippy_utils::source::snippet_opt;
4 use clippy_utils::ty::is_isize_or_usize;
5 use rustc_errors::Applicability;
6 use rustc_hir::{Expr, ExprKind};
7 use rustc_lint::LateContext;
8 use rustc_middle::ty::{self, FloatTy, Ty};
10 use super::{utils, CAST_LOSSLESS};
12 pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
13 if !should_lint(cx, expr, cast_from, cast_to) {
17 // The suggestion is to use a function call, so if the original expression
18 // has parens on the outside, they are no longer needed.
19 let mut applicability = Applicability::MachineApplicable;
20 let opt = snippet_opt(cx, cast_op.span);
21 let sugg = opt.as_ref().map_or_else(
23 applicability = Applicability::HasPlaceholders;
27 if should_strip_parens(cast_op, snip) {
28 &snip[1..snip.len() - 1]
40 "casting `{}` to `{}` may become silently lossy if you later change the type",
44 format!("{}::from({})", cast_to, sugg),
49 fn should_lint(cx: &LateContext<'_>, expr: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) -> bool {
50 // Do not suggest using From in consts/statics until it is valid to do so (see #2267).
51 if in_constant(cx, expr.hir_id) {
55 match (cast_from.is_integral(), cast_to.is_integral()) {
57 let cast_signed_to_unsigned = cast_from.is_signed() && !cast_to.is_signed();
58 let from_nbits = utils::int_ty_to_nbits(cast_from, cx.tcx);
59 let to_nbits = utils::int_ty_to_nbits(cast_to, cx.tcx);
60 !is_isize_or_usize(cast_from)
61 && !is_isize_or_usize(cast_to)
62 && from_nbits < to_nbits
63 && !cast_signed_to_unsigned
67 let from_nbits = utils::int_ty_to_nbits(cast_from, cx.tcx);
68 let to_nbits = if let ty::Float(FloatTy::F32) = cast_to.kind() {
77 matches!(cast_from.kind(), ty::Float(FloatTy::F32)) && matches!(cast_to.kind(), ty::Float(FloatTy::F64))
82 fn should_strip_parens(cast_expr: &Expr<'_>, snip: &str) -> bool {
83 if let ExprKind::Binary(_, _, _) = cast_expr.kind {
84 if snip.starts_with('(') && snip.ends_with(')') {