|
| 1 | +use clippy_utils::diagnostics::span_lint_and_sugg; |
| 2 | +use rustc_errors::Applicability; |
| 3 | +use rustc_hir::{ExprKind, MatchSource, Stmt, StmtKind}; |
| 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 presence of a semicolon at the end of |
| 10 | + /// a `match` or `if` statement evaluating to `()`. |
| 11 | + /// |
| 12 | + /// ### Why is this bad? |
| 13 | + /// The semicolon is not needed, and may be removed to |
| 14 | + /// avoid confusion and visual clutter. |
| 15 | + /// |
| 16 | + /// ### Example |
| 17 | + /// ```no_run |
| 18 | + /// # let a: u32 = 42; |
| 19 | + /// if a > 10 { |
| 20 | + /// println!("a is greater than 10"); |
| 21 | + /// }; |
| 22 | + /// ``` |
| 23 | + /// Use instead: |
| 24 | + /// ```no_run |
| 25 | + /// # let a: u32 = 42; |
| 26 | + /// if a > 10 { |
| 27 | + /// println!("a is greater than 10"); |
| 28 | + /// } |
| 29 | + /// ``` |
| 30 | + #[clippy::version = "1.86.0"] |
| 31 | + pub UNNECESSARY_SEMICOLON, |
| 32 | + pedantic, |
| 33 | + "unnecessary semicolon after expression returning `()`" |
| 34 | +} |
| 35 | + |
| 36 | +declare_lint_pass!(UnnecessarySemicolon => [UNNECESSARY_SEMICOLON]); |
| 37 | + |
| 38 | +impl LateLintPass<'_> for UnnecessarySemicolon { |
| 39 | + fn check_stmt(&mut self, cx: &LateContext<'_>, stmt: &Stmt<'_>) { |
| 40 | + // rustfmt already takes care of removing semicolons at the end |
| 41 | + // of loops. |
| 42 | + if let StmtKind::Semi(expr) = stmt.kind |
| 43 | + && !stmt.span.from_expansion() |
| 44 | + && !expr.span.from_expansion() |
| 45 | + && matches!( |
| 46 | + expr.kind, |
| 47 | + ExprKind::If(..) | ExprKind::Match(_, _, MatchSource::Normal | MatchSource::Postfix) |
| 48 | + ) |
| 49 | + && cx.typeck_results().expr_ty(expr) == cx.tcx.types.unit |
| 50 | + { |
| 51 | + let semi_span = expr.span.shrink_to_hi().to(stmt.span.shrink_to_hi()); |
| 52 | + span_lint_and_sugg( |
| 53 | + cx, |
| 54 | + UNNECESSARY_SEMICOLON, |
| 55 | + semi_span, |
| 56 | + "unnecessary semicolon", |
| 57 | + "remove", |
| 58 | + String::new(), |
| 59 | + Applicability::MachineApplicable, |
| 60 | + ); |
| 61 | + } |
| 62 | + } |
| 63 | +} |
0 commit comments