]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/enum_variants.rs
Auto merge of #3645 - phansch:remove_copyright_headers, r=oli-obk
[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 crate::utils::{camel_case, in_macro};
4 use crate::utils::{span_help_and_lint, span_lint};
5 use rustc::lint::{EarlyContext, EarlyLintPass, Lint, LintArray, LintPass};
6 use rustc::{declare_tool_lint, lint_array};
7 use syntax::ast::*;
8 use syntax::source_map::Span;
9 use syntax::symbol::{InternedString, LocalInternedString};
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 MODULE_NAME_REPETITIONS,
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<(InternedString, 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!(
121             ENUM_VARIANT_NAMES,
122             PUB_ENUM_VARIANT_NAMES,
123             MODULE_NAME_REPETITIONS,
124             MODULE_INCEPTION
125         )
126     }
127 }
128
129 fn var2str(var: &Variant) -> LocalInternedString {
130     var.node.ident.as_str()
131 }
132
133 /// Returns the number of chars that match from the start
134 fn partial_match(pre: &str, name: &str) -> usize {
135     let mut name_iter = name.chars();
136     let _ = name_iter.next_back(); // make sure the name is never fully matched
137     pre.chars().zip(name_iter).take_while(|&(l, r)| l == r).count()
138 }
139
140 /// Returns the number of chars that match from the end
141 fn partial_rmatch(post: &str, name: &str) -> usize {
142     let mut name_iter = name.chars();
143     let _ = name_iter.next(); // make sure the name is never fully matched
144     post.chars()
145         .rev()
146         .zip(name_iter.rev())
147         .take_while(|&(l, r)| l == r)
148         .count()
149 }
150
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().nth(item_name_chars).map_or(false, |c| !c.is_lowercase())
167         {
168             span_lint(cx, lint, var.span, "Variant name starts with the enum's name");
169         }
170         if partial_rmatch(item_name, &name) == item_name_chars {
171             span_lint(cx, lint, var.span, "Variant name ends with the enum's name");
172         }
173     }
174     let first = var2str(&def.variants[0]);
175     let mut pre = &first[..camel_case::until(&*first)];
176     let mut post = &first[camel_case::from(&*first)..];
177     for var in &def.variants {
178         let name = var2str(var);
179
180         let pre_match = partial_match(pre, &name);
181         pre = &pre[..pre_match];
182         let pre_camel = camel_case::until(pre);
183         pre = &pre[..pre_camel];
184         while let Some((next, last)) = name[pre.len()..].chars().zip(pre.chars().rev()).next() {
185             if next.is_lowercase() {
186                 let last = pre.len() - last.len_utf8();
187                 let last_camel = camel_case::until(&pre[..last]);
188                 pre = &pre[..last_camel];
189             } else {
190                 break;
191             }
192         }
193
194         let post_match = partial_rmatch(post, &name);
195         let post_end = post.len() - post_match;
196         post = &post[post_end..];
197         let post_camel = camel_case::from(post);
198         post = &post[post_camel..];
199     }
200     let (what, value) = match (pre.is_empty(), post.is_empty()) {
201         (true, true) => return,
202         (false, _) => ("pre", pre),
203         (true, false) => ("post", post),
204     };
205     span_help_and_lint(
206         cx,
207         lint,
208         span,
209         &format!("All variants have the same {}fix: `{}`", what, value),
210         &format!(
211             "remove the {}fixes and use full paths to \
212              the variants instead of glob imports",
213             what
214         ),
215     );
216 }
217
218 fn to_camel_case(item_name: &str) -> String {
219     let mut s = String::new();
220     let mut up = true;
221     for c in item_name.chars() {
222         if c.is_uppercase() {
223             // we only turn snake case text into CamelCase
224             return item_name.to_string();
225         }
226         if c == '_' {
227             up = true;
228             continue;
229         }
230         if up {
231             up = false;
232             s.extend(c.to_uppercase());
233         } else {
234             s.push(c);
235         }
236     }
237     s
238 }
239
240 impl EarlyLintPass for EnumVariantNames {
241     fn check_item_post(&mut self, _cx: &EarlyContext<'_>, _item: &Item) {
242         let last = self.modules.pop();
243         assert!(last.is_some());
244     }
245
246     #[allow(clippy::similar_names)]
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.is_pub() {
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| c == '_' || c.is_uppercase() || c.is_numeric();
271
272                         if matching == nchars {
273                             match item_camel.chars().nth(nchars) {
274                                 Some(c) if is_word_beginning(c) => span_lint(
275                                     cx,
276                                     MODULE_NAME_REPETITIONS,
277                                     item.span,
278                                     "item name starts with its containing module's name",
279                                 ),
280                                 _ => (),
281                             }
282                         }
283                         if rmatching == nchars {
284                             span_lint(
285                                 cx,
286                                 MODULE_NAME_REPETITIONS,
287                                 item.span,
288                                 "item name ends with its containing module's name",
289                             );
290                         }
291                     }
292                 }
293             }
294         }
295         if let ItemKind::Enum(ref def, _) = item.node {
296             let lint = match item.vis.node {
297                 VisibilityKind::Public => PUB_ENUM_VARIANT_NAMES,
298                 _ => ENUM_VARIANT_NAMES,
299             };
300             check_variant(cx, self.threshold, def, &item_name, item_name_chars, item.span, lint);
301         }
302         self.modules.push((item_name.as_interned_str(), item_camel));
303     }
304 }