|
| 1 | +use clippy_utils::diagnostics::span_lint_and_sugg; |
| 2 | +use hir::PatKind; |
| 3 | +use rustc_errors::Applicability; |
| 4 | +use rustc_hir as hir; |
| 5 | +use rustc_lint::{LateContext, LateLintPass}; |
| 6 | +use rustc_session::{declare_lint_pass, declare_tool_lint}; |
| 7 | + |
| 8 | +declare_clippy_lint! { |
| 9 | + /// ### What it does |
| 10 | + /// Checks for usage of `_` in patterns of type `()`. |
| 11 | + /// |
| 12 | + /// ### Why is this bad? |
| 13 | + /// Matching with `()` explicitly instead of `_` outlines |
| 14 | + /// the fact that the pattern contains no data. Also it |
| 15 | + /// would detect a type change that `_` would ignore. |
| 16 | + /// |
| 17 | + /// ### Example |
| 18 | + /// ```rust |
| 19 | + /// match std::fs::create_dir("tmp-work-dir") { |
| 20 | + /// Ok(_) => println!("Working directory created"), |
| 21 | + /// Err(s) => eprintln!("Could not create directory: {s}"), |
| 22 | + /// } |
| 23 | + /// ``` |
| 24 | + /// Use instead: |
| 25 | + /// ```rust |
| 26 | + /// match std::fs::create_dir("tmp-work-dir") { |
| 27 | + /// Ok(()) => println!("Working directory created"), |
| 28 | + /// Err(s) => eprintln!("Could not create directory: {s}"), |
| 29 | + /// } |
| 30 | + /// ``` |
| 31 | + #[clippy::version = "1.73.0"] |
| 32 | + pub IGNORED_UNIT_PATTERNS, |
| 33 | + pedantic, |
| 34 | + "suggest replacing `_` by `()` in patterns where appropriate" |
| 35 | +} |
| 36 | +declare_lint_pass!(IgnoredUnitPatterns => [IGNORED_UNIT_PATTERNS]); |
| 37 | + |
| 38 | +impl<'tcx> LateLintPass<'tcx> for IgnoredUnitPatterns { |
| 39 | + fn check_pat(&mut self, cx: &LateContext<'tcx>, pat: &'tcx hir::Pat<'tcx>) { |
| 40 | + if matches!(pat.kind, PatKind::Wild) && cx.typeck_results().pat_ty(pat).is_unit() { |
| 41 | + span_lint_and_sugg( |
| 42 | + cx, |
| 43 | + IGNORED_UNIT_PATTERNS, |
| 44 | + pat.span, |
| 45 | + "matching over `()` is more explicit", |
| 46 | + "use `()` instead of `_`", |
| 47 | + String::from("()"), |
| 48 | + Applicability::MachineApplicable, |
| 49 | + ); |
| 50 | + } |
| 51 | + } |
| 52 | +} |
0 commit comments