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