Skip to content

Commit 52a3082

Browse files
committed
add manual_abs_diff lint
1 parent 4c610e3 commit 52a3082

File tree

10 files changed

+465
-1
lines changed

10 files changed

+465
-1
lines changed

Diff for: CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -5784,6 +5784,7 @@ Released 2018-09-13
57845784
[`macro_metavars_in_unsafe`]: https://rust-lang.github.io/rust-clippy/master/index.html#macro_metavars_in_unsafe
57855785
[`macro_use_imports`]: https://rust-lang.github.io/rust-clippy/master/index.html#macro_use_imports
57865786
[`main_recursion`]: https://rust-lang.github.io/rust-clippy/master/index.html#main_recursion
5787+
[`manual_abs_diff`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_abs_diff
57875788
[`manual_assert`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_assert
57885789
[`manual_async_fn`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_async_fn
57895790
[`manual_bits`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_bits

Diff for: book/src/lint_configuration.md

+1
Original file line numberDiff line numberDiff line change
@@ -797,6 +797,7 @@ The minimum rust version that the project supports. Defaults to the `rust-versio
797797
* [`iter_kv_map`](https://rust-lang.github.io/rust-clippy/master/index.html#iter_kv_map)
798798
* [`legacy_numeric_constants`](https://rust-lang.github.io/rust-clippy/master/index.html#legacy_numeric_constants)
799799
* [`lines_filter_map_ok`](https://rust-lang.github.io/rust-clippy/master/index.html#lines_filter_map_ok)
800+
* [`manual_abs_diff`](https://rust-lang.github.io/rust-clippy/master/index.html#manual_abs_diff)
800801
* [`manual_bits`](https://rust-lang.github.io/rust-clippy/master/index.html#manual_bits)
801802
* [`manual_c_str_literals`](https://rust-lang.github.io/rust-clippy/master/index.html#manual_c_str_literals)
802803
* [`manual_clamp`](https://rust-lang.github.io/rust-clippy/master/index.html#manual_clamp)

Diff for: clippy_config/src/conf.rs

+1
Original file line numberDiff line numberDiff line change
@@ -645,6 +645,7 @@ define_Conf! {
645645
iter_kv_map,
646646
legacy_numeric_constants,
647647
lines_filter_map_ok,
648+
manual_abs_diff,
648649
manual_bits,
649650
manual_c_str_literals,
650651
manual_clamp,

Diff for: clippy_lints/src/declared_lints.rs

+1
Original file line numberDiff line numberDiff line change
@@ -313,6 +313,7 @@ pub static LINTS: &[&crate::LintInfo] = &[
313313
crate::macro_metavars_in_unsafe::MACRO_METAVARS_IN_UNSAFE_INFO,
314314
crate::macro_use::MACRO_USE_IMPORTS_INFO,
315315
crate::main_recursion::MAIN_RECURSION_INFO,
316+
crate::manual_abs_diff::MANUAL_ABS_DIFF_INFO,
316317
crate::manual_assert::MANUAL_ASSERT_INFO,
317318
crate::manual_async_fn::MANUAL_ASYNC_FN_INFO,
318319
crate::manual_bits::MANUAL_BITS_INFO,

Diff for: clippy_lints/src/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,7 @@ mod loops;
205205
mod macro_metavars_in_unsafe;
206206
mod macro_use;
207207
mod main_recursion;
208+
mod manual_abs_diff;
208209
mod manual_assert;
209210
mod manual_async_fn;
210211
mod manual_bits;
@@ -878,6 +879,7 @@ pub fn register_lints(store: &mut rustc_lint::LintStore, conf: &'static Conf) {
878879
store.register_late_pass(move |_| Box::new(std_instead_of_core::StdReexports::new(conf)));
879880
store.register_late_pass(move |_| Box::new(instant_subtraction::InstantSubtraction::new(conf)));
880881
store.register_late_pass(|_| Box::new(partialeq_to_none::PartialeqToNone));
882+
store.register_late_pass(move |_| Box::new(manual_abs_diff::ManualAbsDiff::new(conf)));
881883
store.register_late_pass(move |_| Box::new(manual_clamp::ManualClamp::new(conf)));
882884
store.register_late_pass(|_| Box::new(manual_string_new::ManualStringNew));
883885
store.register_late_pass(|_| Box::new(unused_peekable::UnusedPeekable));

Diff for: clippy_lints/src/manual_abs_diff.rs

+152
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
use clippy_config::Conf;
2+
use clippy_utils::diagnostics::span_lint_and_then;
3+
use clippy_utils::higher::If;
4+
use clippy_utils::msrvs::{self, Msrv};
5+
use clippy_utils::source::HasSession as _;
6+
use clippy_utils::sugg::Sugg;
7+
use clippy_utils::ty::is_type_diagnostic_item;
8+
use clippy_utils::{eq_expr_value, peel_blocks, span_contains_comment};
9+
use rustc_errors::Applicability;
10+
use rustc_hir::{BinOpKind, Expr, ExprKind};
11+
use rustc_lint::{LateContext, LateLintPass};
12+
use rustc_middle::ty::{self, Ty};
13+
use rustc_session::impl_lint_pass;
14+
use rustc_span::sym;
15+
16+
declare_clippy_lint! {
17+
/// ### What it does
18+
/// Detects patterns like `if a > b { a - b } else { b - a }` and suggests using `a.abs_diff(b)`.
19+
///
20+
/// ### Why is this bad?
21+
/// Using `abs_diff` is shorter, more readable, and avoids control flow.
22+
///
23+
/// ### Examples
24+
/// ```no_run
25+
/// # let (a, b) = (5_usize, 3_usize);
26+
/// if a > b {
27+
/// a - b
28+
/// } else {
29+
/// b - a
30+
/// }
31+
/// # ;
32+
/// ```
33+
/// Use instead:
34+
/// ```no_run
35+
/// # let (a, b) = (5_usize, 3_usize);
36+
/// a.abs_diff(b)
37+
/// # ;
38+
/// ```
39+
#[clippy::version = "1.86.0"]
40+
pub MANUAL_ABS_DIFF,
41+
complexity,
42+
"using an if-else pattern instead of `abs_diff`"
43+
}
44+
45+
impl_lint_pass!(ManualAbsDiff => [MANUAL_ABS_DIFF]);
46+
47+
pub struct ManualAbsDiff {
48+
msrv: Msrv,
49+
}
50+
51+
impl ManualAbsDiff {
52+
pub fn new(conf: &'static Conf) -> Self {
53+
Self { msrv: conf.msrv }
54+
}
55+
}
56+
57+
impl<'tcx> LateLintPass<'tcx> for ManualAbsDiff {
58+
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
59+
if !expr.span.from_expansion()
60+
&& let Some(if_expr) = If::hir(expr)
61+
&& let Some(r#else) = if_expr.r#else
62+
&& let ExprKind::Binary(op, rhs, lhs) = if_expr.cond.kind
63+
&& let (BinOpKind::Gt | BinOpKind::Ge, mut a, mut b) | (BinOpKind::Lt | BinOpKind::Le, mut b, mut a) =
64+
(op.node, rhs, lhs)
65+
&& let Some(ty) = self.are_ty_eligible(cx, a, b)
66+
&& is_sub_expr(cx, if_expr.then, a, b, ty)
67+
&& is_sub_expr(cx, r#else, b, a, ty)
68+
{
69+
span_lint_and_then(
70+
cx,
71+
MANUAL_ABS_DIFF,
72+
expr.span,
73+
"manual absolute difference pattern without using `abs_diff`",
74+
|diag| {
75+
if is_unsuffixed_numeral_lit(a) && !is_unsuffixed_numeral_lit(b) {
76+
(a, b) = (b, a);
77+
}
78+
let applicability = {
79+
let source_map = cx.sess().source_map();
80+
if span_contains_comment(source_map, if_expr.then.span)
81+
|| span_contains_comment(source_map, r#else.span)
82+
{
83+
Applicability::MaybeIncorrect
84+
} else {
85+
Applicability::MachineApplicable
86+
}
87+
};
88+
let sugg = format!(
89+
"{}.abs_diff({})",
90+
Sugg::hir(cx, a, "..").maybe_paren(),
91+
Sugg::hir(cx, b, "..")
92+
);
93+
diag.span_suggestion(expr.span, "replace with `abs_diff`", sugg, applicability);
94+
},
95+
);
96+
}
97+
}
98+
}
99+
100+
impl ManualAbsDiff {
101+
/// Returns a type if `a` and `b` are both of it, and this lint can be applied to that
102+
/// type (currently, any primitive int, or a `Duration`)
103+
fn are_ty_eligible<'tcx>(&self, cx: &LateContext<'tcx>, a: &Expr<'_>, b: &Expr<'_>) -> Option<Ty<'tcx>> {
104+
let is_int = |ty: Ty<'_>| matches!(ty.kind(), ty::Uint(_) | ty::Int(_)) && self.msrv.meets(cx, msrvs::ABS_DIFF);
105+
let is_duration =
106+
|ty| is_type_diagnostic_item(cx, ty, sym::Duration) && self.msrv.meets(cx, msrvs::DURATION_ABS_DIFF);
107+
108+
let a_ty = cx.typeck_results().expr_ty(a).peel_refs();
109+
(a_ty == cx.typeck_results().expr_ty(b).peel_refs() && (is_int(a_ty) || is_duration(a_ty))).then_some(a_ty)
110+
}
111+
}
112+
113+
/// Checks if the given expression is a subtraction operation between two expected expressions,
114+
/// i.e. if `expr` is `{expected_a} - {expected_b}`.
115+
///
116+
/// If `expected_ty` is a signed primitive integer, this function will only return `Some` if the
117+
/// subtraction expr is wrapped in a cast to the equivalent unsigned int.
118+
fn is_sub_expr(
119+
cx: &LateContext<'_>,
120+
expr: &Expr<'_>,
121+
expected_a: &Expr<'_>,
122+
expected_b: &Expr<'_>,
123+
expected_ty: Ty<'_>,
124+
) -> bool {
125+
let expr = peel_blocks(expr).kind;
126+
127+
if let ty::Int(ty) = expected_ty.kind() {
128+
let unsigned = Ty::new_uint(cx.tcx, ty.to_unsigned());
129+
130+
return if let ExprKind::Cast(expr, cast_ty) = expr
131+
&& cx.typeck_results().node_type(cast_ty.hir_id) == unsigned
132+
{
133+
is_sub_expr(cx, expr, expected_a, expected_b, unsigned)
134+
} else {
135+
false
136+
};
137+
}
138+
139+
if let ExprKind::Binary(op, a, b) = expr
140+
&& let BinOpKind::Sub = op.node
141+
&& eq_expr_value(cx, a, expected_a)
142+
&& eq_expr_value(cx, b, expected_b)
143+
{
144+
true
145+
} else {
146+
false
147+
}
148+
}
149+
150+
fn is_unsuffixed_numeral_lit(expr: &Expr<'_>) -> bool {
151+
matches!(expr.kind, ExprKind::Lit(lit) if lit.node.is_numeric() && lit.node.is_unsuffixed())
152+
}

Diff for: clippy_utils/src/msrvs.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ msrv_aliases! {
2727
1,84,0 { CONST_OPTION_AS_SLICE }
2828
1,83,0 { CONST_EXTERN_FN, CONST_FLOAT_BITS_CONV, CONST_FLOAT_CLASSIFY, CONST_MUT_REFS, CONST_UNWRAP }
2929
1,82,0 { IS_NONE_OR, REPEAT_N, RAW_REF_OP }
30-
1,81,0 { LINT_REASONS_STABILIZATION, ERROR_IN_CORE, EXPLICIT_SELF_TYPE_ELISION }
30+
1,81,0 { LINT_REASONS_STABILIZATION, ERROR_IN_CORE, EXPLICIT_SELF_TYPE_ELISION, DURATION_ABS_DIFF }
3131
1,80,0 { BOX_INTO_ITER, LAZY_CELL }
3232
1,77,0 { C_STR_LITERALS }
3333
1,76,0 { PTR_FROM_REF, OPTION_RESULT_INSPECT }
@@ -40,6 +40,7 @@ msrv_aliases! {
4040
1,65,0 { LET_ELSE, POINTER_CAST_CONSTNESS }
4141
1,63,0 { CLONE_INTO }
4242
1,62,0 { BOOL_THEN_SOME, DEFAULT_ENUM_ATTRIBUTE, CONST_EXTERN_C_FN }
43+
1,60,0 { ABS_DIFF }
4344
1,59,0 { THREAD_LOCAL_CONST_INIT }
4445
1,58,0 { FORMAT_ARGS_CAPTURE, PATTERN_TRAIT_CHAR_ARRAY, CONST_RAW_PTR_DEREF }
4546
1,57,0 { MAP_WHILE }

Diff for: tests/ui/manual_abs_diff.fixed

+106
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
#![warn(clippy::manual_abs_diff)]
2+
3+
use std::time::Duration;
4+
5+
fn main() {
6+
let a: usize = 5;
7+
let b: usize = 3;
8+
let c: usize = 8;
9+
let d: usize = 11;
10+
11+
let _ = a.abs_diff(b);
12+
//~^ manual_abs_diff
13+
let _ = b.abs_diff(a);
14+
//~^ manual_abs_diff
15+
16+
let _ = b.abs_diff(5);
17+
//~^ manual_abs_diff
18+
let _ = b.abs_diff(5);
19+
//~^ manual_abs_diff
20+
21+
let _ = a.abs_diff(b);
22+
//~^ manual_abs_diff
23+
let _ = b.abs_diff(a);
24+
//~^ manual_abs_diff
25+
26+
#[allow(arithmetic_overflow)]
27+
{
28+
let _ = if a > b { b - a } else { a - b };
29+
let _ = if a < b { a - b } else { b - a };
30+
}
31+
32+
let _ = (a + b).abs_diff(c + d);
33+
let _ = (c + d).abs_diff(a + b);
34+
35+
const A: usize = 5;
36+
const B: usize = 3;
37+
// check const context
38+
const _: usize = A.abs_diff(B);
39+
//~^ manual_abs_diff
40+
41+
let a = Duration::from_secs(3);
42+
let b = Duration::from_secs(5);
43+
let _ = a.abs_diff(b);
44+
//~^ manual_abs_diff
45+
46+
let a: i32 = 3;
47+
let b: i32 = -5;
48+
let _ = if a > b { a - b } else { b - a };
49+
let _ = a.abs_diff(b);
50+
//~^ manual_abs_diff
51+
}
52+
53+
// FIXME: bunch of patterns that should be linted
54+
fn fixme() {
55+
let a: usize = 5;
56+
let b: usize = 3;
57+
let c: usize = 8;
58+
let d: usize = 11;
59+
60+
{
61+
let out;
62+
if a > b {
63+
out = a - b;
64+
} else {
65+
out = b - a;
66+
}
67+
}
68+
69+
{
70+
let mut out = 0;
71+
if a > b {
72+
out = a - b;
73+
} else if a < b {
74+
out = b - a;
75+
}
76+
}
77+
78+
#[allow(clippy::implicit_saturating_sub)]
79+
let _ = if a > b {
80+
a - b
81+
} else if a < b {
82+
b - a
83+
} else {
84+
0
85+
};
86+
87+
let a: i32 = 3;
88+
let b: i32 = 5;
89+
let _: u32 = if a > b { a - b } else { b - a } as u32;
90+
}
91+
92+
fn non_primitive_ty() {
93+
#[derive(Eq, PartialEq, PartialOrd)]
94+
struct S(i32);
95+
96+
impl std::ops::Sub for S {
97+
type Output = S;
98+
99+
fn sub(self, rhs: Self) -> Self::Output {
100+
Self(self.0 - rhs.0)
101+
}
102+
}
103+
104+
let (a, b) = (S(10), S(20));
105+
let _ = if a < b { b - a } else { a - b };
106+
}

0 commit comments

Comments
 (0)