]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/enum_variants.rs
Auto merge of #4809 - iankronquist:patch-1, r=flip1995
[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_lint, span_lint_and_help};
5 use rustc_lint::{EarlyContext, EarlyLintPass, Lint};
6 use rustc_session::{declare_tool_lint, impl_lint_pass};
7 use rustc_span::source_map::Span;
8 use rustc_span::symbol::Symbol;
9 use syntax::ast::*;
10
11 declare_clippy_lint! {
12     /// **What it does:** Detects enumeration variants that are prefixed or suffixed
13     /// by the same characters.
14     ///
15     /// **Why is this bad?** Enumeration variant names should specify their variant,
16     /// not repeat the enumeration name.
17     ///
18     /// **Known problems:** None.
19     ///
20     /// **Example:**
21     /// ```rust
22     /// enum Cake {
23     ///     BlackForestCake,
24     ///     HummingbirdCake,
25     ///     BattenbergCake,
26     /// }
27     /// ```
28     pub ENUM_VARIANT_NAMES,
29     style,
30     "enums where all variants share a prefix/postfix"
31 }
32
33 declare_clippy_lint! {
34     /// **What it does:** Detects enumeration variants that are prefixed or suffixed
35     /// by the same characters.
36     ///
37     /// **Why is this bad?** Enumeration variant names should specify their variant,
38     /// not repeat the enumeration name.
39     ///
40     /// **Known problems:** None.
41     ///
42     /// **Example:**
43     /// ```rust
44     /// enum Cake {
45     ///     BlackForestCake,
46     ///     HummingbirdCake,
47     ///     BattenbergCake,
48     /// }
49     /// ```
50     pub PUB_ENUM_VARIANT_NAMES,
51     pedantic,
52     "enums where all variants share a prefix/postfix"
53 }
54
55 declare_clippy_lint! {
56     /// **What it does:** Detects type names that are prefixed or suffixed by the
57     /// containing module's name.
58     ///
59     /// **Why is this bad?** It requires the user to type the module name twice.
60     ///
61     /// **Known problems:** None.
62     ///
63     /// **Example:**
64     /// ```rust
65     /// mod cake {
66     ///     struct BlackForestCake;
67     /// }
68     /// ```
69     pub MODULE_NAME_REPETITIONS,
70     pedantic,
71     "type names prefixed/postfixed with their containing module's name"
72 }
73
74 declare_clippy_lint! {
75     /// **What it does:** Checks for modules that have the same name as their
76     /// parent module
77     ///
78     /// **Why is this bad?** A typical beginner mistake is to have `mod foo;` and
79     /// again `mod foo { ..
80     /// }` in `foo.rs`.
81     /// The expectation is that items inside the inner `mod foo { .. }` are then
82     /// available
83     /// through `foo::x`, but they are only available through
84     /// `foo::foo::x`.
85     /// If this is done on purpose, it would be better to choose a more
86     /// representative module name.
87     ///
88     /// **Known problems:** None.
89     ///
90     /// **Example:**
91     /// ```ignore
92     /// // lib.rs
93     /// mod foo;
94     /// // foo.rs
95     /// mod foo {
96     ///     ...
97     /// }
98     /// ```
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<(Symbol, String)>,
106     threshold: u64,
107 }
108
109 impl EnumVariantNames {
110     #[must_use]
111     pub fn new(threshold: u64) -> Self {
112         Self {
113             modules: Vec::new(),
114             threshold,
115         }
116     }
117 }
118
119 impl_lint_pass!(EnumVariantNames => [
120     ENUM_VARIANT_NAMES,
121     PUB_ENUM_VARIANT_NAMES,
122     MODULE_NAME_REPETITIONS,
123     MODULE_INCEPTION
124 ]);
125
126 /// Returns the number of chars that match from the start
127 #[must_use]
128 fn partial_match(pre: &str, name: &str) -> usize {
129     let mut name_iter = name.chars();
130     let _ = name_iter.next_back(); // make sure the name is never fully matched
131     pre.chars().zip(name_iter).take_while(|&(l, r)| l == r).count()
132 }
133
134 /// Returns the number of chars that match from the end
135 #[must_use]
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 fn check_variant(
147     cx: &EarlyContext<'_>,
148     threshold: u64,
149     def: &EnumDef,
150     item_name: &str,
151     item_name_chars: usize,
152     span: Span,
153     lint: &'static Lint,
154 ) {
155     if (def.variants.len() as u64) < threshold {
156         return;
157     }
158     for var in &def.variants {
159         let name = var.ident.name.as_str();
160         if partial_match(item_name, &name) == item_name_chars
161             && name.chars().nth(item_name_chars).map_or(false, |c| !c.is_lowercase())
162             && name.chars().nth(item_name_chars + 1).map_or(false, |c| !c.is_numeric())
163         {
164             span_lint(cx, lint, var.span, "Variant name starts with the enum's name");
165         }
166         if partial_rmatch(item_name, &name) == item_name_chars {
167             span_lint(cx, lint, var.span, "Variant name ends with the enum's name");
168         }
169     }
170     let first = &def.variants[0].ident.name.as_str();
171     let mut pre = &first[..camel_case::until(&*first)];
172     let mut post = &first[camel_case::from(&*first)..];
173     for var in &def.variants {
174         let name = var.ident.name.as_str();
175
176         let pre_match = partial_match(pre, &name);
177         pre = &pre[..pre_match];
178         let pre_camel = camel_case::until(pre);
179         pre = &pre[..pre_camel];
180         while let Some((next, last)) = name[pre.len()..].chars().zip(pre.chars().rev()).next() {
181             if next.is_numeric() {
182                 return;
183             }
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_lint_and_help(
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 #[must_use]
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.name.as_str();
249         let item_name_chars = item_name.chars().count();
250         let item_camel = to_camel_case(&item_name);
251         if !item.span.from_expansion() && is_present_in_source(cx, 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.ident.name {
256                         if let ItemKind::Mod(..) = item.kind {
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.kind {
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.ident.name, item_camel));
303     }
304 }