1 //! lint on enum variants that are prefixed or suffixed by the same characters
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;
12 declare_clippy_lint! {
14 /// Detects enumeration variants that are prefixed or suffixed
15 /// by the same characters.
17 /// ### Why is this bad?
18 /// Enumeration variant names should specify their variant,
19 /// not repeat the enumeration name.
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蟹`
43 #[clippy::version = "pre 1.29.0"]
44 pub ENUM_VARIANT_NAMES,
46 "enums where all variants share a prefix/postfix"
49 declare_clippy_lint! {
51 /// Detects type names that are prefixed or suffixed by the
52 /// containing module's name.
54 /// ### Why is this bad?
55 /// It requires the user to type the module name twice.
60 /// struct BlackForestCake;
67 /// struct BlackForest;
70 #[clippy::version = "1.33.0"]
71 pub MODULE_NAME_REPETITIONS,
73 "type names prefixed/postfixed with their containing module's name"
76 declare_clippy_lint! {
78 /// Checks for modules that have the same name as their
81 /// ### Why is this bad?
82 /// A typical beginner mistake is to have `mod foo;` and
83 /// again `mod foo { ..
85 /// The expectation is that items inside the inner `mod foo { .. }` are then
87 /// through `foo::x`, but they are only available through
89 /// If this is done on purpose, it would be better to choose a more
90 /// representative module name.
101 #[clippy::version = "pre 1.29.0"]
102 pub MODULE_INCEPTION,
104 "modules that have the same name as their parent module"
107 pub struct EnumVariantNames {
108 modules: Vec<(Symbol, String)>,
110 avoid_breaking_exported_api: bool,
113 impl EnumVariantNames {
115 pub fn new(threshold: u64, avoid_breaking_exported_api: bool) -> Self {
119 avoid_breaking_exported_api,
124 impl_lint_pass!(EnumVariantNames => [
126 MODULE_NAME_REPETITIONS,
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();
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())
142 "variant name starts with the enum's name",
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();
151 if count_match_end(item_name, name).char_count == item_name_chars {
156 "variant name ends with the enum's name",
161 fn check_variant(cx: &LateContext<'_>, threshold: u64, def: &EnumDef<'_>, item_name: &str, span: Span) {
162 if (def.variants.len() as u64) < threshold {
166 let first = &def.variants[0].ident.name.as_str();
167 let mut pre = camel_case_split(first);
168 let mut post = pre.clone();
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();
175 let variant_split = camel_case_split(name);
176 if variant_split.len() == 1 {
182 .zip(variant_split.iter())
183 .take_while(|(a, b)| a == b)
188 .zip(variant_split.iter().rev())
189 .take_while(|(a, b)| a == b)
193 let (what, value) = match (have_no_extra_prefix(&pre), post.is_empty()) {
194 (true, true) => return,
195 (false, _) => ("pre", pre.join("")),
198 ("post", post.join(""))
205 &format!("all variants have the same {what}fix: `{value}`"),
208 "remove the {what}fixes and use full paths to \
209 the variants instead of glob imports"
215 fn have_no_extra_prefix(prefixes: &[&str]) -> bool {
216 prefixes.iter().all(|p| p == &"" || p == &"_")
220 fn to_camel_case(item_name: &str) -> String {
221 let mut s = String::new();
223 for c in item_name.chars() {
224 if c.is_uppercase() {
225 // we only turn snake case text into CamelCase
226 return item_name.to_string();
234 s.extend(c.to_uppercase());
242 impl LateLintPass<'_> for EnumVariantNames {
243 fn check_item_post(&mut self, _cx: &LateContext<'_>, _item: &Item<'_>) {
244 let last = self.modules.pop();
245 assert!(last.is_some());
248 #[expect(clippy::similar_names)]
249 fn check_item(&mut self, cx: &LateContext<'_>, item: &Item<'_>) {
250 let item_name = item.ident.name.as_str();
251 let item_camel = to_camel_case(item_name);
252 if !item.span.from_expansion() && is_present_in_source(cx, item.span) {
253 if let Some((mod_name, mod_camel)) = self.modules.last() {
254 // constants don't have surrounding modules
255 if !mod_camel.is_empty() {
256 if mod_name == &item.ident.name {
257 if let ItemKind::Mod(..) = item.kind {
262 "module has the same name as its containing module",
266 // The `module_name_repetitions` lint should only trigger if the item has the module in its
267 // name. Having the same name is accepted.
268 if cx.tcx.visibility(item.owner_id).is_public() && item_camel.len() > mod_camel.len() {
269 let matching = count_match_start(mod_camel, &item_camel);
270 let rmatching = count_match_end(mod_camel, &item_camel);
271 let nchars = mod_camel.chars().count();
273 let is_word_beginning = |c: char| c == '_' || c.is_uppercase() || c.is_numeric();
275 if matching.char_count == nchars {
276 match item_camel.chars().nth(nchars) {
277 Some(c) if is_word_beginning(c) => span_lint(
279 MODULE_NAME_REPETITIONS,
281 "item name starts with its containing module's name",
286 if rmatching.char_count == nchars {
289 MODULE_NAME_REPETITIONS,
291 "item name ends with its containing module's name",
298 if let ItemKind::Enum(ref def, _) = item.kind {
299 if !(self.avoid_breaking_exported_api && cx.effective_visibilities.is_exported(item.owner_id.def_id)) {
300 check_variant(cx, self.threshold, def, item_name, item.span);
303 self.modules.push((item.ident.name, item_camel));