]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/enum_variants.rs
Auto merge of #98675 - eddyb:cg-array-literal, r=nikic
[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     /// Use instead:
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     ///
64     /// Use instead:
65     /// ```rust
66     /// mod cake {
67     ///     struct BlackForest;
68     /// }
69     /// ```
70     #[clippy::version = "1.33.0"]
71     pub MODULE_NAME_REPETITIONS,
72     pedantic,
73     "type names prefixed/postfixed with their containing module's name"
74 }
75
76 declare_clippy_lint! {
77     /// ### What it does
78     /// Checks for modules that have the same name as their
79     /// parent module
80     ///
81     /// ### Why is this bad?
82     /// A typical beginner mistake is to have `mod foo;` and
83     /// again `mod foo { ..
84     /// }` in `foo.rs`.
85     /// The expectation is that items inside the inner `mod foo { .. }` are then
86     /// available
87     /// through `foo::x`, but they are only available through
88     /// `foo::foo::x`.
89     /// If this is done on purpose, it would be better to choose a more
90     /// representative module name.
91     ///
92     /// ### Example
93     /// ```ignore
94     /// // lib.rs
95     /// mod foo;
96     /// // foo.rs
97     /// mod foo {
98     ///     ...
99     /// }
100     /// ```
101     #[clippy::version = "pre 1.29.0"]
102     pub MODULE_INCEPTION,
103     style,
104     "modules that have the same name as their parent module"
105 }
106
107 pub struct EnumVariantNames {
108     modules: Vec<(Symbol, String)>,
109     threshold: u64,
110     avoid_breaking_exported_api: bool,
111 }
112
113 impl EnumVariantNames {
114     #[must_use]
115     pub fn new(threshold: u64, avoid_breaking_exported_api: bool) -> Self {
116         Self {
117             modules: Vec::new(),
118             threshold,
119             avoid_breaking_exported_api,
120         }
121     }
122 }
123
124 impl_lint_pass!(EnumVariantNames => [
125     ENUM_VARIANT_NAMES,
126     MODULE_NAME_REPETITIONS,
127     MODULE_INCEPTION
128 ]);
129
130 fn check_enum_start(cx: &LateContext<'_>, item_name: &str, variant: &Variant<'_>) {
131     let name = variant.ident.name.as_str();
132     let item_name_chars = item_name.chars().count();
133
134     if count_match_start(item_name, name).char_count == item_name_chars
135         && name.chars().nth(item_name_chars).map_or(false, |c| !c.is_lowercase())
136         && name.chars().nth(item_name_chars + 1).map_or(false, |c| !c.is_numeric())
137     {
138         span_lint(
139             cx,
140             ENUM_VARIANT_NAMES,
141             variant.span,
142             "variant name starts with the enum's name",
143         );
144     }
145 }
146
147 fn check_enum_end(cx: &LateContext<'_>, item_name: &str, variant: &Variant<'_>) {
148     let name = variant.ident.name.as_str();
149     let item_name_chars = item_name.chars().count();
150
151     if count_match_end(item_name, name).char_count == item_name_chars {
152         span_lint(
153             cx,
154             ENUM_VARIANT_NAMES,
155             variant.span,
156             "variant name ends with the enum's name",
157         );
158     }
159 }
160
161 fn check_variant(cx: &LateContext<'_>, threshold: u64, def: &EnumDef<'_>, item_name: &str, span: Span) {
162     if (def.variants.len() as u64) < threshold {
163         return;
164     }
165
166     let first = &def.variants[0].ident.name.as_str();
167     let mut pre = camel_case_split(first);
168     let mut post = pre.clone();
169     post.reverse();
170     for var in def.variants {
171         check_enum_start(cx, item_name, var);
172         check_enum_end(cx, item_name, var);
173         let name = var.ident.name.as_str();
174
175         let variant_split = camel_case_split(name);
176         if variant_split.len() == 1 {
177             return;
178         }
179
180         pre = pre
181             .iter()
182             .zip(variant_split.iter())
183             .take_while(|(a, b)| a == b)
184             .map(|e| *e.0)
185             .collect();
186         post = post
187             .iter()
188             .zip(variant_split.iter().rev())
189             .take_while(|(a, b)| a == b)
190             .map(|e| *e.0)
191             .collect();
192     }
193     let (what, value) = match (have_no_extra_prefix(&pre), post.is_empty()) {
194         (true, true) => return,
195         (false, _) => ("pre", pre.join("")),
196         (true, false) => {
197             post.reverse();
198             ("post", post.join(""))
199         },
200     };
201     span_lint_and_help(
202         cx,
203         ENUM_VARIANT_NAMES,
204         span,
205         &format!("all variants have the same {}fix: `{}`", what, value),
206         None,
207         &format!(
208             "remove the {}fixes and use full paths to \
209              the variants instead of glob imports",
210             what
211         ),
212     );
213 }
214
215 #[must_use]
216 fn have_no_extra_prefix(prefixes: &[&str]) -> bool {
217     prefixes.iter().all(|p| p == &"" || p == &"_")
218 }
219
220 #[must_use]
221 fn to_camel_case(item_name: &str) -> String {
222     let mut s = String::new();
223     let mut up = true;
224     for c in item_name.chars() {
225         if c.is_uppercase() {
226             // we only turn snake case text into CamelCase
227             return item_name.to_string();
228         }
229         if c == '_' {
230             up = true;
231             continue;
232         }
233         if up {
234             up = false;
235             s.extend(c.to_uppercase());
236         } else {
237             s.push(c);
238         }
239     }
240     s
241 }
242
243 impl LateLintPass<'_> for EnumVariantNames {
244     fn check_item_post(&mut self, _cx: &LateContext<'_>, _item: &Item<'_>) {
245         let last = self.modules.pop();
246         assert!(last.is_some());
247     }
248
249     #[expect(clippy::similar_names)]
250     fn check_item(&mut self, cx: &LateContext<'_>, item: &Item<'_>) {
251         let item_name = item.ident.name.as_str();
252         let item_camel = to_camel_case(item_name);
253         if !item.span.from_expansion() && is_present_in_source(cx, item.span) {
254             if let Some(&(ref mod_name, ref mod_camel)) = self.modules.last() {
255                 // constants don't have surrounding modules
256                 if !mod_camel.is_empty() {
257                     if mod_name == &item.ident.name {
258                         if let ItemKind::Mod(..) = item.kind {
259                             span_lint(
260                                 cx,
261                                 MODULE_INCEPTION,
262                                 item.span,
263                                 "module has the same name as its containing module",
264                             );
265                         }
266                     }
267                     // The `module_name_repetitions` lint should only trigger if the item has the module in its
268                     // name. Having the same name is accepted.
269                     if cx.tcx.visibility(item.def_id).is_public() && item_camel.len() > mod_camel.len() {
270                         let matching = count_match_start(mod_camel, &item_camel);
271                         let rmatching = count_match_end(mod_camel, &item_camel);
272                         let nchars = mod_camel.chars().count();
273
274                         let is_word_beginning = |c: char| c == '_' || c.is_uppercase() || c.is_numeric();
275
276                         if matching.char_count == nchars {
277                             match item_camel.chars().nth(nchars) {
278                                 Some(c) if is_word_beginning(c) => span_lint(
279                                     cx,
280                                     MODULE_NAME_REPETITIONS,
281                                     item.span,
282                                     "item name starts with its containing module's name",
283                                 ),
284                                 _ => (),
285                             }
286                         }
287                         if rmatching.char_count == nchars {
288                             span_lint(
289                                 cx,
290                                 MODULE_NAME_REPETITIONS,
291                                 item.span,
292                                 "item name ends with its containing module's name",
293                             );
294                         }
295                     }
296                 }
297             }
298         }
299         if let ItemKind::Enum(ref def, _) = item.kind {
300             if !(self.avoid_breaking_exported_api && cx.access_levels.is_exported(item.def_id)) {
301                 check_variant(cx, self.threshold, def, item_name, item.span);
302             }
303         }
304         self.modules.push((item.ident.name, item_camel));
305     }
306 }