about summary refs log tree commit diff
path: root/clippy_lints/src/unneeded_struct_pattern.rs
blob: a74eab8b6ae50d193329c83d1507a8a1a273e977 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::is_from_proc_macro;
use rustc_errors::Applicability;
use rustc_hir::def::{DefKind, Res};
use rustc_hir::{Pat, PatKind, QPath};
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::declare_lint_pass;

declare_clippy_lint! {
    /// ### What it does
    /// Checks for struct patterns that match against unit variant.
    ///
    /// ### Why is this bad?
    /// Struct pattern `{ }` or `{ .. }` is not needed for unit variant.
    ///
    /// ### Example
    /// ```no_run
    /// match Some(42) {
    ///     Some(v) => v,
    ///     None { .. } => 0,
    /// };
    /// // Or
    /// match Some(42) {
    ///     Some(v) => v,
    ///     None { } => 0,
    /// };
    /// ```
    /// Use instead:
    /// ```no_run
    /// match Some(42) {
    ///     Some(v) => v,
    ///     None => 0,
    /// };
    /// ```
    #[clippy::version = "1.86.0"]
    pub UNNEEDED_STRUCT_PATTERN,
    style,
    "using struct pattern to match against unit variant"
}

declare_lint_pass!(UnneededStructPattern => [UNNEEDED_STRUCT_PATTERN]);

impl LateLintPass<'_> for UnneededStructPattern {
    fn check_pat(&mut self, cx: &LateContext<'_>, pat: &Pat<'_>) {
        if !pat.span.from_expansion()
            && let PatKind::Struct(path, [], _) = &pat.kind
            && let QPath::Resolved(_, path) = path
            && let Res::Def(DefKind::Variant, did) = path.res
        {
            let enum_did = cx.tcx.parent(did);
            let variant = cx.tcx.adt_def(enum_did).variant_with_id(did);

            let has_only_fields_brackets = variant.ctor.is_some() && variant.fields.is_empty();
            let non_exhaustive_activated = !variant.def_id.is_local() && variant.is_field_list_non_exhaustive();
            if !has_only_fields_brackets || non_exhaustive_activated {
                return;
            }

            if is_from_proc_macro(cx, *path) {
                return;
            }

            if let Some(brackets_span) = pat.span.trim_start(path.span) {
                span_lint_and_sugg(
                    cx,
                    UNNEEDED_STRUCT_PATTERN,
                    brackets_span,
                    "struct pattern is not needed for a unit variant",
                    "remove the struct pattern",
                    String::new(),
                    Applicability::MachineApplicable,
                );
            }
        }
    }
}