|
| 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 | +} |
0 commit comments