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);
175 if variant_split.len() == 1 {
181 .zip(variant_split.iter())
182 .take_while(|(a, b)| a == b)
187 .zip(variant_split.iter().rev())
188 .take_while(|(a, b)| a == b)
192 let (what, value) = match (pre.is_empty(), post.is_empty()) {
193 (true, true) => return,
194 (false, _) => ("pre", pre.join("")),
197 ("post", post.join(""))
204 &format!("all variants have the same {}fix: `{}`", what, value),
207 "remove the {}fixes and use full paths to \
208 the variants instead of glob imports",
215 fn to_camel_case(item_name: &str) -> String {
216 let mut s = String::new();
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();
229 s.extend(c.to_uppercase());
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());
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 {
257 "module has the same name as its containing module",
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();
268 let is_word_beginning = |c: char| c == '_' || c.is_uppercase() || c.is_numeric();
270 if matching.char_count == nchars {
271 match item_camel.chars().nth(nchars) {
272 Some(c) if is_word_beginning(c) => span_lint(
274 MODULE_NAME_REPETITIONS,
276 "item name starts with its containing module's name",
281 if rmatching.char_count == nchars {
284 MODULE_NAME_REPETITIONS,
286 "item name ends with its containing module's name",
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);
298 self.modules.push((item.ident.name, item_camel));