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蟹`
35 /// Could be written as:
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;
63 /// Could be written as:
66 /// struct BlackForest;
69 #[clippy::version = "1.33.0"]
70 pub MODULE_NAME_REPETITIONS,
72 "type names prefixed/postfixed with their containing module's name"
75 declare_clippy_lint! {
77 /// Checks for modules that have the same name as their
80 /// ### Why is this bad?
81 /// A typical beginner mistake is to have `mod foo;` and
82 /// again `mod foo { ..
84 /// The expectation is that items inside the inner `mod foo { .. }` are then
86 /// through `foo::x`, but they are only available through
88 /// If this is done on purpose, it would be better to choose a more
89 /// representative module name.
100 #[clippy::version = "pre 1.29.0"]
101 pub MODULE_INCEPTION,
103 "modules that have the same name as their parent module"
106 pub struct EnumVariantNames {
107 modules: Vec<(Symbol, String)>,
109 avoid_breaking_exported_api: bool,
112 impl EnumVariantNames {
114 pub fn new(threshold: u64, avoid_breaking_exported_api: bool) -> Self {
118 avoid_breaking_exported_api,
123 impl_lint_pass!(EnumVariantNames => [
125 MODULE_NAME_REPETITIONS,
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();
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())
141 "variant name starts with the enum's name",
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();
150 if count_match_end(item_name, name).char_count == item_name_chars {
155 "variant name ends with the enum's name",
160 fn check_variant(cx: &LateContext<'_>, threshold: u64, def: &EnumDef<'_>, item_name: &str, span: Span) {
161 if (def.variants.len() as u64) < threshold {
165 let first = &def.variants[0].ident.name.as_str();
166 let mut pre = camel_case_split(first);
167 let mut post = pre.clone();
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();
174 let variant_split = camel_case_split(name);
178 .zip(variant_split.iter())
179 .take_while(|(a, b)| a == b)
184 .zip(variant_split.iter().rev())
185 .take_while(|(a, b)| a == b)
189 let (what, value) = match (pre.is_empty(), post.is_empty()) {
190 (true, true) => return,
191 (false, _) => ("pre", pre.join("")),
194 ("post", post.join(""))
201 &format!("all variants have the same {}fix: `{}`", what, value),
204 "remove the {}fixes and use full paths to \
205 the variants instead of glob imports",
212 fn to_camel_case(item_name: &str) -> String {
213 let mut s = String::new();
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();
226 s.extend(c.to_uppercase());
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());
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 {
254 "module has the same name as its containing module",
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();
265 let is_word_beginning = |c: char| c == '_' || c.is_uppercase() || c.is_numeric();
267 if matching.char_count == nchars {
268 match item_camel.chars().nth(nchars) {
269 Some(c) if is_word_beginning(c) => span_lint(
271 MODULE_NAME_REPETITIONS,
273 "item name starts with its containing module's name",
278 if rmatching.char_count == nchars {
281 MODULE_NAME_REPETITIONS,
283 "item name ends with its containing module's name",
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);
295 self.modules.push((item.ident.name, item_camel));