]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/casts/cast_abs_to_unsigned.rs
Auto merge of #9870 - koka831:unformat-unused-rounding, r=Jarcho
[rust.git] / clippy_lints / src / casts / cast_abs_to_unsigned.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::sugg::Sugg;
3 use clippy_utils::{meets_msrv, msrvs};
4 use rustc_errors::Applicability;
5 use rustc_hir::{Expr, ExprKind};
6 use rustc_lint::LateContext;
7 use rustc_middle::ty::{self, Ty};
8 use rustc_semver::RustcVersion;
9
10 use super::CAST_ABS_TO_UNSIGNED;
11
12 pub(super) fn check(
13     cx: &LateContext<'_>,
14     expr: &Expr<'_>,
15     cast_expr: &Expr<'_>,
16     cast_from: Ty<'_>,
17     cast_to: Ty<'_>,
18     msrv: Option<RustcVersion>,
19 ) {
20     if meets_msrv(msrv, msrvs::UNSIGNED_ABS)
21         && let ty::Int(from) = cast_from.kind()
22         && let ty::Uint(to) = cast_to.kind()
23         && let ExprKind::MethodCall(method_path, receiver, ..) = cast_expr.kind
24         && method_path.ident.name.as_str() == "abs"
25     {
26         let span = if from.bit_width() == to.bit_width() {
27             expr.span
28         } else {
29             // if the result of `.unsigned_abs` would be a different type, keep the cast
30             // e.g. `i64 -> usize`, `i16 -> u8`
31             cast_expr.span
32         };
33
34         span_lint_and_sugg(
35             cx,
36             CAST_ABS_TO_UNSIGNED,
37             span,
38             &format!("casting the result of `{cast_from}::abs()` to {cast_to}"),
39             "replace with",
40             format!("{}.unsigned_abs()", Sugg::hir(cx, receiver, "..").maybe_par()),
41             Applicability::MachineApplicable,
42         );
43     }
44 }