]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/casts/unnecessary_cast.rs
Merge commit '4f3ab69ea0a0908260944443c739426cc384ae1a' into clippyup
[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 clippy_utils::{get_parent_expr, path_to_local};
5 use if_chain::if_chain;
6 use rustc_ast::{LitFloatType, LitIntType, LitKind};
7 use rustc_errors::Applicability;
8 use rustc_hir::def::Res;
9 use rustc_hir::{Expr, ExprKind, Lit, QPath, TyKind, UnOp};
10 use rustc_lint::{LateContext, LintContext};
11 use rustc_middle::lint::in_external_macro;
12 use rustc_middle::ty::{self, FloatTy, InferTy, Ty};
13
14 use super::UNNECESSARY_CAST;
15
16 pub(super) fn check<'tcx>(
17     cx: &LateContext<'tcx>,
18     expr: &Expr<'tcx>,
19     cast_expr: &Expr<'tcx>,
20     cast_from: Ty<'tcx>,
21     cast_to: Ty<'tcx>,
22 ) -> bool {
23     // skip non-primitive type cast
24     if_chain! {
25         if let ExprKind::Cast(_, cast_to) = expr.kind;
26         if let TyKind::Path(QPath::Resolved(_, path)) = &cast_to.kind;
27         if let Res::PrimTy(_) = path.res;
28         then {}
29         else {
30             return false
31         }
32     }
33
34     let cast_str = snippet_opt(cx, cast_expr.span).unwrap_or_default();
35
36     if let Some(lit) = get_numeric_literal(cast_expr) {
37         let literal_str = &cast_str;
38
39         if_chain! {
40             if let LitKind::Int(n, _) = lit.node;
41             if let Some(src) = snippet_opt(cx, cast_expr.span);
42             if cast_to.is_floating_point();
43             if let Some(num_lit) = NumericLiteral::from_lit_kind(&src, &lit.node);
44             let from_nbits = 128 - n.leading_zeros();
45             let to_nbits = fp_ty_mantissa_nbits(cast_to);
46             if from_nbits != 0 && to_nbits != 0 && from_nbits <= to_nbits && num_lit.is_decimal();
47             then {
48                 lint_unnecessary_cast(cx, expr, num_lit.integer, cast_from, cast_to);
49                 return true
50             }
51         }
52
53         match lit.node {
54             LitKind::Int(_, LitIntType::Unsuffixed) if cast_to.is_integral() => {
55                 lint_unnecessary_cast(cx, expr, literal_str, cast_from, cast_to);
56                 return false;
57             },
58             LitKind::Float(_, LitFloatType::Unsuffixed) if cast_to.is_floating_point() => {
59                 lint_unnecessary_cast(cx, expr, literal_str, cast_from, cast_to);
60                 return false;
61             },
62             LitKind::Int(_, LitIntType::Signed(_) | LitIntType::Unsigned(_))
63             | LitKind::Float(_, LitFloatType::Suffixed(_))
64                 if cast_from.kind() == cast_to.kind() =>
65             {
66                 if let Some(src) = snippet_opt(cx, cast_expr.span) {
67                     if let Some(num_lit) = NumericLiteral::from_lit_kind(&src, &lit.node) {
68                         lint_unnecessary_cast(cx, expr, num_lit.integer, cast_from, cast_to);
69                         return true;
70                     }
71                 }
72             },
73             _ => {},
74         }
75     }
76
77     if cast_from.kind() == cast_to.kind() && !in_external_macro(cx.sess(), expr.span) {
78         if let Some(id) = path_to_local(cast_expr)
79             && let Some(span) = cx.tcx.hir().opt_span(id)
80             && span.ctxt() != cast_expr.span.ctxt()
81         {
82             // Binding context is different than the identifiers context.
83             // Weird macro wizardry could be involved here.
84             return false;
85         }
86
87         span_lint_and_sugg(
88             cx,
89             UNNECESSARY_CAST,
90             expr.span,
91             &format!("casting to the same type is unnecessary (`{cast_from}` -> `{cast_to}`)"),
92             "try",
93             if get_parent_expr(cx, expr).map_or(false, |e| matches!(e.kind, ExprKind::AddrOf(..))) {
94                 format!("{{ {cast_str} }}")
95             } else {
96                 cast_str
97             },
98             Applicability::MachineApplicable,
99         );
100         return true;
101     }
102
103     false
104 }
105
106 fn lint_unnecessary_cast(
107     cx: &LateContext<'_>,
108     expr: &Expr<'_>,
109     raw_literal_str: &str,
110     cast_from: Ty<'_>,
111     cast_to: Ty<'_>,
112 ) {
113     let literal_kind_name = if cast_from.is_integral() { "integer" } else { "float" };
114     // first we remove all matches so `-(1)` become `-1`, and remove trailing dots, so `1.` become `1`
115     let literal_str = raw_literal_str
116         .replace(['(', ')'], "")
117         .trim_end_matches('.')
118         .to_string();
119     // we know need to check if the parent is a method call, to add parenthesis accordingly (eg:
120     // (-1).foo() instead of -1.foo())
121     let sugg = if let Some(parent_expr) = get_parent_expr(cx, expr)
122         && let ExprKind::MethodCall(..) = parent_expr.kind
123         && literal_str.starts_with('-')
124         {
125             format!("({literal_str}_{cast_to})")
126
127         } else {
128             format!("{literal_str}_{cast_to}")
129     };
130
131     span_lint_and_sugg(
132         cx,
133         UNNECESSARY_CAST,
134         expr.span,
135         &format!("casting {literal_kind_name} literal to `{cast_to}` is unnecessary"),
136         "try",
137         sugg,
138         Applicability::MachineApplicable,
139     );
140 }
141
142 fn get_numeric_literal<'e>(expr: &'e Expr<'e>) -> Option<&'e Lit> {
143     match expr.kind {
144         ExprKind::Lit(ref lit) => Some(lit),
145         ExprKind::Unary(UnOp::Neg, e) => {
146             if let ExprKind::Lit(ref lit) = e.kind {
147                 Some(lit)
148             } else {
149                 None
150             }
151         },
152         _ => None,
153     }
154 }
155
156 /// Returns the mantissa bits wide of a fp type.
157 /// Will return 0 if the type is not a fp
158 fn fp_ty_mantissa_nbits(typ: Ty<'_>) -> u32 {
159     match typ.kind() {
160         ty::Float(FloatTy::F32) => 23,
161         ty::Float(FloatTy::F64) | ty::Infer(InferTy::FloatVar(_)) => 52,
162         _ => 0,
163     }
164 }