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