]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/casts/unnecessary_cast.rs
Auto merge of #92252 - GuillaumeGomez:update-pulldown, r=camelid,xFrednet
[rust.git] / clippy_lints / src / casts / unnecessary_cast.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::numeric_literal::NumericLiteral;
3 use clippy_utils::source::snippet_opt;
4 use if_chain::if_chain;
5 use rustc_ast::{LitFloatType, LitIntType, LitKind};
6 use rustc_errors::Applicability;
7 use rustc_hir::{Expr, ExprKind, Lit, UnOp};
8 use rustc_lint::{LateContext, LintContext};
9 use rustc_middle::lint::in_external_macro;
10 use rustc_middle::ty::{self, FloatTy, InferTy, Ty};
11
12 use super::UNNECESSARY_CAST;
13
14 pub(super) fn check(
15     cx: &LateContext<'_>,
16     expr: &Expr<'_>,
17     cast_expr: &Expr<'_>,
18     cast_from: Ty<'_>,
19     cast_to: Ty<'_>,
20 ) -> bool {
21     if let Some(lit) = get_numeric_literal(cast_expr) {
22         let literal_str = snippet_opt(cx, cast_expr.span).unwrap_or_default();
23
24         if_chain! {
25             if let LitKind::Int(n, _) = lit.node;
26             if let Some(src) = snippet_opt(cx, lit.span);
27             if cast_to.is_floating_point();
28             if let Some(num_lit) = NumericLiteral::from_lit_kind(&src, &lit.node);
29             let from_nbits = 128 - n.leading_zeros();
30             let to_nbits = fp_ty_mantissa_nbits(cast_to);
31             if from_nbits != 0 && to_nbits != 0 && from_nbits <= to_nbits && num_lit.is_decimal();
32             then {
33                 let literal_str = if is_unary_neg(cast_expr) { format!("-{}", num_lit.integer) } else { num_lit.integer.into() };
34                 lint_unnecessary_cast(cx, expr, &literal_str, cast_from, cast_to);
35                 return true
36             }
37         }
38
39         match lit.node {
40             LitKind::Int(_, LitIntType::Unsuffixed) if cast_to.is_integral() => {
41                 lint_unnecessary_cast(cx, expr, &literal_str, cast_from, cast_to);
42             },
43             LitKind::Float(_, LitFloatType::Unsuffixed) if cast_to.is_floating_point() => {
44                 lint_unnecessary_cast(cx, expr, &literal_str, cast_from, cast_to);
45             },
46             LitKind::Int(_, LitIntType::Unsuffixed) | LitKind::Float(_, LitFloatType::Unsuffixed) => {},
47             LitKind::Int(_, LitIntType::Signed(_) | LitIntType::Unsigned(_))
48             | LitKind::Float(_, LitFloatType::Suffixed(_))
49                 if cast_from.kind() == cast_to.kind() =>
50             {
51                 if let Some(src) = snippet_opt(cx, lit.span) {
52                     if let Some(num_lit) = NumericLiteral::from_lit_kind(&src, &lit.node) {
53                         lint_unnecessary_cast(cx, expr, num_lit.integer, cast_from, cast_to);
54                     }
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 }