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