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