1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
11 //! lint on enum variants that are prefixed or suffixed by the same characters
13 use crate::rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass, Lint};
14 use crate::rustc::{declare_tool_lint, lint_array};
15 use crate::syntax::ast::*;
16 use crate::syntax::source_map::Span;
17 use crate::syntax::symbol::LocalInternedString;
18 use crate::utils::{span_help_and_lint, span_lint};
19 use crate::utils::{camel_case_from, camel_case_until, in_macro};
21 /// **What it does:** Detects enumeration variants that are prefixed or suffixed
22 /// by the same characters.
24 /// **Why is this bad?** Enumeration variant names should specify their variant,
25 /// not repeat the enumeration name.
27 /// **Known problems:** None.
37 declare_clippy_lint! {
38 pub ENUM_VARIANT_NAMES,
40 "enums where all variants share a prefix/postfix"
43 /// **What it does:** Detects enumeration variants that are prefixed or suffixed
44 /// by the same characters.
46 /// **Why is this bad?** Enumeration variant names should specify their variant,
47 /// not repeat the enumeration name.
49 /// **Known problems:** None.
59 declare_clippy_lint! {
60 pub PUB_ENUM_VARIANT_NAMES,
62 "enums where all variants share a prefix/postfix"
65 /// **What it does:** Detects type names that are prefixed or suffixed by the
66 /// containing module's name.
68 /// **Why is this bad?** It requires the user to type the module name twice.
70 /// **Known problems:** None.
75 /// struct BlackForestCake;
78 declare_clippy_lint! {
81 "type names prefixed/postfixed with their containing module's name"
84 /// **What it does:** Checks for modules that have the same name as their
87 /// **Why is this bad?** A typical beginner mistake is to have `mod foo;` and
88 /// again `mod foo { ..
90 /// The expectation is that items inside the inner `mod foo { .. }` are then
92 /// through `foo::x`, but they are only available through
94 /// If this is done on purpose, it would be better to choose a more
95 /// representative module name.
97 /// **Known problems:** None.
108 declare_clippy_lint! {
109 pub MODULE_INCEPTION,
111 "modules that have the same name as their parent module"
114 pub struct EnumVariantNames {
115 modules: Vec<(LocalInternedString, String)>,
119 impl EnumVariantNames {
120 pub fn new(threshold: u64) -> Self {
128 impl LintPass for EnumVariantNames {
129 fn get_lints(&self) -> LintArray {
130 lint_array!(ENUM_VARIANT_NAMES, PUB_ENUM_VARIANT_NAMES, STUTTER, MODULE_INCEPTION)
134 fn var2str(var: &Variant) -> LocalInternedString {
135 var.node.ident.as_str()
138 /// Returns the number of chars that match from the start
139 fn partial_match(pre: &str, name: &str) -> usize {
140 let mut name_iter = name.chars();
141 let _ = name_iter.next_back(); // make sure the name is never fully matched
144 .take_while(|&(l, r)| l == r)
148 /// Returns the number of chars that match from the end
149 fn partial_rmatch(post: &str, name: &str) -> usize {
150 let mut name_iter = name.chars();
151 let _ = name_iter.next(); // make sure the name is never fully matched
154 .zip(name_iter.rev())
155 .take_while(|&(l, r)| l == r)
160 #[allow(clippy::while_let_on_iterator)]
162 cx: &EarlyContext<'_>,
166 item_name_chars: usize,
170 if (def.variants.len() as u64) < threshold {
173 for var in &def.variants {
174 let name = var2str(var);
175 if partial_match(item_name, &name) == item_name_chars
177 .nth(item_name_chars)
178 .map_or(false, |c| !c.is_lowercase())
180 span_lint(cx, lint, var.span, "Variant name starts with the enum's name");
182 if partial_rmatch(item_name, &name) == item_name_chars {
183 span_lint(cx, lint, var.span, "Variant name ends with the enum's name");
186 let first = var2str(&def.variants[0]);
187 let mut pre = &first[..camel_case_until(&*first)];
188 let mut post = &first[camel_case_from(&*first)..];
189 for var in &def.variants {
190 let name = var2str(var);
192 let pre_match = partial_match(pre, &name);
193 pre = &pre[..pre_match];
194 let pre_camel = camel_case_until(pre);
195 pre = &pre[..pre_camel];
196 while let Some((next, last)) = name[pre.len()..].chars().zip(pre.chars().rev()).next() {
197 if next.is_lowercase() {
198 let last = pre.len() - last.len_utf8();
199 let last_camel = camel_case_until(&pre[..last]);
200 pre = &pre[..last_camel];
206 let post_match = partial_rmatch(post, &name);
207 let post_end = post.len() - post_match;
208 post = &post[post_end..];
209 let post_camel = camel_case_from(post);
210 post = &post[post_camel..];
212 let (what, value) = match (pre.is_empty(), post.is_empty()) {
213 (true, true) => return,
214 (false, _) => ("pre", pre),
215 (true, false) => ("post", post),
221 &format!("All variants have the same {}fix: `{}`", what, value),
223 "remove the {}fixes and use full paths to \
224 the variants instead of glob imports",
230 fn to_camel_case(item_name: &str) -> String {
231 let mut s = String::new();
233 for c in item_name.chars() {
234 if c.is_uppercase() {
235 // we only turn snake case text into CamelCase
236 return item_name.to_string();
244 s.extend(c.to_uppercase());
252 impl EarlyLintPass for EnumVariantNames {
253 fn check_item_post(&mut self, _cx: &EarlyContext<'_>, _item: &Item) {
254 let last = self.modules.pop();
255 assert!(last.is_some());
258 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &Item) {
259 let item_name = item.ident.as_str();
260 let item_name_chars = item_name.chars().count();
261 let item_camel = to_camel_case(&item_name);
262 if !in_macro(item.span) {
263 if let Some(&(ref mod_name, ref mod_camel)) = self.modules.last() {
264 // constants don't have surrounding modules
265 if !mod_camel.is_empty() {
266 if *mod_name == item_name {
267 if let ItemKind::Mod(..) = item.node {
272 "module has the same name as its containing module",
276 if item.vis.node.is_pub() {
277 let matching = partial_match(mod_camel, &item_camel);
278 let rmatching = partial_rmatch(mod_camel, &item_camel);
279 let nchars = mod_camel.chars().count();
281 let is_word_beginning = |c: char| {
282 c == '_' || c.is_uppercase() || c.is_numeric()
285 if matching == nchars {
286 match item_camel.chars().nth(nchars) {
287 Some(c) if is_word_beginning(c) =>
288 span_lint(cx, STUTTER, item.span, "item name starts with its containing module's name"),
292 if rmatching == nchars {
293 span_lint(cx, STUTTER, item.span, "item name ends with its containing module's name");
299 if let ItemKind::Enum(ref def, _) = item.node {
300 let lint = match item.vis.node {
301 VisibilityKind::Public => PUB_ENUM_VARIANT_NAMES,
302 _ => ENUM_VARIANT_NAMES,
304 check_variant(cx, self.threshold, def, &item_name, item_name_chars, item.span, lint);
306 self.modules.push((item_name, item_camel));