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