]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/casts/unnecessary_cast.rs
Auto merge of #9487 - kraktus:question_mark, r=Jarcho
[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!("casting to the same type is unnecessary (`{cast_from}` -> `{cast_to}`)"),
75                         "try",
76                         literal_str,
77                         Applicability::MachineApplicable,
78                     );
79                     return true;
80                 }
81             },
82         }
83     }
84
85     false
86 }
87
88 fn lint_unnecessary_cast(cx: &LateContext<'_>, expr: &Expr<'_>, literal_str: &str, cast_from: Ty<'_>, cast_to: Ty<'_>) {
89     let literal_kind_name = if cast_from.is_integral() { "integer" } else { "float" };
90     let replaced_literal;
91     let matchless = if literal_str.contains(['(', ')']) {
92         replaced_literal = literal_str.replace(['(', ')'], "");
93         &replaced_literal
94     } else {
95         literal_str
96     };
97     span_lint_and_sugg(
98         cx,
99         UNNECESSARY_CAST,
100         expr.span,
101         &format!("casting {literal_kind_name} literal to `{cast_to}` is unnecessary"),
102         "try",
103         format!("{}_{cast_to}", matchless.trim_end_matches('.')),
104         Applicability::MachineApplicable,
105     );
106 }
107
108 fn get_numeric_literal<'e>(expr: &'e Expr<'e>) -> Option<&'e Lit> {
109     match expr.kind {
110         ExprKind::Lit(ref lit) => Some(lit),
111         ExprKind::Unary(UnOp::Neg, e) => {
112             if let ExprKind::Lit(ref lit) = e.kind {
113                 Some(lit)
114             } else {
115                 None
116             }
117         },
118         _ => None,
119     }
120 }
121
122 /// Returns the mantissa bits wide of a fp type.
123 /// Will return 0 if the type is not a fp
124 fn fp_ty_mantissa_nbits(typ: Ty<'_>) -> u32 {
125     match typ.kind() {
126         ty::Float(FloatTy::F32) => 23,
127         ty::Float(FloatTy::F64) | ty::Infer(InferTy::FloatVar(_)) => 52,
128         _ => 0,
129     }
130 }