-
Notifications
You must be signed in to change notification settings - Fork 1.7k
add manual_abs_diff
lint
#14482
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
add manual_abs_diff
lint
#14482
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,152 @@ | ||
use clippy_config::Conf; | ||
use clippy_utils::diagnostics::span_lint_and_then; | ||
use clippy_utils::higher::If; | ||
use clippy_utils::msrvs::{self, Msrv}; | ||
use clippy_utils::source::HasSession as _; | ||
use clippy_utils::sugg::Sugg; | ||
use clippy_utils::ty::is_type_diagnostic_item; | ||
use clippy_utils::{eq_expr_value, peel_blocks, span_contains_comment}; | ||
use rustc_errors::Applicability; | ||
use rustc_hir::{BinOpKind, Expr, ExprKind}; | ||
use rustc_lint::{LateContext, LateLintPass}; | ||
use rustc_middle::ty::{self, Ty}; | ||
use rustc_session::impl_lint_pass; | ||
use rustc_span::sym; | ||
|
||
declare_clippy_lint! { | ||
/// ### What it does | ||
/// Detects patterns like `if a > b { a - b } else { b - a }` and suggests using `a.abs_diff(b)`. | ||
/// | ||
/// ### Why is this bad? | ||
/// Using `abs_diff` is shorter, more readable, and avoids control flow. | ||
/// | ||
/// ### Examples | ||
/// ```no_run | ||
/// # let (a, b) = (5_usize, 3_usize); | ||
/// if a > b { | ||
/// a - b | ||
/// } else { | ||
/// b - a | ||
/// } | ||
/// # ; | ||
/// ``` | ||
/// Use instead: | ||
/// ```no_run | ||
/// # let (a, b) = (5_usize, 3_usize); | ||
/// a.abs_diff(b) | ||
/// # ; | ||
/// ``` | ||
#[clippy::version = "1.86.0"] | ||
pub MANUAL_ABS_DIFF, | ||
complexity, | ||
"using an if-else pattern instead of `abs_diff`" | ||
} | ||
|
||
impl_lint_pass!(ManualAbsDiff => [MANUAL_ABS_DIFF]); | ||
|
||
pub struct ManualAbsDiff { | ||
msrv: Msrv, | ||
} | ||
|
||
impl ManualAbsDiff { | ||
pub fn new(conf: &'static Conf) -> Self { | ||
Self { msrv: conf.msrv } | ||
} | ||
} | ||
|
||
impl<'tcx> LateLintPass<'tcx> for ManualAbsDiff { | ||
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) { | ||
if !expr.span.from_expansion() | ||
&& let Some(if_expr) = If::hir(expr) | ||
&& let Some(r#else) = if_expr.r#else | ||
&& let ExprKind::Binary(op, rhs, lhs) = if_expr.cond.kind | ||
&& let (BinOpKind::Gt | BinOpKind::Ge, mut a, mut b) | (BinOpKind::Lt | BinOpKind::Le, mut b, mut a) = | ||
(op.node, rhs, lhs) | ||
&& let Some(ty) = self.are_ty_eligible(cx, a, b) | ||
&& is_sub_expr(cx, if_expr.then, a, b, ty) | ||
&& is_sub_expr(cx, r#else, b, a, ty) | ||
{ | ||
span_lint_and_then( | ||
cx, | ||
MANUAL_ABS_DIFF, | ||
expr.span, | ||
"manual absolute difference pattern without using `abs_diff`", | ||
|diag| { | ||
if is_unsuffixed_numeral_lit(a) && !is_unsuffixed_numeral_lit(b) { | ||
(a, b) = (b, a); | ||
} | ||
let applicability = { | ||
let source_map = cx.sess().source_map(); | ||
if span_contains_comment(source_map, if_expr.then.span) | ||
|| span_contains_comment(source_map, r#else.span) | ||
{ | ||
Applicability::MaybeIncorrect | ||
} else { | ||
Applicability::MachineApplicable | ||
} | ||
}; | ||
let sugg = format!( | ||
"{}.abs_diff({})", | ||
Sugg::hir(cx, a, "..").maybe_paren(), | ||
Sugg::hir(cx, b, "..") | ||
); | ||
diag.span_suggestion(expr.span, "replace with `abs_diff`", sugg, applicability); | ||
}, | ||
); | ||
} | ||
} | ||
} | ||
|
||
impl ManualAbsDiff { | ||
/// Returns a type if `a` and `b` are both of it, and this lint can be applied to that | ||
/// type (currently, any primitive int, or a `Duration`) | ||
fn are_ty_eligible<'tcx>(&self, cx: &LateContext<'tcx>, a: &Expr<'_>, b: &Expr<'_>) -> Option<Ty<'tcx>> { | ||
let is_int = |ty: Ty<'_>| matches!(ty.kind(), ty::Uint(_) | ty::Int(_)) && self.msrv.meets(cx, msrvs::ABS_DIFF); | ||
let is_duration = | ||
|ty| is_type_diagnostic_item(cx, ty, sym::Duration) && self.msrv.meets(cx, msrvs::DURATION_ABS_DIFF); | ||
|
||
let a_ty = cx.typeck_results().expr_ty(a).peel_refs(); | ||
(a_ty == cx.typeck_results().expr_ty(b).peel_refs() && (is_int(a_ty) || is_duration(a_ty))).then_some(a_ty) | ||
} | ||
} | ||
|
||
/// Checks if the given expression is a subtraction operation between two expected expressions, | ||
/// i.e. if `expr` is `{expected_a} - {expected_b}`. | ||
/// | ||
/// If `expected_ty` is a signed primitive integer, this function will only return `Some` if the | ||
/// subtraction expr is wrapped in a cast to the equivalent unsigned int. | ||
fn is_sub_expr( | ||
cx: &LateContext<'_>, | ||
expr: &Expr<'_>, | ||
expected_a: &Expr<'_>, | ||
expected_b: &Expr<'_>, | ||
expected_ty: Ty<'_>, | ||
) -> bool { | ||
let expr = peel_blocks(expr).kind; | ||
|
||
if let ty::Int(ty) = expected_ty.kind() { | ||
let unsigned = Ty::new_uint(cx.tcx, ty.to_unsigned()); | ||
|
||
return if let ExprKind::Cast(expr, cast_ty) = expr | ||
&& cx.typeck_results().node_type(cast_ty.hir_id) == unsigned | ||
{ | ||
is_sub_expr(cx, expr, expected_a, expected_b, unsigned) | ||
} else { | ||
false | ||
}; | ||
} | ||
|
||
if let ExprKind::Binary(op, a, b) = expr | ||
&& let BinOpKind::Sub = op.node | ||
&& eq_expr_value(cx, a, expected_a) | ||
&& eq_expr_value(cx, b, expected_b) | ||
{ | ||
true | ||
} else { | ||
false | ||
} | ||
} | ||
|
||
fn is_unsuffixed_numeral_lit(expr: &Expr<'_>) -> bool { | ||
matches!(expr.kind, ExprKind::Lit(lit) if lit.node.is_numeric() && lit.node.is_unsuffixed()) | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,106 @@ | ||
#![warn(clippy::manual_abs_diff)] | ||
|
||
use std::time::Duration; | ||
|
||
fn main() { | ||
let a: usize = 5; | ||
let b: usize = 3; | ||
let c: usize = 8; | ||
let d: usize = 11; | ||
|
||
let _ = a.abs_diff(b); | ||
//~^ manual_abs_diff | ||
let _ = b.abs_diff(a); | ||
//~^ manual_abs_diff | ||
|
||
let _ = b.abs_diff(5); | ||
//~^ manual_abs_diff | ||
let _ = b.abs_diff(5); | ||
//~^ manual_abs_diff | ||
|
||
let _ = a.abs_diff(b); | ||
//~^ manual_abs_diff | ||
let _ = b.abs_diff(a); | ||
//~^ manual_abs_diff | ||
|
||
#[allow(arithmetic_overflow)] | ||
{ | ||
let _ = if a > b { b - a } else { a - b }; | ||
let _ = if a < b { a - b } else { b - a }; | ||
} | ||
|
||
let _ = (a + b).abs_diff(c + d); | ||
let _ = (c + d).abs_diff(a + b); | ||
|
||
const A: usize = 5; | ||
const B: usize = 3; | ||
// check const context | ||
const _: usize = A.abs_diff(B); | ||
//~^ manual_abs_diff | ||
|
||
let a = Duration::from_secs(3); | ||
let b = Duration::from_secs(5); | ||
let _ = a.abs_diff(b); | ||
//~^ manual_abs_diff | ||
|
||
let a: i32 = 3; | ||
let b: i32 = -5; | ||
let _ = if a > b { a - b } else { b - a }; | ||
let _ = a.abs_diff(b); | ||
//~^ manual_abs_diff | ||
} | ||
|
||
// FIXME: bunch of patterns that should be linted | ||
fn fixme() { | ||
let a: usize = 5; | ||
let b: usize = 3; | ||
let c: usize = 8; | ||
let d: usize = 11; | ||
|
||
{ | ||
let out; | ||
if a > b { | ||
out = a - b; | ||
} else { | ||
out = b - a; | ||
} | ||
} | ||
|
||
{ | ||
let mut out = 0; | ||
if a > b { | ||
out = a - b; | ||
} else if a < b { | ||
out = b - a; | ||
} | ||
} | ||
|
||
#[allow(clippy::implicit_saturating_sub)] | ||
let _ = if a > b { | ||
a - b | ||
} else if a < b { | ||
b - a | ||
} else { | ||
0 | ||
}; | ||
|
||
let a: i32 = 3; | ||
let b: i32 = 5; | ||
let _: u32 = if a > b { a - b } else { b - a } as u32; | ||
} | ||
|
||
fn non_primitive_ty() { | ||
#[derive(Eq, PartialEq, PartialOrd)] | ||
struct S(i32); | ||
|
||
impl std::ops::Sub for S { | ||
type Output = S; | ||
|
||
fn sub(self, rhs: Self) -> Self::Output { | ||
Self(self.0 - rhs.0) | ||
} | ||
} | ||
|
||
let (a, b) = (S(10), S(20)); | ||
let _ = if a < b { b - a } else { a - b }; | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should be 1.88.0, see #14653