]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/casts/unnecessary_cast.rs
Merge commit '0e87918536b9833bbc6c683d1f9d51ee2bf03ef1' into clippyup
[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                     let num_lit = NumericLiteral::from_lit_kind(&src, &lit.node).unwrap();
53                     lint_unnecessary_cast(cx, expr, num_lit.integer, cast_from, cast_to);
54                 }
55             },
56             _ => {
57                 if cast_from.kind() == cast_to.kind() && !in_external_macro(cx.sess(), expr.span) {
58                     span_lint_and_sugg(
59                         cx,
60                         UNNECESSARY_CAST,
61                         expr.span,
62                         &format!(
63                             "casting to the same type is unnecessary (`{}` -> `{}`)",
64                             cast_from, cast_to
65                         ),
66                         "try",
67                         literal_str,
68                         Applicability::MachineApplicable,
69                     );
70                     return true;
71                 }
72             },
73         }
74     }
75
76     false
77 }
78
79 fn lint_unnecessary_cast(cx: &LateContext<'_>, expr: &Expr<'_>, literal_str: &str, cast_from: Ty<'_>, cast_to: Ty<'_>) {
80     let literal_kind_name = if cast_from.is_integral() { "integer" } else { "float" };
81     span_lint_and_sugg(
82         cx,
83         UNNECESSARY_CAST,
84         expr.span,
85         &format!("casting {} literal to `{}` is unnecessary", literal_kind_name, cast_to),
86         "try",
87         format!("{}_{}", literal_str.trim_end_matches('.'), cast_to),
88         Applicability::MachineApplicable,
89     );
90 }
91
92 fn get_numeric_literal<'e>(expr: &'e Expr<'e>) -> Option<&'e Lit> {
93     match expr.kind {
94         ExprKind::Lit(ref lit) => Some(lit),
95         ExprKind::Unary(UnOp::Neg, e) => {
96             if let ExprKind::Lit(ref lit) = e.kind {
97                 Some(lit)
98             } else {
99                 None
100             }
101         },
102         _ => None,
103     }
104 }
105
106 /// Returns the mantissa bits wide of a fp type.
107 /// Will return 0 if the type is not a fp
108 fn fp_ty_mantissa_nbits(typ: Ty<'_>) -> u32 {
109     match typ.kind() {
110         ty::Float(FloatTy::F32) => 23,
111         ty::Float(FloatTy::F64) | ty::Infer(InferTy::FloatVar(_)) => 52,
112         _ => 0,
113     }
114 }
115
116 fn is_unary_neg(expr: &Expr<'_>) -> bool {
117     matches!(expr.kind, ExprKind::Unary(UnOp::Neg, _))
118 }