1 //! lint on enum variants that are prefixed or suffixed by the same characters
3 use crate::utils::{camel_case, is_present_in_source};
4 use crate::utils::{span_lint, span_lint_and_help};
5 use rustc_ast::ast::{EnumDef, Item, ItemKind, VisibilityKind};
6 use rustc_lint::{EarlyContext, EarlyLintPass, Lint};
7 use rustc_session::{declare_tool_lint, impl_lint_pass};
8 use rustc_span::source_map::Span;
9 use rustc_span::symbol::Symbol;
11 declare_clippy_lint! {
12 /// **What it does:** Detects enumeration variants that are prefixed or suffixed
13 /// by the same characters.
15 /// **Why is this bad?** Enumeration variant names should specify their variant,
16 /// not repeat the enumeration name.
18 /// **Known problems:** None.
28 /// Could be written as:
36 pub ENUM_VARIANT_NAMES,
38 "enums where all variants share a prefix/postfix"
41 declare_clippy_lint! {
42 /// **What it does:** Detects public enumeration variants that are
43 /// prefixed or suffixed by the same characters.
45 /// **Why is this bad?** Public enumeration variant names should specify their variant,
46 /// not repeat the enumeration name.
48 /// **Known problems:** None.
58 /// Could be written as:
66 pub PUB_ENUM_VARIANT_NAMES,
68 "public enums where all variants share a prefix/postfix"
71 declare_clippy_lint! {
72 /// **What it does:** Detects type names that are prefixed or suffixed by the
73 /// containing module's name.
75 /// **Why is this bad?** It requires the user to type the module name twice.
77 /// **Known problems:** None.
82 /// struct BlackForestCake;
85 /// Could be written as:
88 /// struct BlackForest;
91 pub MODULE_NAME_REPETITIONS,
93 "type names prefixed/postfixed with their containing module's name"
96 declare_clippy_lint! {
97 /// **What it does:** Checks for modules that have the same name as their
100 /// **Why is this bad?** A typical beginner mistake is to have `mod foo;` and
101 /// again `mod foo { ..
103 /// The expectation is that items inside the inner `mod foo { .. }` are then
105 /// through `foo::x`, but they are only available through
107 /// If this is done on purpose, it would be better to choose a more
108 /// representative module name.
110 /// **Known problems:** None.
121 pub MODULE_INCEPTION,
123 "modules that have the same name as their parent module"
126 pub struct EnumVariantNames {
127 modules: Vec<(Symbol, String)>,
131 impl EnumVariantNames {
133 pub fn new(threshold: u64) -> Self {
141 impl_lint_pass!(EnumVariantNames => [
143 PUB_ENUM_VARIANT_NAMES,
144 MODULE_NAME_REPETITIONS,
148 /// Returns the number of chars that match from the start
150 fn partial_match(pre: &str, name: &str) -> usize {
151 let mut name_iter = name.chars();
152 let _ = name_iter.next_back(); // make sure the name is never fully matched
153 pre.chars().zip(name_iter).take_while(|&(l, r)| l == r).count()
156 /// Returns the number of chars that match from the end
158 fn partial_rmatch(post: &str, name: &str) -> usize {
159 let mut name_iter = name.chars();
160 let _ = name_iter.next(); // make sure the name is never fully matched
163 .zip(name_iter.rev())
164 .take_while(|&(l, r)| l == r)
169 cx: &EarlyContext<'_>,
173 item_name_chars: usize,
177 if (def.variants.len() as u64) < threshold {
180 for var in &def.variants {
181 let name = var.ident.name.as_str();
182 if partial_match(item_name, &name) == item_name_chars
183 && name.chars().nth(item_name_chars).map_or(false, |c| !c.is_lowercase())
184 && name.chars().nth(item_name_chars + 1).map_or(false, |c| !c.is_numeric())
186 span_lint(cx, lint, var.span, "Variant name starts with the enum's name");
188 if partial_rmatch(item_name, &name) == item_name_chars {
189 span_lint(cx, lint, var.span, "Variant name ends with the enum's name");
192 let first = &def.variants[0].ident.name.as_str();
193 let mut pre = &first[..camel_case::until(&*first)];
194 let mut post = &first[camel_case::from(&*first)..];
195 for var in &def.variants {
196 let name = var.ident.name.as_str();
198 let pre_match = partial_match(pre, &name);
199 pre = &pre[..pre_match];
200 let pre_camel = camel_case::until(pre);
201 pre = &pre[..pre_camel];
202 while let Some((next, last)) = name[pre.len()..].chars().zip(pre.chars().rev()).next() {
203 if next.is_numeric() {
206 if next.is_lowercase() {
207 let last = pre.len() - last.len_utf8();
208 let last_camel = camel_case::until(&pre[..last]);
209 pre = &pre[..last_camel];
215 let post_match = partial_rmatch(post, &name);
216 let post_end = post.len() - post_match;
217 post = &post[post_end..];
218 let post_camel = camel_case::from(post);
219 post = &post[post_camel..];
221 let (what, value) = match (pre.is_empty(), post.is_empty()) {
222 (true, true) => return,
223 (false, _) => ("pre", pre),
224 (true, false) => ("post", post),
230 &format!("All variants have the same {}fix: `{}`", what, value),
233 "remove the {}fixes and use full paths to \
234 the variants instead of glob imports",
241 fn to_camel_case(item_name: &str) -> String {
242 let mut s = String::new();
244 for c in item_name.chars() {
245 if c.is_uppercase() {
246 // we only turn snake case text into CamelCase
247 return item_name.to_string();
255 s.extend(c.to_uppercase());
263 impl EarlyLintPass for EnumVariantNames {
264 fn check_item_post(&mut self, _cx: &EarlyContext<'_>, _item: &Item) {
265 let last = self.modules.pop();
266 assert!(last.is_some());
269 #[allow(clippy::similar_names)]
270 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &Item) {
271 let item_name = item.ident.name.as_str();
272 let item_name_chars = item_name.chars().count();
273 let item_camel = to_camel_case(&item_name);
274 if !item.span.from_expansion() && is_present_in_source(cx, item.span) {
275 if let Some(&(ref mod_name, ref mod_camel)) = self.modules.last() {
276 // constants don't have surrounding modules
277 if !mod_camel.is_empty() {
278 if mod_name == &item.ident.name {
279 if let ItemKind::Mod(..) = item.kind {
284 "module has the same name as its containing module",
288 if item.vis.node.is_pub() {
289 let matching = partial_match(mod_camel, &item_camel);
290 let rmatching = partial_rmatch(mod_camel, &item_camel);
291 let nchars = mod_camel.chars().count();
293 let is_word_beginning = |c: char| c == '_' || c.is_uppercase() || c.is_numeric();
295 if matching == nchars {
296 match item_camel.chars().nth(nchars) {
297 Some(c) if is_word_beginning(c) => span_lint(
299 MODULE_NAME_REPETITIONS,
301 "item name starts with its containing module's name",
306 if rmatching == nchars {
309 MODULE_NAME_REPETITIONS,
311 "item name ends with its containing module's name",
318 if let ItemKind::Enum(ref def, _) = item.kind {
319 let lint = match item.vis.node {
320 VisibilityKind::Public => PUB_ENUM_VARIANT_NAMES,
321 _ => ENUM_VARIANT_NAMES,
323 check_variant(cx, self.threshold, def, &item_name, item_name_chars, item.span, lint);
325 self.modules.push((item.ident.name, item_camel));