]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/enum_variants.rs
Rollup merge of #82917 - cuviper:iter-zip, r=m-ou-se
[rust.git] / 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::camel_case;
4 use clippy_utils::diagnostics::{span_lint, span_lint_and_help};
5 use clippy_utils::source::is_present_in_source;
6 use rustc_ast::ast::{EnumDef, Item, ItemKind, VisibilityKind};
7 use rustc_lint::{EarlyContext, EarlyLintPass, Lint};
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:** Detects enumeration variants that are prefixed or suffixed
14     /// by the same characters.
15     ///
16     /// **Why is this bad?** Enumeration variant names should specify their variant,
17     /// not repeat the enumeration name.
18     ///
19     /// **Known problems:** None.
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     pub ENUM_VARIANT_NAMES,
38     style,
39     "enums where all variants share a prefix/postfix"
40 }
41
42 declare_clippy_lint! {
43     /// **What it does:** Detects public enumeration variants that are
44     /// prefixed or suffixed by the same characters.
45     ///
46     /// **Why is this bad?** Public enumeration variant names should specify their variant,
47     /// not repeat the enumeration name.
48     ///
49     /// **Known problems:** None.
50     ///
51     /// **Example:**
52     /// ```rust
53     /// pub enum Cake {
54     ///     BlackForestCake,
55     ///     HummingbirdCake,
56     ///     BattenbergCake,
57     /// }
58     /// ```
59     /// Could be written as:
60     /// ```rust
61     /// pub enum Cake {
62     ///     BlackForest,
63     ///     Hummingbird,
64     ///     Battenberg,
65     /// }
66     /// ```
67     pub PUB_ENUM_VARIANT_NAMES,
68     pedantic,
69     "public enums where all variants share a prefix/postfix"
70 }
71
72 declare_clippy_lint! {
73     /// **What it does:** Detects type names that are prefixed or suffixed by the
74     /// containing module's name.
75     ///
76     /// **Why is this bad?** It requires the user to type the module name twice.
77     ///
78     /// **Known problems:** None.
79     ///
80     /// **Example:**
81     /// ```rust
82     /// mod cake {
83     ///     struct BlackForestCake;
84     /// }
85     /// ```
86     /// Could be written as:
87     /// ```rust
88     /// mod cake {
89     ///     struct BlackForest;
90     /// }
91     /// ```
92     pub MODULE_NAME_REPETITIONS,
93     pedantic,
94     "type names prefixed/postfixed with their containing module's name"
95 }
96
97 declare_clippy_lint! {
98     /// **What it does:** Checks for modules that have the same name as their
99     /// parent module
100     ///
101     /// **Why is this bad?** A typical beginner mistake is to have `mod foo;` and
102     /// again `mod foo { ..
103     /// }` in `foo.rs`.
104     /// The expectation is that items inside the inner `mod foo { .. }` are then
105     /// available
106     /// through `foo::x`, but they are only available through
107     /// `foo::foo::x`.
108     /// If this is done on purpose, it would be better to choose a more
109     /// representative module name.
110     ///
111     /// **Known problems:** None.
112     ///
113     /// **Example:**
114     /// ```ignore
115     /// // lib.rs
116     /// mod foo;
117     /// // foo.rs
118     /// mod foo {
119     ///     ...
120     /// }
121     /// ```
122     pub MODULE_INCEPTION,
123     style,
124     "modules that have the same name as their parent module"
125 }
126
127 pub struct EnumVariantNames {
128     modules: Vec<(Symbol, String)>,
129     threshold: u64,
130 }
131
132 impl EnumVariantNames {
133     #[must_use]
134     pub fn new(threshold: u64) -> Self {
135         Self {
136             modules: Vec::new(),
137             threshold,
138         }
139     }
140 }
141
142 impl_lint_pass!(EnumVariantNames => [
143     ENUM_VARIANT_NAMES,
144     PUB_ENUM_VARIANT_NAMES,
145     MODULE_NAME_REPETITIONS,
146     MODULE_INCEPTION
147 ]);
148
149 /// Returns the number of chars that match from the start
150 #[must_use]
151 fn partial_match(pre: &str, name: &str) -> usize {
152     let mut name_iter = name.chars();
153     let _ = name_iter.next_back(); // make sure the name is never fully matched
154     pre.chars().zip(name_iter).take_while(|&(l, r)| l == r).count()
155 }
156
157 /// Returns the number of chars that match from the end
158 #[must_use]
159 fn partial_rmatch(post: &str, name: &str) -> usize {
160     let mut name_iter = name.chars();
161     let _ = name_iter.next(); // make sure the name is never fully matched
162     post.chars()
163         .rev()
164         .zip(name_iter.rev())
165         .take_while(|&(l, r)| l == r)
166         .count()
167 }
168
169 fn check_variant(
170     cx: &EarlyContext<'_>,
171     threshold: u64,
172     def: &EnumDef,
173     item_name: &str,
174     item_name_chars: usize,
175     span: Span,
176     lint: &'static Lint,
177 ) {
178     if (def.variants.len() as u64) < threshold {
179         return;
180     }
181     for var in &def.variants {
182         let name = var.ident.name.as_str();
183         if partial_match(item_name, &name) == item_name_chars
184             && name.chars().nth(item_name_chars).map_or(false, |c| !c.is_lowercase())
185             && name.chars().nth(item_name_chars + 1).map_or(false, |c| !c.is_numeric())
186         {
187             span_lint(cx, lint, var.span, "variant name starts with the enum's name");
188         }
189         if partial_rmatch(item_name, &name) == item_name_chars {
190             span_lint(cx, lint, var.span, "variant name ends with the enum's name");
191         }
192     }
193     let first = &def.variants[0].ident.name.as_str();
194     let mut pre = &first[..camel_case::until(&*first)];
195     let mut post = &first[camel_case::from(&*first)..];
196     for var in &def.variants {
197         let name = var.ident.name.as_str();
198
199         let pre_match = partial_match(pre, &name);
200         pre = &pre[..pre_match];
201         let pre_camel = camel_case::until(pre);
202         pre = &pre[..pre_camel];
203         while let Some((next, last)) = name[pre.len()..].chars().zip(pre.chars().rev()).next() {
204             if next.is_numeric() {
205                 return;
206             }
207             if next.is_lowercase() {
208                 let last = pre.len() - last.len_utf8();
209                 let last_camel = camel_case::until(&pre[..last]);
210                 pre = &pre[..last_camel];
211             } else {
212                 break;
213             }
214         }
215
216         let post_match = partial_rmatch(post, &name);
217         let post_end = post.len() - post_match;
218         post = &post[post_end..];
219         let post_camel = camel_case::from(post);
220         post = &post[post_camel..];
221     }
222     let (what, value) = match (pre.is_empty(), post.is_empty()) {
223         (true, true) => return,
224         (false, _) => ("pre", pre),
225         (true, false) => ("post", post),
226     };
227     span_lint_and_help(
228         cx,
229         lint,
230         span,
231         &format!("all variants have the same {}fix: `{}`", what, value),
232         None,
233         &format!(
234             "remove the {}fixes and use full paths to \
235              the variants instead of glob imports",
236             what
237         ),
238     );
239 }
240
241 #[must_use]
242 fn to_camel_case(item_name: &str) -> String {
243     let mut s = String::new();
244     let mut up = true;
245     for c in item_name.chars() {
246         if c.is_uppercase() {
247             // we only turn snake case text into CamelCase
248             return item_name.to_string();
249         }
250         if c == '_' {
251             up = true;
252             continue;
253         }
254         if up {
255             up = false;
256             s.extend(c.to_uppercase());
257         } else {
258             s.push(c);
259         }
260     }
261     s
262 }
263
264 impl EarlyLintPass for EnumVariantNames {
265     fn check_item_post(&mut self, _cx: &EarlyContext<'_>, _item: &Item) {
266         let last = self.modules.pop();
267         assert!(last.is_some());
268     }
269
270     #[allow(clippy::similar_names)]
271     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &Item) {
272         let item_name = item.ident.name.as_str();
273         let item_name_chars = item_name.chars().count();
274         let item_camel = to_camel_case(&item_name);
275         if !item.span.from_expansion() && is_present_in_source(cx, item.span) {
276             if let Some(&(ref mod_name, ref mod_camel)) = self.modules.last() {
277                 // constants don't have surrounding modules
278                 if !mod_camel.is_empty() {
279                     if mod_name == &item.ident.name {
280                         if let ItemKind::Mod(..) = item.kind {
281                             span_lint(
282                                 cx,
283                                 MODULE_INCEPTION,
284                                 item.span,
285                                 "module has the same name as its containing module",
286                             );
287                         }
288                     }
289                     if item.vis.kind.is_pub() {
290                         let matching = partial_match(mod_camel, &item_camel);
291                         let rmatching = partial_rmatch(mod_camel, &item_camel);
292                         let nchars = mod_camel.chars().count();
293
294                         let is_word_beginning = |c: char| c == '_' || c.is_uppercase() || c.is_numeric();
295
296                         if matching == nchars {
297                             match item_camel.chars().nth(nchars) {
298                                 Some(c) if is_word_beginning(c) => span_lint(
299                                     cx,
300                                     MODULE_NAME_REPETITIONS,
301                                     item.span,
302                                     "item name starts with its containing module's name",
303                                 ),
304                                 _ => (),
305                             }
306                         }
307                         if rmatching == nchars {
308                             span_lint(
309                                 cx,
310                                 MODULE_NAME_REPETITIONS,
311                                 item.span,
312                                 "item name ends with its containing module's name",
313                             );
314                         }
315                     }
316                 }
317             }
318         }
319         if let ItemKind::Enum(ref def, _) = item.kind {
320             let lint = match item.vis.kind {
321                 VisibilityKind::Public => PUB_ENUM_VARIANT_NAMES,
322                 _ => ENUM_VARIANT_NAMES,
323             };
324             check_variant(cx, self.threshold, def, &item_name, item_name_chars, item.span, lint);
325         }
326         self.modules.push((item.ident.name, item_camel));
327     }
328 }