]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/enum_variants.rs
Rollup merge of #96142 - cjgillot:no-crate-def-index, r=petrochenkov
[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 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         if variant_split.len() == 1 {
176             return;
177         }
178
179         pre = pre
180             .iter()
181             .zip(variant_split.iter())
182             .take_while(|(a, b)| a == b)
183             .map(|e| *e.0)
184             .collect();
185         post = post
186             .iter()
187             .zip(variant_split.iter().rev())
188             .take_while(|(a, b)| a == b)
189             .map(|e| *e.0)
190             .collect();
191     }
192     let (what, value) = match (pre.is_empty(), post.is_empty()) {
193         (true, true) => return,
194         (false, _) => ("pre", pre.join("")),
195         (true, false) => {
196             post.reverse();
197             ("post", post.join(""))
198         },
199     };
200     span_lint_and_help(
201         cx,
202         ENUM_VARIANT_NAMES,
203         span,
204         &format!("all variants have the same {}fix: `{}`", what, value),
205         None,
206         &format!(
207             "remove the {}fixes and use full paths to \
208              the variants instead of glob imports",
209             what
210         ),
211     );
212 }
213
214 #[must_use]
215 fn to_camel_case(item_name: &str) -> String {
216     let mut s = String::new();
217     let mut up = true;
218     for c in item_name.chars() {
219         if c.is_uppercase() {
220             // we only turn snake case text into CamelCase
221             return item_name.to_string();
222         }
223         if c == '_' {
224             up = true;
225             continue;
226         }
227         if up {
228             up = false;
229             s.extend(c.to_uppercase());
230         } else {
231             s.push(c);
232         }
233     }
234     s
235 }
236
237 impl LateLintPass<'_> for EnumVariantNames {
238     fn check_item_post(&mut self, _cx: &LateContext<'_>, _item: &Item<'_>) {
239         let last = self.modules.pop();
240         assert!(last.is_some());
241     }
242
243     #[allow(clippy::similar_names)]
244     fn check_item(&mut self, cx: &LateContext<'_>, item: &Item<'_>) {
245         let item_name = item.ident.name.as_str();
246         let item_camel = to_camel_case(item_name);
247         if !item.span.from_expansion() && is_present_in_source(cx, item.span) {
248             if let Some(&(ref mod_name, ref mod_camel)) = self.modules.last() {
249                 // constants don't have surrounding modules
250                 if !mod_camel.is_empty() {
251                     if mod_name == &item.ident.name {
252                         if let ItemKind::Mod(..) = item.kind {
253                             span_lint(
254                                 cx,
255                                 MODULE_INCEPTION,
256                                 item.span,
257                                 "module has the same name as its containing module",
258                             );
259                         }
260                     }
261                     // The `module_name_repetitions` lint should only trigger if the item has the module in its
262                     // name. Having the same name is accepted.
263                     if item.vis.node.is_pub() && item_camel.len() > mod_camel.len() {
264                         let matching = count_match_start(mod_camel, &item_camel);
265                         let rmatching = count_match_end(mod_camel, &item_camel);
266                         let nchars = mod_camel.chars().count();
267
268                         let is_word_beginning = |c: char| c == '_' || c.is_uppercase() || c.is_numeric();
269
270                         if matching.char_count == nchars {
271                             match item_camel.chars().nth(nchars) {
272                                 Some(c) if is_word_beginning(c) => span_lint(
273                                     cx,
274                                     MODULE_NAME_REPETITIONS,
275                                     item.span,
276                                     "item name starts with its containing module's name",
277                                 ),
278                                 _ => (),
279                             }
280                         }
281                         if rmatching.char_count == nchars {
282                             span_lint(
283                                 cx,
284                                 MODULE_NAME_REPETITIONS,
285                                 item.span,
286                                 "item name ends with its containing module's name",
287                             );
288                         }
289                     }
290                 }
291             }
292         }
293         if let ItemKind::Enum(ref def, _) = item.kind {
294             if !(self.avoid_breaking_exported_api && cx.access_levels.is_exported(item.def_id)) {
295                 check_variant(cx, self.threshold, def, item_name, item.span);
296             }
297         }
298         self.modules.push((item.ident.name, item_camel));
299     }
300 }