|
| 1 | +use clippy_utils::diagnostics::span_lint_and_sugg; |
| 2 | +use rustc_errors::Applicability; |
| 3 | +use rustc_hir::def::{DefKind, Res}; |
| 4 | +use rustc_hir::{Pat, PatKind, QPath}; |
| 5 | +use rustc_lint::{LateContext, LateLintPass}; |
| 6 | +use rustc_session::declare_lint_pass; |
| 7 | + |
| 8 | +declare_clippy_lint! { |
| 9 | + /// ### What it does |
| 10 | + /// Checks for struct patterns that match against unit variant. |
| 11 | + /// |
| 12 | + /// ### Why is this bad? |
| 13 | + /// Struct pattern `{ }` or `{ .. }` is not needed for unit variant. |
| 14 | + /// |
| 15 | + /// ### Example |
| 16 | + /// ```no_run |
| 17 | + /// match Some(42) { |
| 18 | + /// Some(v) => v, |
| 19 | + /// None { .. } => 0, |
| 20 | + /// }; |
| 21 | + /// // Or |
| 22 | + /// match Some(42) { |
| 23 | + /// Some(v) => v, |
| 24 | + /// None { } => 0, |
| 25 | + /// }; |
| 26 | + /// ``` |
| 27 | + /// Use instead: |
| 28 | + /// ```no_run |
| 29 | + /// match Some(42) { |
| 30 | + /// Some(v) => v, |
| 31 | + /// None => 0, |
| 32 | + /// }; |
| 33 | + /// ``` |
| 34 | + #[clippy::version = "1.83.0"] |
| 35 | + pub UNNEEDED_STRUCT_PATTERN, |
| 36 | + nursery, |
| 37 | + "using struct pattern to match against unit variant" |
| 38 | +} |
| 39 | + |
| 40 | +declare_lint_pass!(UnneededStructPattern => [UNNEEDED_STRUCT_PATTERN]); |
| 41 | + |
| 42 | +impl LateLintPass<'_> for UnneededStructPattern { |
| 43 | + fn check_pat(&mut self, cx: &LateContext<'_>, pat: &Pat<'_>) { |
| 44 | + if !pat.span.from_expansion() |
| 45 | + && let PatKind::Struct(path, [], _) = &pat.kind |
| 46 | + && let QPath::Resolved(_, path) = path |
| 47 | + && let Res::Def(DefKind::Variant, did) = path.res |
| 48 | + { |
| 49 | + let enum_did = cx.tcx.parent(did); |
| 50 | + let variant = cx.tcx.adt_def(enum_did).variant_with_id(did); |
| 51 | + |
| 52 | + let has_fields_brackets = !(variant.ctor.is_some() && variant.fields.is_empty()); |
| 53 | + let non_exhaustive_activated = !variant.def_id.is_local() && variant.is_field_list_non_exhaustive(); |
| 54 | + if has_fields_brackets || non_exhaustive_activated { |
| 55 | + return; |
| 56 | + } |
| 57 | + |
| 58 | + if let Some(brackets_span) = pat.span.trim_start(path.span) { |
| 59 | + span_lint_and_sugg( |
| 60 | + cx, |
| 61 | + UNNEEDED_STRUCT_PATTERN, |
| 62 | + brackets_span, |
| 63 | + "struct pattern is not needed for a unit variant", |
| 64 | + "remove the struct pattern", |
| 65 | + String::new(), |
| 66 | + Applicability::Unspecified, |
| 67 | + ); |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | +} |
0 commit comments