]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/casts/unnecessary_cast.rs
Auto merge of #6805 - matthiaskrgr:uca_nopub_6803, r=flip1995
[rust.git] / clippy_lints / src / casts / unnecessary_cast.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::source::snippet_opt;
3 use if_chain::if_chain;
4 use rustc_ast::{LitFloatType, LitIntType, LitKind};
5 use rustc_errors::Applicability;
6 use rustc_hir::{Expr, ExprKind, Lit, UnOp};
7 use rustc_lint::{LateContext, LintContext};
8 use rustc_middle::lint::in_external_macro;
9 use rustc_middle::ty::{self, FloatTy, InferTy, Ty};
10
11 use crate::utils::numeric_literal::NumericLiteral;
12
13 use super::UNNECESSARY_CAST;
14
15 pub(super) fn check(
16     cx: &LateContext<'_>,
17     expr: &Expr<'_>,
18     cast_expr: &Expr<'_>,
19     cast_from: Ty<'_>,
20     cast_to: Ty<'_>,
21 ) -> bool {
22     if let Some(lit) = get_numeric_literal(cast_expr) {
23         let literal_str = snippet_opt(cx, cast_expr.span).unwrap_or_default();
24
25         if_chain! {
26             if let LitKind::Int(n, _) = lit.node;
27             if let Some(src) = snippet_opt(cx, lit.span);
28             if cast_to.is_floating_point();
29             if let Some(num_lit) = NumericLiteral::from_lit_kind(&src, &lit.node);
30             let from_nbits = 128 - n.leading_zeros();
31             let to_nbits = fp_ty_mantissa_nbits(cast_to);
32             if from_nbits != 0 && to_nbits != 0 && from_nbits <= to_nbits && num_lit.is_decimal();
33             then {
34                 let literal_str = if is_unary_neg(cast_expr) { format!("-{}", num_lit.integer) } else { num_lit.integer.into() };
35                 lint_unnecessary_cast(cx, expr, &literal_str, cast_from, cast_to);
36                 return true
37             }
38         }
39
40         match lit.node {
41             LitKind::Int(_, LitIntType::Unsuffixed) if cast_to.is_integral() => {
42                 lint_unnecessary_cast(cx, expr, &literal_str, cast_from, cast_to);
43             },
44             LitKind::Float(_, LitFloatType::Unsuffixed) if cast_to.is_floating_point() => {
45                 lint_unnecessary_cast(cx, expr, &literal_str, cast_from, cast_to);
46             },
47             LitKind::Int(_, LitIntType::Unsuffixed) | LitKind::Float(_, LitFloatType::Unsuffixed) => {},
48             LitKind::Int(_, LitIntType::Signed(_) | LitIntType::Unsigned(_))
49             | LitKind::Float(_, LitFloatType::Suffixed(_))
50                 if cast_from.kind() == cast_to.kind() =>
51             {
52                 if let Some(src) = snippet_opt(cx, lit.span) {
53                     let num_lit = NumericLiteral::from_lit_kind(&src, &lit.node).unwrap();
54                     lint_unnecessary_cast(cx, expr, num_lit.integer, cast_from, cast_to);
55                 }
56             },
57             _ => {
58                 if cast_from.kind() == cast_to.kind() && !in_external_macro(cx.sess(), expr.span) {
59                     span_lint_and_sugg(
60                         cx,
61                         UNNECESSARY_CAST,
62                         expr.span,
63                         &format!(
64                             "casting to the same type is unnecessary (`{}` -> `{}`)",
65                             cast_from, cast_to
66                         ),
67                         "try",
68                         literal_str,
69                         Applicability::MachineApplicable,
70                     );
71                     return true;
72                 }
73             },
74         }
75     }
76
77     false
78 }
79
80 fn lint_unnecessary_cast(cx: &LateContext<'_>, expr: &Expr<'_>, literal_str: &str, cast_from: Ty<'_>, cast_to: Ty<'_>) {
81     let literal_kind_name = if cast_from.is_integral() { "integer" } else { "float" };
82     span_lint_and_sugg(
83         cx,
84         UNNECESSARY_CAST,
85         expr.span,
86         &format!("casting {} literal to `{}` is unnecessary", literal_kind_name, cast_to),
87         "try",
88         format!("{}_{}", literal_str.trim_end_matches('.'), cast_to),
89         Applicability::MachineApplicable,
90     );
91 }
92
93 fn get_numeric_literal<'e>(expr: &'e Expr<'e>) -> Option<&'e Lit> {
94     match expr.kind {
95         ExprKind::Lit(ref lit) => Some(lit),
96         ExprKind::Unary(UnOp::Neg, e) => {
97             if let ExprKind::Lit(ref lit) = e.kind {
98                 Some(lit)
99             } else {
100                 None
101             }
102         },
103         _ => None,
104     }
105 }
106
107 /// Returns the mantissa bits wide of a fp type.
108 /// Will return 0 if the type is not a fp
109 fn fp_ty_mantissa_nbits(typ: Ty<'_>) -> u32 {
110     match typ.kind() {
111         ty::Float(FloatTy::F32) => 23,
112         ty::Float(FloatTy::F64) | ty::Infer(InferTy::FloatVar(_)) => 52,
113         _ => 0,
114     }
115 }
116
117 fn is_unary_neg(expr: &Expr<'_>) -> bool {
118     matches!(expr.kind, ExprKind::Unary(UnOp::Neg, _))
119 }