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