]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/manual_non_exhaustive.rs
Auto merge of #7016 - camsteffen:bind-map-paths, r=Manishearth
[rust.git] / clippy_lints / src / manual_non_exhaustive.rs
1 use clippy_utils::attrs::is_doc_hidden;
2 use clippy_utils::diagnostics::span_lint_and_then;
3 use clippy_utils::meets_msrv;
4 use clippy_utils::source::snippet_opt;
5 use if_chain::if_chain;
6 use rustc_ast::ast::{FieldDef, Item, ItemKind, Variant, VariantData, VisibilityKind};
7 use rustc_errors::Applicability;
8 use rustc_lint::{EarlyContext, EarlyLintPass};
9 use rustc_semver::RustcVersion;
10 use rustc_session::{declare_tool_lint, impl_lint_pass};
11 use rustc_span::{sym, Span};
12
13 const MANUAL_NON_EXHAUSTIVE_MSRV: RustcVersion = RustcVersion::new(1, 40, 0);
14
15 declare_clippy_lint! {
16     /// **What it does:** Checks for manual implementations of the non-exhaustive pattern.
17     ///
18     /// **Why is this bad?** Using the #[non_exhaustive] attribute expresses better the intent
19     /// and allows possible optimizations when applied to enums.
20     ///
21     /// **Known problems:** None.
22     ///
23     /// **Example:**
24     ///
25     /// ```rust
26     /// struct S {
27     ///     pub a: i32,
28     ///     pub b: i32,
29     ///     _c: (),
30     /// }
31     ///
32     /// enum E {
33     ///     A,
34     ///     B,
35     ///     #[doc(hidden)]
36     ///     _C,
37     /// }
38     ///
39     /// struct T(pub i32, pub i32, ());
40     /// ```
41     /// Use instead:
42     /// ```rust
43     /// #[non_exhaustive]
44     /// struct S {
45     ///     pub a: i32,
46     ///     pub b: i32,
47     /// }
48     ///
49     /// #[non_exhaustive]
50     /// enum E {
51     ///     A,
52     ///     B,
53     /// }
54     ///
55     /// #[non_exhaustive]
56     /// struct T(pub i32, pub i32);
57     /// ```
58     pub MANUAL_NON_EXHAUSTIVE,
59     style,
60     "manual implementations of the non-exhaustive pattern can be simplified using #[non_exhaustive]"
61 }
62
63 #[derive(Clone)]
64 pub struct ManualNonExhaustive {
65     msrv: Option<RustcVersion>,
66 }
67
68 impl ManualNonExhaustive {
69     #[must_use]
70     pub fn new(msrv: Option<RustcVersion>) -> Self {
71         Self { msrv }
72     }
73 }
74
75 impl_lint_pass!(ManualNonExhaustive => [MANUAL_NON_EXHAUSTIVE]);
76
77 impl EarlyLintPass for ManualNonExhaustive {
78     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &Item) {
79         if !meets_msrv(self.msrv.as_ref(), &MANUAL_NON_EXHAUSTIVE_MSRV) {
80             return;
81         }
82
83         match &item.kind {
84             ItemKind::Enum(def, _) => {
85                 check_manual_non_exhaustive_enum(cx, item, &def.variants);
86             },
87             ItemKind::Struct(variant_data, _) => {
88                 if let VariantData::Unit(..) = variant_data {
89                     return;
90                 }
91
92                 check_manual_non_exhaustive_struct(cx, item, variant_data);
93             },
94             _ => {},
95         }
96     }
97
98     extract_msrv_attr!(EarlyContext);
99 }
100
101 fn check_manual_non_exhaustive_enum(cx: &EarlyContext<'_>, item: &Item, variants: &[Variant]) {
102     fn is_non_exhaustive_marker(variant: &Variant) -> bool {
103         matches!(variant.data, VariantData::Unit(_))
104             && variant.ident.as_str().starts_with('_')
105             && is_doc_hidden(&variant.attrs)
106     }
107
108     let mut markers = variants.iter().filter(|v| is_non_exhaustive_marker(v));
109     if_chain! {
110         if let Some(marker) = markers.next();
111         if markers.count() == 0 && variants.len() > 1;
112         then {
113             span_lint_and_then(
114                 cx,
115                 MANUAL_NON_EXHAUSTIVE,
116                 item.span,
117                 "this seems like a manual implementation of the non-exhaustive pattern",
118                 |diag| {
119                     if_chain! {
120                         if !item.attrs.iter().any(|attr| attr.has_name(sym::non_exhaustive));
121                         let header_span = cx.sess.source_map().span_until_char(item.span, '{');
122                         if let Some(snippet) = snippet_opt(cx, header_span);
123                         then {
124                             diag.span_suggestion(
125                                 header_span,
126                                 "add the attribute",
127                                 format!("#[non_exhaustive] {}", snippet),
128                                 Applicability::Unspecified,
129                             );
130                         }
131                     }
132                     diag.span_help(marker.span, "remove this variant");
133                 });
134         }
135     }
136 }
137
138 fn check_manual_non_exhaustive_struct(cx: &EarlyContext<'_>, item: &Item, data: &VariantData) {
139     fn is_private(field: &FieldDef) -> bool {
140         matches!(field.vis.kind, VisibilityKind::Inherited)
141     }
142
143     fn is_non_exhaustive_marker(field: &FieldDef) -> bool {
144         is_private(field) && field.ty.kind.is_unit() && field.ident.map_or(true, |n| n.as_str().starts_with('_'))
145     }
146
147     fn find_header_span(cx: &EarlyContext<'_>, item: &Item, data: &VariantData) -> Span {
148         let delimiter = match data {
149             VariantData::Struct(..) => '{',
150             VariantData::Tuple(..) => '(',
151             VariantData::Unit(_) => unreachable!("`VariantData::Unit` is already handled above"),
152         };
153
154         cx.sess.source_map().span_until_char(item.span, delimiter)
155     }
156
157     let fields = data.fields();
158     let private_fields = fields.iter().filter(|f| is_private(f)).count();
159     let public_fields = fields.iter().filter(|f| f.vis.kind.is_pub()).count();
160
161     if_chain! {
162         if private_fields == 1 && public_fields >= 1 && public_fields == fields.len() - 1;
163         if let Some(marker) = fields.iter().find(|f| is_non_exhaustive_marker(f));
164         then {
165             span_lint_and_then(
166                 cx,
167                 MANUAL_NON_EXHAUSTIVE,
168                 item.span,
169                 "this seems like a manual implementation of the non-exhaustive pattern",
170                 |diag| {
171                     if_chain! {
172                         if !item.attrs.iter().any(|attr| attr.has_name(sym::non_exhaustive));
173                         let header_span = find_header_span(cx, item, data);
174                         if let Some(snippet) = snippet_opt(cx, header_span);
175                         then {
176                             diag.span_suggestion(
177                                 header_span,
178                                 "add the attribute",
179                                 format!("#[non_exhaustive] {}", snippet),
180                                 Applicability::Unspecified,
181                             );
182                         }
183                     }
184                     diag.span_help(marker.span, "remove this field");
185                 });
186         }
187     }
188 }