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