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.
10 //! lint on enum variants that are prefixed or suffixed by the same characters
12 use crate::utils::{camel_case, in_macro};
13 use crate::utils::{span_help_and_lint, span_lint};
14 use rustc::lint::{EarlyContext, EarlyLintPass, Lint, LintArray, LintPass};
15 use rustc::{declare_tool_lint, lint_array};
17 use syntax::source_map::Span;
18 use syntax::symbol::{InternedString, LocalInternedString};
20 /// **What it does:** Detects enumeration variants that are prefixed or suffixed
21 /// by the same characters.
23 /// **Why is this bad?** Enumeration variant names should specify their variant,
24 /// not repeat the enumeration name.
26 /// **Known problems:** None.
36 declare_clippy_lint! {
37 pub ENUM_VARIANT_NAMES,
39 "enums where all variants share a prefix/postfix"
42 /// **What it does:** Detects enumeration variants that are prefixed or suffixed
43 /// by the same characters.
45 /// **Why is this bad?** Enumeration variant names should specify their variant,
46 /// not repeat the enumeration name.
48 /// **Known problems:** None.
58 declare_clippy_lint! {
59 pub PUB_ENUM_VARIANT_NAMES,
61 "enums where all variants share a prefix/postfix"
64 /// **What it does:** Detects type names that are prefixed or suffixed by the
65 /// containing module's name.
67 /// **Why is this bad?** It requires the user to type the module name twice.
69 /// **Known problems:** None.
74 /// struct BlackForestCake;
77 declare_clippy_lint! {
78 pub MODULE_NAME_REPETITIONS,
80 "type names prefixed/postfixed with their containing module's name"
83 /// **What it does:** Checks for modules that have the same name as their
86 /// **Why is this bad?** A typical beginner mistake is to have `mod foo;` and
87 /// again `mod foo { ..
89 /// The expectation is that items inside the inner `mod foo { .. }` are then
91 /// through `foo::x`, but they are only available through
93 /// If this is done on purpose, it would be better to choose a more
94 /// representative module name.
96 /// **Known problems:** None.
107 declare_clippy_lint! {
108 pub MODULE_INCEPTION,
110 "modules that have the same name as their parent module"
113 pub struct EnumVariantNames {
114 modules: Vec<(InternedString, String)>,
118 impl EnumVariantNames {
119 pub fn new(threshold: u64) -> Self {
127 impl LintPass for EnumVariantNames {
128 fn get_lints(&self) -> LintArray {
131 PUB_ENUM_VARIANT_NAMES,
132 MODULE_NAME_REPETITIONS,
138 fn var2str(var: &Variant) -> LocalInternedString {
139 var.node.ident.as_str()
142 /// Returns the number of chars that match from the start
143 fn partial_match(pre: &str, name: &str) -> usize {
144 let mut name_iter = name.chars();
145 let _ = name_iter.next_back(); // make sure the name is never fully matched
146 pre.chars().zip(name_iter).take_while(|&(l, r)| l == r).count()
149 /// Returns the number of chars that match from the end
150 fn partial_rmatch(post: &str, name: &str) -> usize {
151 let mut name_iter = name.chars();
152 let _ = name_iter.next(); // make sure the name is never fully matched
155 .zip(name_iter.rev())
156 .take_while(|&(l, r)| l == r)
161 cx: &EarlyContext<'_>,
165 item_name_chars: usize,
169 if (def.variants.len() as u64) < threshold {
172 for var in &def.variants {
173 let name = var2str(var);
174 if partial_match(item_name, &name) == item_name_chars
175 && name.chars().nth(item_name_chars).map_or(false, |c| !c.is_lowercase())
177 span_lint(cx, lint, var.span, "Variant name starts with the enum's name");
179 if partial_rmatch(item_name, &name) == item_name_chars {
180 span_lint(cx, lint, var.span, "Variant name ends with the enum's name");
183 let first = var2str(&def.variants[0]);
184 let mut pre = &first[..camel_case::until(&*first)];
185 let mut post = &first[camel_case::from(&*first)..];
186 for var in &def.variants {
187 let name = var2str(var);
189 let pre_match = partial_match(pre, &name);
190 pre = &pre[..pre_match];
191 let pre_camel = camel_case::until(pre);
192 pre = &pre[..pre_camel];
193 while let Some((next, last)) = name[pre.len()..].chars().zip(pre.chars().rev()).next() {
194 if next.is_lowercase() {
195 let last = pre.len() - last.len_utf8();
196 let last_camel = camel_case::until(&pre[..last]);
197 pre = &pre[..last_camel];
203 let post_match = partial_rmatch(post, &name);
204 let post_end = post.len() - post_match;
205 post = &post[post_end..];
206 let post_camel = camel_case::from(post);
207 post = &post[post_camel..];
209 let (what, value) = match (pre.is_empty(), post.is_empty()) {
210 (true, true) => return,
211 (false, _) => ("pre", pre),
212 (true, false) => ("post", post),
218 &format!("All variants have the same {}fix: `{}`", what, value),
220 "remove the {}fixes and use full paths to \
221 the variants instead of glob imports",
227 fn to_camel_case(item_name: &str) -> String {
228 let mut s = String::new();
230 for c in item_name.chars() {
231 if c.is_uppercase() {
232 // we only turn snake case text into CamelCase
233 return item_name.to_string();
241 s.extend(c.to_uppercase());
249 impl EarlyLintPass for EnumVariantNames {
250 fn check_item_post(&mut self, _cx: &EarlyContext<'_>, _item: &Item) {
251 let last = self.modules.pop();
252 assert!(last.is_some());
255 #[allow(clippy::similar_names)]
256 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &Item) {
257 let item_name = item.ident.as_str();
258 let item_name_chars = item_name.chars().count();
259 let item_camel = to_camel_case(&item_name);
260 if !in_macro(item.span) {
261 if let Some(&(ref mod_name, ref mod_camel)) = self.modules.last() {
262 // constants don't have surrounding modules
263 if !mod_camel.is_empty() {
264 if *mod_name == item_name {
265 if let ItemKind::Mod(..) = item.node {
270 "module has the same name as its containing module",
274 if item.vis.node.is_pub() {
275 let matching = partial_match(mod_camel, &item_camel);
276 let rmatching = partial_rmatch(mod_camel, &item_camel);
277 let nchars = mod_camel.chars().count();
279 let is_word_beginning = |c: char| c == '_' || c.is_uppercase() || c.is_numeric();
281 if matching == nchars {
282 match item_camel.chars().nth(nchars) {
283 Some(c) if is_word_beginning(c) => span_lint(
285 MODULE_NAME_REPETITIONS,
287 "item name starts with its containing module's name",
292 if rmatching == nchars {
295 MODULE_NAME_REPETITIONS,
297 "item name ends with its containing module's name",
304 if let ItemKind::Enum(ref def, _) = item.node {
305 let lint = match item.vis.node {
306 VisibilityKind::Public => PUB_ENUM_VARIANT_NAMES,
307 _ => ENUM_VARIANT_NAMES,
309 check_variant(cx, self.threshold, def, &item_name, item_name_chars, item.span, lint);
311 self.modules.push((item_name.as_interned_str(), item_camel));