]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/casts/unnecessary_cast.rs
19d2e6e1d1298e448619d608056a591ba13d88eb
[rust.git] / src / tools / clippy / 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     let replaced_literal;
94     let matchless = if literal_str.contains(['(', ')']) {
95         replaced_literal = literal_str.replace(['(', ')'], "");
96         &replaced_literal
97     } else {
98         literal_str
99     };
100     span_lint_and_sugg(
101         cx,
102         UNNECESSARY_CAST,
103         expr.span,
104         &format!("casting {} literal to `{}` is unnecessary", literal_kind_name, cast_to),
105         "try",
106         format!("{}_{}", matchless.trim_end_matches('.'), cast_to),
107         Applicability::MachineApplicable,
108     );
109 }
110
111 fn get_numeric_literal<'e>(expr: &'e Expr<'e>) -> Option<&'e Lit> {
112     match expr.kind {
113         ExprKind::Lit(ref lit) => Some(lit),
114         ExprKind::Unary(UnOp::Neg, e) => {
115             if let ExprKind::Lit(ref lit) = e.kind {
116                 Some(lit)
117             } else {
118                 None
119             }
120         },
121         _ => None,
122     }
123 }
124
125 /// Returns the mantissa bits wide of a fp type.
126 /// Will return 0 if the type is not a fp
127 fn fp_ty_mantissa_nbits(typ: Ty<'_>) -> u32 {
128     match typ.kind() {
129         ty::Float(FloatTy::F32) => 23,
130         ty::Float(FloatTy::F64) | ty::Infer(InferTy::FloatVar(_)) => 52,
131         _ => 0,
132     }
133 }