]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/enum_variants.rs
Run rustfmt on clippy_lints
[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 STUTTER,
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!(ENUM_VARIANT_NAMES, PUB_ENUM_VARIANT_NAMES, STUTTER, MODULE_INCEPTION)
130     }
131 }
132
133 fn var2str(var: &Variant) -> LocalInternedString {
134     var.node.ident.as_str()
135 }
136
137 /// Returns the number of chars that match from the start
138 fn partial_match(pre: &str, name: &str) -> usize {
139     let mut name_iter = name.chars();
140     let _ = name_iter.next_back(); // make sure the name is never fully matched
141     pre.chars().zip(name_iter).take_while(|&(l, r)| l == r).count()
142 }
143
144 /// Returns the number of chars that match from the end
145 fn partial_rmatch(post: &str, name: &str) -> usize {
146     let mut name_iter = name.chars();
147     let _ = name_iter.next(); // make sure the name is never fully matched
148     post.chars()
149         .rev()
150         .zip(name_iter.rev())
151         .take_while(|&(l, r)| l == r)
152         .count()
153 }
154
155 fn check_variant(
156     cx: &EarlyContext<'_>,
157     threshold: u64,
158     def: &EnumDef,
159     item_name: &str,
160     item_name_chars: usize,
161     span: Span,
162     lint: &'static Lint,
163 ) {
164     if (def.variants.len() as u64) < threshold {
165         return;
166     }
167     for var in &def.variants {
168         let name = var2str(var);
169         if partial_match(item_name, &name) == item_name_chars
170             && name.chars().nth(item_name_chars).map_or(false, |c| !c.is_lowercase())
171         {
172             span_lint(cx, lint, var.span, "Variant name starts with the enum's name");
173         }
174         if partial_rmatch(item_name, &name) == item_name_chars {
175             span_lint(cx, lint, var.span, "Variant name ends with the enum's name");
176         }
177     }
178     let first = var2str(&def.variants[0]);
179     let mut pre = &first[..camel_case::until(&*first)];
180     let mut post = &first[camel_case::from(&*first)..];
181     for var in &def.variants {
182         let name = var2str(var);
183
184         let pre_match = partial_match(pre, &name);
185         pre = &pre[..pre_match];
186         let pre_camel = camel_case::until(pre);
187         pre = &pre[..pre_camel];
188         while let Some((next, last)) = name[pre.len()..].chars().zip(pre.chars().rev()).next() {
189             if next.is_lowercase() {
190                 let last = pre.len() - last.len_utf8();
191                 let last_camel = camel_case::until(&pre[..last]);
192                 pre = &pre[..last_camel];
193             } else {
194                 break;
195             }
196         }
197
198         let post_match = partial_rmatch(post, &name);
199         let post_end = post.len() - post_match;
200         post = &post[post_end..];
201         let post_camel = camel_case::from(post);
202         post = &post[post_camel..];
203     }
204     let (what, value) = match (pre.is_empty(), post.is_empty()) {
205         (true, true) => return,
206         (false, _) => ("pre", pre),
207         (true, false) => ("post", post),
208     };
209     span_help_and_lint(
210         cx,
211         lint,
212         span,
213         &format!("All variants have the same {}fix: `{}`", what, value),
214         &format!(
215             "remove the {}fixes and use full paths to \
216              the variants instead of glob imports",
217             what
218         ),
219     );
220 }
221
222 fn to_camel_case(item_name: &str) -> String {
223     let mut s = String::new();
224     let mut up = true;
225     for c in item_name.chars() {
226         if c.is_uppercase() {
227             // we only turn snake case text into CamelCase
228             return item_name.to_string();
229         }
230         if c == '_' {
231             up = true;
232             continue;
233         }
234         if up {
235             up = false;
236             s.extend(c.to_uppercase());
237         } else {
238             s.push(c);
239         }
240     }
241     s
242 }
243
244 impl EarlyLintPass for EnumVariantNames {
245     fn check_item_post(&mut self, _cx: &EarlyContext<'_>, _item: &Item) {
246         let last = self.modules.pop();
247         assert!(last.is_some());
248     }
249
250     #[allow(clippy::similar_names)]
251     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &Item) {
252         let item_name = item.ident.as_str();
253         let item_name_chars = item_name.chars().count();
254         let item_camel = to_camel_case(&item_name);
255         if !in_macro(item.span) {
256             if let Some(&(ref mod_name, ref mod_camel)) = self.modules.last() {
257                 // constants don't have surrounding modules
258                 if !mod_camel.is_empty() {
259                     if *mod_name == item_name {
260                         if let ItemKind::Mod(..) = item.node {
261                             span_lint(
262                                 cx,
263                                 MODULE_INCEPTION,
264                                 item.span,
265                                 "module has the same name as its containing module",
266                             );
267                         }
268                     }
269                     if item.vis.node.is_pub() {
270                         let matching = partial_match(mod_camel, &item_camel);
271                         let rmatching = partial_rmatch(mod_camel, &item_camel);
272                         let nchars = mod_camel.chars().count();
273
274                         let is_word_beginning = |c: char| c == '_' || c.is_uppercase() || c.is_numeric();
275
276                         if matching == nchars {
277                             match item_camel.chars().nth(nchars) {
278                                 Some(c) if is_word_beginning(c) => span_lint(
279                                     cx,
280                                     STUTTER,
281                                     item.span,
282                                     "item name starts with its containing module's name",
283                                 ),
284                                 _ => (),
285                             }
286                         }
287                         if rmatching == nchars {
288                             span_lint(
289                                 cx,
290                                 STUTTER,
291                                 item.span,
292                                 "item name ends with its containing module's name",
293                             );
294                         }
295                     }
296                 }
297             }
298         }
299         if let ItemKind::Enum(ref def, _) = item.node {
300             let lint = match item.vis.node {
301                 VisibilityKind::Public => PUB_ENUM_VARIANT_NAMES,
302                 _ => ENUM_VARIANT_NAMES,
303             };
304             check_variant(cx, self.threshold, def, &item_name, item_name_chars, item.span, lint);
305         }
306         self.modules.push((item_name, item_camel));
307     }
308 }