]> git.proxmox.com Git - rustc.git/blame - src/tools/clippy/clippy_lints/src/casts/cast_abs_to_unsigned.rs
New upstream version 1.65.0+dfsg1
[rustc.git] / src / tools / clippy / clippy_lints / src / casts / cast_abs_to_unsigned.rs
CommitLineData
04454e1e
FG
1use clippy_utils::diagnostics::span_lint_and_sugg;
2use clippy_utils::sugg::Sugg;
3use clippy_utils::{meets_msrv, msrvs};
04454e1e
FG
4use rustc_errors::Applicability;
5use rustc_hir::{Expr, ExprKind};
6use rustc_lint::LateContext;
923072b8 7use rustc_middle::ty::{self, Ty};
04454e1e
FG
8use rustc_semver::RustcVersion;
9
10use super::CAST_ABS_TO_UNSIGNED;
11
12pub(super) fn check(
13 cx: &LateContext<'_>,
14 expr: &Expr<'_>,
15 cast_expr: &Expr<'_>,
16 cast_from: Ty<'_>,
17 cast_to: Ty<'_>,
923072b8 18 msrv: Option<RustcVersion>,
04454e1e 19) {
923072b8
FG
20 if meets_msrv(msrv, msrvs::UNSIGNED_ABS)
21 && let ty::Int(from) = cast_from.kind()
22 && let ty::Uint(to) = cast_to.kind()
f2b60f7d 23 && let ExprKind::MethodCall(method_path, receiver, ..) = cast_expr.kind
923072b8
FG
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",
f2b60f7d 40 format!("{}.unsigned_abs()", Sugg::hir(cx, receiver, "..").maybe_par()),
923072b8
FG
41 Applicability::MachineApplicable,
42 );
04454e1e
FG
43 }
44}