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