|
| 1 | +use clippy_utils::diagnostics::span_lint; |
| 2 | +use clippy_utils::eq_expr_value; |
| 3 | +use rustc_hir::{Arm, ExprKind}; |
| 4 | +use rustc_lint::{LateContext, LateLintPass}; |
| 5 | +use rustc_session::declare_lint_pass; |
| 6 | + |
| 7 | +declare_clippy_lint! { |
| 8 | + /// ### What it does |
| 9 | + /// Checks for the same condition being checked in a match guard and in the match body |
| 10 | + /// |
| 11 | + /// ### Why is this bad? |
| 12 | + /// This is usually just a typo or a copy and paste error. |
| 13 | + /// |
| 14 | + /// ### Known problems |
| 15 | + /// False negatives: if the condition is an impure function, it could've been called twice on |
| 16 | + /// purpose for its side effects |
| 17 | + /// |
| 18 | + /// ### Example |
| 19 | + /// ```no_run |
| 20 | + /// # let n = 0; |
| 21 | + /// # let a = 3; |
| 22 | + /// # let b = 4; |
| 23 | + /// match n { |
| 24 | + /// 0 if a > b => { |
| 25 | + /// if a > b { |
| 26 | + /// return; |
| 27 | + /// } |
| 28 | + /// } |
| 29 | + /// _ => {} |
| 30 | + /// } |
| 31 | + /// ``` |
| 32 | + /// Use instead: |
| 33 | + /// ```no_run |
| 34 | + /// # let n = 0; |
| 35 | + /// # let a = 3; |
| 36 | + /// # let b = 4; |
| 37 | + /// match n { |
| 38 | + /// 0 if a > b => { |
| 39 | + /// return; |
| 40 | + /// } |
| 41 | + /// _ => {} |
| 42 | + /// } |
| 43 | + /// ``` |
| 44 | + #[clippy::version = "1.89.0"] |
| 45 | + pub DUPLICATE_MATCH_GUARD, |
| 46 | + nursery, |
| 47 | + "a condition in match body duplicating the match guard" |
| 48 | +} |
| 49 | +declare_lint_pass!(DuplicateMatchGuard => [DUPLICATE_MATCH_GUARD]); |
| 50 | + |
| 51 | +impl<'tcx> LateLintPass<'tcx> for DuplicateMatchGuard { |
| 52 | + fn check_arm(&mut self, cx: &LateContext<'tcx>, arm: &'tcx Arm<'tcx>) { |
| 53 | + if let Some(guard) = arm.guard |
| 54 | + && let ExprKind::Block(block, _) = arm.body.kind |
| 55 | + && block.stmts.is_empty() |
| 56 | + && let Some(trailing_expr) = block.expr |
| 57 | + && let ExprKind::If(cond, _, None) = trailing_expr.kind |
| 58 | + && eq_expr_value(cx, guard, cond.peel_drop_temps()) |
| 59 | + { |
| 60 | + span_lint(cx, DUPLICATE_MATCH_GUARD, cond.span, "condition duplicates match guard"); |
| 61 | + } |
| 62 | + } |
| 63 | +} |
0 commit comments