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