]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/enum_variants.rs
Fix 'redudant' spelling in redundant_clone docs
[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, is_present_in_source};
4 use crate::utils::{span_help_and_lint, span_lint};
5 use rustc::impl_lint_pass;
6 use rustc::lint::{EarlyContext, EarlyLintPass, Lint, LintArray, LintPass};
7 use rustc_session::declare_tool_lint;
8 use syntax::ast::*;
9 use syntax::source_map::Span;
10 use syntax::symbol::Symbol;
11
12 declare_clippy_lint! {
13     /// **What it does:** Detects enumeration variants that are prefixed or suffixed
14     /// by the same characters.
15     ///
16     /// **Why is this bad?** Enumeration variant names should specify their variant,
17     /// not repeat the enumeration name.
18     ///
19     /// **Known problems:** None.
20     ///
21     /// **Example:**
22     /// ```rust
23     /// enum Cake {
24     ///     BlackForestCake,
25     ///     HummingbirdCake,
26     ///     BattenbergCake,
27     /// }
28     /// ```
29     pub ENUM_VARIANT_NAMES,
30     style,
31     "enums where all variants share a prefix/postfix"
32 }
33
34 declare_clippy_lint! {
35     /// **What it does:** Detects enumeration variants that are prefixed or suffixed
36     /// by the same characters.
37     ///
38     /// **Why is this bad?** Enumeration variant names should specify their variant,
39     /// not repeat the enumeration name.
40     ///
41     /// **Known problems:** None.
42     ///
43     /// **Example:**
44     /// ```rust
45     /// enum Cake {
46     ///     BlackForestCake,
47     ///     HummingbirdCake,
48     ///     BattenbergCake,
49     /// }
50     /// ```
51     pub PUB_ENUM_VARIANT_NAMES,
52     pedantic,
53     "enums where all variants share a prefix/postfix"
54 }
55
56 declare_clippy_lint! {
57     /// **What it does:** Detects type names that are prefixed or suffixed by the
58     /// containing module's name.
59     ///
60     /// **Why is this bad?** It requires the user to type the module name twice.
61     ///
62     /// **Known problems:** None.
63     ///
64     /// **Example:**
65     /// ```rust
66     /// mod cake {
67     ///     struct BlackForestCake;
68     /// }
69     /// ```
70     pub MODULE_NAME_REPETITIONS,
71     pedantic,
72     "type names prefixed/postfixed with their containing module's name"
73 }
74
75 declare_clippy_lint! {
76     /// **What it does:** Checks for modules that have the same name as their
77     /// parent module
78     ///
79     /// **Why is this bad?** A typical beginner mistake is to have `mod foo;` and
80     /// again `mod foo { ..
81     /// }` in `foo.rs`.
82     /// The expectation is that items inside the inner `mod foo { .. }` are then
83     /// available
84     /// through `foo::x`, but they are only available through
85     /// `foo::foo::x`.
86     /// If this is done on purpose, it would be better to choose a more
87     /// representative module name.
88     ///
89     /// **Known problems:** None.
90     ///
91     /// **Example:**
92     /// ```ignore
93     /// // lib.rs
94     /// mod foo;
95     /// // foo.rs
96     /// mod foo {
97     ///     ...
98     /// }
99     /// ```
100     pub MODULE_INCEPTION,
101     style,
102     "modules that have the same name as their parent module"
103 }
104
105 pub struct EnumVariantNames {
106     modules: Vec<(Symbol, String)>,
107     threshold: u64,
108 }
109
110 impl EnumVariantNames {
111     #[must_use]
112     pub fn new(threshold: u64) -> Self {
113         Self {
114             modules: Vec::new(),
115             threshold,
116         }
117     }
118 }
119
120 impl_lint_pass!(EnumVariantNames => [
121     ENUM_VARIANT_NAMES,
122     PUB_ENUM_VARIANT_NAMES,
123     MODULE_NAME_REPETITIONS,
124     MODULE_INCEPTION
125 ]);
126
127 /// Returns the number of chars that match from the start
128 #[must_use]
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().zip(name_iter).take_while(|&(l, r)| l == r).count()
133 }
134
135 /// Returns the number of chars that match from the end
136 #[must_use]
137 fn partial_rmatch(post: &str, name: &str) -> usize {
138     let mut name_iter = name.chars();
139     let _ = name_iter.next(); // make sure the name is never fully matched
140     post.chars()
141         .rev()
142         .zip(name_iter.rev())
143         .take_while(|&(l, r)| l == r)
144         .count()
145 }
146
147 fn check_variant(
148     cx: &EarlyContext<'_>,
149     threshold: u64,
150     def: &EnumDef,
151     item_name: &str,
152     item_name_chars: usize,
153     span: Span,
154     lint: &'static Lint,
155 ) {
156     if (def.variants.len() as u64) < threshold {
157         return;
158     }
159     for var in &def.variants {
160         let name = var.ident.name.as_str();
161         if partial_match(item_name, &name) == item_name_chars
162             && name.chars().nth(item_name_chars).map_or(false, |c| !c.is_lowercase())
163             && name.chars().nth(item_name_chars + 1).map_or(false, |c| !c.is_numeric())
164         {
165             span_lint(cx, lint, var.span, "Variant name starts with the enum's name");
166         }
167         if partial_rmatch(item_name, &name) == item_name_chars {
168             span_lint(cx, lint, var.span, "Variant name ends with the enum's name");
169         }
170     }
171     let first = &def.variants[0].ident.name.as_str();
172     let mut pre = &first[..camel_case::until(&*first)];
173     let mut post = &first[camel_case::from(&*first)..];
174     for var in &def.variants {
175         let name = var.ident.name.as_str();
176
177         let pre_match = partial_match(pre, &name);
178         pre = &pre[..pre_match];
179         let pre_camel = camel_case::until(pre);
180         pre = &pre[..pre_camel];
181         while let Some((next, last)) = name[pre.len()..].chars().zip(pre.chars().rev()).next() {
182             if next.is_numeric() {
183                 return;
184             }
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 #[must_use]
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     #[allow(clippy::similar_names)]
248     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &Item) {
249         let item_name = item.ident.name.as_str();
250         let item_name_chars = item_name.chars().count();
251         let item_camel = to_camel_case(&item_name);
252         if !item.span.from_expansion() && is_present_in_source(cx, 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.ident.name {
257                         if let ItemKind::Mod(..) = item.kind {
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| c == '_' || c.is_uppercase() || c.is_numeric();
272
273                         if matching == nchars {
274                             match item_camel.chars().nth(nchars) {
275                                 Some(c) if is_word_beginning(c) => span_lint(
276                                     cx,
277                                     MODULE_NAME_REPETITIONS,
278                                     item.span,
279                                     "item name starts with its containing module's name",
280                                 ),
281                                 _ => (),
282                             }
283                         }
284                         if rmatching == nchars {
285                             span_lint(
286                                 cx,
287                                 MODULE_NAME_REPETITIONS,
288                                 item.span,
289                                 "item name ends with its containing module's name",
290                             );
291                         }
292                     }
293                 }
294             }
295         }
296         if let ItemKind::Enum(ref def, _) = item.kind {
297             let lint = match item.vis.node {
298                 VisibilityKind::Public => PUB_ENUM_VARIANT_NAMES,
299                 _ => ENUM_VARIANT_NAMES,
300             };
301             check_variant(cx, self.threshold, def, &item_name, item_name_chars, item.span, lint);
302         }
303         self.modules.push((item.ident.name, item_camel));
304     }
305 }