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