]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/enum_variants.rs
Rollup merge of #90741 - mbartlett21:patch-4, r=dtolnay
[rust.git] / src / tools / clippy / clippy_lints / src / enum_variants.rs
1 //! lint on enum variants that are prefixed or suffixed by the same characters
2
3 use clippy_utils::diagnostics::{span_lint, span_lint_and_help};
4 use clippy_utils::source::is_present_in_source;
5 use clippy_utils::str_utils::{self, count_match_end, count_match_start};
6 use rustc_hir::{EnumDef, Item, ItemKind};
7 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_session::{declare_tool_lint, impl_lint_pass};
9 use rustc_span::source_map::Span;
10 use rustc_span::symbol::Symbol;
11
12 declare_clippy_lint! {
13     /// ### What it does
14     /// Detects enumeration variants that are prefixed or suffixed
15     /// by the same characters.
16     ///
17     /// ### Why is this bad?
18     /// Enumeration variant names should specify their variant,
19     /// not repeat the enumeration name.
20     ///
21     /// ### Example
22     /// ```rust
23     /// enum Cake {
24     ///     BlackForestCake,
25     ///     HummingbirdCake,
26     ///     BattenbergCake,
27     /// }
28     /// ```
29     /// Could be written as:
30     /// ```rust
31     /// enum Cake {
32     ///     BlackForest,
33     ///     Hummingbird,
34     ///     Battenberg,
35     /// }
36     /// ```
37     #[clippy::version = "pre 1.29.0"]
38     pub ENUM_VARIANT_NAMES,
39     style,
40     "enums where all variants share a prefix/postfix"
41 }
42
43 declare_clippy_lint! {
44     /// ### What it does
45     /// Detects type names that are prefixed or suffixed by the
46     /// containing module's name.
47     ///
48     /// ### Why is this bad?
49     /// It requires the user to type the module name twice.
50     ///
51     /// ### Example
52     /// ```rust
53     /// mod cake {
54     ///     struct BlackForestCake;
55     /// }
56     /// ```
57     /// Could be written as:
58     /// ```rust
59     /// mod cake {
60     ///     struct BlackForest;
61     /// }
62     /// ```
63     #[clippy::version = "1.33.0"]
64     pub MODULE_NAME_REPETITIONS,
65     pedantic,
66     "type names prefixed/postfixed with their containing module's name"
67 }
68
69 declare_clippy_lint! {
70     /// ### What it does
71     /// Checks for modules that have the same name as their
72     /// parent module
73     ///
74     /// ### Why is this bad?
75     /// A typical beginner mistake is to have `mod foo;` and
76     /// again `mod foo { ..
77     /// }` in `foo.rs`.
78     /// The expectation is that items inside the inner `mod foo { .. }` are then
79     /// available
80     /// through `foo::x`, but they are only available through
81     /// `foo::foo::x`.
82     /// If this is done on purpose, it would be better to choose a more
83     /// representative module name.
84     ///
85     /// ### Example
86     /// ```ignore
87     /// // lib.rs
88     /// mod foo;
89     /// // foo.rs
90     /// mod foo {
91     ///     ...
92     /// }
93     /// ```
94     #[clippy::version = "pre 1.29.0"]
95     pub MODULE_INCEPTION,
96     style,
97     "modules that have the same name as their parent module"
98 }
99
100 pub struct EnumVariantNames {
101     modules: Vec<(Symbol, String)>,
102     threshold: u64,
103     avoid_breaking_exported_api: bool,
104 }
105
106 impl EnumVariantNames {
107     #[must_use]
108     pub fn new(threshold: u64, avoid_breaking_exported_api: bool) -> Self {
109         Self {
110             modules: Vec::new(),
111             threshold,
112             avoid_breaking_exported_api,
113         }
114     }
115 }
116
117 impl_lint_pass!(EnumVariantNames => [
118     ENUM_VARIANT_NAMES,
119     MODULE_NAME_REPETITIONS,
120     MODULE_INCEPTION
121 ]);
122
123 fn check_variant(
124     cx: &LateContext<'_>,
125     threshold: u64,
126     def: &EnumDef<'_>,
127     item_name: &str,
128     item_name_chars: usize,
129     span: Span,
130 ) {
131     if (def.variants.len() as u64) < threshold {
132         return;
133     }
134     for var in def.variants {
135         let name = var.ident.name.as_str();
136         if count_match_start(item_name, &name).char_count == item_name_chars
137             && name.chars().nth(item_name_chars).map_or(false, |c| !c.is_lowercase())
138             && name.chars().nth(item_name_chars + 1).map_or(false, |c| !c.is_numeric())
139         {
140             span_lint(
141                 cx,
142                 ENUM_VARIANT_NAMES,
143                 var.span,
144                 "variant name starts with the enum's name",
145             );
146         }
147         if count_match_end(item_name, &name).char_count == item_name_chars {
148             span_lint(
149                 cx,
150                 ENUM_VARIANT_NAMES,
151                 var.span,
152                 "variant name ends with the enum's name",
153             );
154         }
155     }
156     let first = &def.variants[0].ident.name.as_str();
157     let mut pre = &first[..str_utils::camel_case_until(&*first).byte_index];
158     let mut post = &first[str_utils::camel_case_start(&*first).byte_index..];
159     for var in def.variants {
160         let name = var.ident.name.as_str();
161
162         let pre_match = count_match_start(pre, &name).byte_count;
163         pre = &pre[..pre_match];
164         let pre_camel = str_utils::camel_case_until(pre).byte_index;
165         pre = &pre[..pre_camel];
166         while let Some((next, last)) = name[pre.len()..].chars().zip(pre.chars().rev()).next() {
167             if next.is_numeric() {
168                 return;
169             }
170             if next.is_lowercase() {
171                 let last = pre.len() - last.len_utf8();
172                 let last_camel = str_utils::camel_case_until(&pre[..last]);
173                 pre = &pre[..last_camel.byte_index];
174             } else {
175                 break;
176             }
177         }
178
179         let post_match = count_match_end(post, &name);
180         let post_end = post.len() - post_match.byte_count;
181         post = &post[post_end..];
182         let post_camel = str_utils::camel_case_start(post);
183         post = &post[post_camel.byte_index..];
184     }
185     let (what, value) = match (pre.is_empty(), post.is_empty()) {
186         (true, true) => return,
187         (false, _) => ("pre", pre),
188         (true, false) => ("post", post),
189     };
190     span_lint_and_help(
191         cx,
192         ENUM_VARIANT_NAMES,
193         span,
194         &format!("all variants have the same {}fix: `{}`", what, value),
195         None,
196         &format!(
197             "remove the {}fixes and use full paths to \
198              the variants instead of glob imports",
199             what
200         ),
201     );
202 }
203
204 #[must_use]
205 fn to_camel_case(item_name: &str) -> String {
206     let mut s = String::new();
207     let mut up = true;
208     for c in item_name.chars() {
209         if c.is_uppercase() {
210             // we only turn snake case text into CamelCase
211             return item_name.to_string();
212         }
213         if c == '_' {
214             up = true;
215             continue;
216         }
217         if up {
218             up = false;
219             s.extend(c.to_uppercase());
220         } else {
221             s.push(c);
222         }
223     }
224     s
225 }
226
227 impl LateLintPass<'_> for EnumVariantNames {
228     fn check_item_post(&mut self, _cx: &LateContext<'_>, _item: &Item<'_>) {
229         let last = self.modules.pop();
230         assert!(last.is_some());
231     }
232
233     #[allow(clippy::similar_names)]
234     fn check_item(&mut self, cx: &LateContext<'_>, item: &Item<'_>) {
235         let item_name = item.ident.name.as_str();
236         let item_name_chars = item_name.chars().count();
237         let item_camel = to_camel_case(&item_name);
238         if !item.span.from_expansion() && is_present_in_source(cx, item.span) {
239             if let Some(&(ref mod_name, ref mod_camel)) = self.modules.last() {
240                 // constants don't have surrounding modules
241                 if !mod_camel.is_empty() {
242                     if mod_name == &item.ident.name {
243                         if let ItemKind::Mod(..) = item.kind {
244                             span_lint(
245                                 cx,
246                                 MODULE_INCEPTION,
247                                 item.span,
248                                 "module has the same name as its containing module",
249                             );
250                         }
251                     }
252                     // The `module_name_repetitions` lint should only trigger if the item has the module in its
253                     // name. Having the same name is accepted.
254                     if item.vis.node.is_pub() && item_camel.len() > mod_camel.len() {
255                         let matching = count_match_start(mod_camel, &item_camel);
256                         let rmatching = count_match_end(mod_camel, &item_camel);
257                         let nchars = mod_camel.chars().count();
258
259                         let is_word_beginning = |c: char| c == '_' || c.is_uppercase() || c.is_numeric();
260
261                         if matching.char_count == nchars {
262                             match item_camel.chars().nth(nchars) {
263                                 Some(c) if is_word_beginning(c) => span_lint(
264                                     cx,
265                                     MODULE_NAME_REPETITIONS,
266                                     item.span,
267                                     "item name starts with its containing module's name",
268                                 ),
269                                 _ => (),
270                             }
271                         }
272                         if rmatching.char_count == nchars {
273                             span_lint(
274                                 cx,
275                                 MODULE_NAME_REPETITIONS,
276                                 item.span,
277                                 "item name ends with its containing module's name",
278                             );
279                         }
280                     }
281                 }
282             }
283         }
284         if let ItemKind::Enum(ref def, _) = item.kind {
285             if !(self.avoid_breaking_exported_api && cx.access_levels.is_exported(item.def_id)) {
286                 check_variant(cx, self.threshold, def, &item_name, item_name_chars, item.span);
287             }
288         }
289         self.modules.push((item.ident.name, item_camel));
290     }
291 }