rust-clippy/clippy_lints/src/enum_variants.rs

308 lines
9.4 KiB
Rust
Raw Normal View History

2018-10-06 16:18:06 +00:00
// Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! lint on enum variants that are prefixed or suffixed by the same characters
use crate::rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass, Lint};
use crate::rustc::{declare_tool_lint, lint_array};
use crate::syntax::ast::*;
use crate::syntax::source_map::Span;
use crate::syntax::symbol::LocalInternedString;
2018-05-30 08:15:50 +00:00
use crate::utils::{span_help_and_lint, span_lint};
2018-10-11 22:36:40 +00:00
use crate::utils::{camel_case, in_macro};
/// **What it does:** Detects enumeration variants that are prefixed or suffixed
/// by the same characters.
///
/// **Why is this bad?** Enumeration variant names should specify their variant,
/// not repeat the enumeration name.
///
/// **Known problems:** None.
///
2016-07-15 22:25:44 +00:00
/// **Example:**
/// ```rust
/// enum Cake {
/// BlackForestCake,
/// HummingbirdCake,
/// BattenbergCake,
2016-07-15 22:25:44 +00:00
/// }
/// ```
2018-03-28 13:24:26 +00:00
declare_clippy_lint! {
pub ENUM_VARIANT_NAMES,
2018-03-28 13:24:26 +00:00
style,
"enums where all variants share a prefix/postfix"
}
/// **What it does:** Detects enumeration variants that are prefixed or suffixed
/// by the same characters.
///
/// **Why is this bad?** Enumeration variant names should specify their variant,
/// not repeat the enumeration name.
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust
/// enum Cake {
/// BlackForestCake,
/// HummingbirdCake,
/// BattenbergCake,
/// }
/// ```
2018-03-28 13:24:26 +00:00
declare_clippy_lint! {
pub PUB_ENUM_VARIANT_NAMES,
2018-03-28 13:24:26 +00:00
pedantic,
"enums where all variants share a prefix/postfix"
}
/// **What it does:** Detects type names that are prefixed or suffixed by the
/// containing module's name.
2016-06-16 16:37:56 +00:00
///
/// **Why is this bad?** It requires the user to type the module name twice.
2016-06-16 16:37:56 +00:00
///
/// **Known problems:** None.
2016-06-16 16:37:56 +00:00
///
2016-07-15 22:25:44 +00:00
/// **Example:**
/// ```rust
/// mod cake {
/// struct BlackForestCake;
/// }
/// ```
2018-03-28 13:24:26 +00:00
declare_clippy_lint! {
pub STUTTER,
2018-03-28 13:24:26 +00:00
pedantic,
"type names prefixed/postfixed with their containing module's name"
2016-06-16 16:37:56 +00:00
}
2017-08-09 07:30:56 +00:00
/// **What it does:** Checks for modules that have the same name as their
/// parent module
///
2017-08-09 07:30:56 +00:00
/// **Why is this bad?** A typical beginner mistake is to have `mod foo;` and
/// again `mod foo { ..
/// }` in `foo.rs`.
/// The expectation is that items inside the inner `mod foo { .. }` are then
/// available
2017-08-09 07:30:56 +00:00
/// through `foo::x`, but they are only available through
/// `foo::foo::x`.
/// If this is done on purpose, it would be better to choose a more
/// representative module name.
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust
/// // lib.rs
/// mod foo;
/// // foo.rs
/// mod foo {
/// ...
/// }
/// ```
2018-03-28 13:24:26 +00:00
declare_clippy_lint! {
pub MODULE_INCEPTION,
2018-03-28 13:24:26 +00:00
style,
"modules that have the same name as their parent module"
}
pub struct EnumVariantNames {
modules: Vec<(LocalInternedString, String)>,
threshold: u64,
}
impl EnumVariantNames {
2017-08-21 11:32:12 +00:00
pub fn new(threshold: u64) -> Self {
Self {
2016-12-20 17:21:30 +00:00
modules: Vec::new(),
threshold,
2016-12-20 17:21:30 +00:00
}
}
}
impl LintPass for EnumVariantNames {
fn get_lints(&self) -> LintArray {
lint_array!(ENUM_VARIANT_NAMES, PUB_ENUM_VARIANT_NAMES, STUTTER, MODULE_INCEPTION)
}
}
fn var2str(var: &Variant) -> LocalInternedString {
2018-06-28 13:46:58 +00:00
var.node.ident.as_str()
}
/// Returns the number of chars that match from the start
fn partial_match(pre: &str, name: &str) -> usize {
let mut name_iter = name.chars();
let _ = name_iter.next_back(); // make sure the name is never fully matched
2017-08-09 07:30:56 +00:00
pre.chars()
.zip(name_iter)
.take_while(|&(l, r)| l == r)
.count()
}
/// Returns the number of chars that match from the end
fn partial_rmatch(post: &str, name: &str) -> usize {
let mut name_iter = name.chars();
let _ = name_iter.next(); // make sure the name is never fully matched
2017-08-09 07:30:56 +00:00
post.chars()
.rev()
.zip(name_iter.rev())
.take_while(|&(l, r)| l == r)
.count()
}
fn check_variant(
2018-07-23 11:01:12 +00:00
cx: &EarlyContext<'_>,
threshold: u64,
def: &EnumDef,
item_name: &str,
item_name_chars: usize,
span: Span,
2017-08-09 07:30:56 +00:00
lint: &'static Lint,
) {
if (def.variants.len() as u64) < threshold {
return;
}
for var in &def.variants {
let name = var2str(var);
2017-11-04 19:55:56 +00:00
if partial_match(item_name, &name) == item_name_chars
&& name.chars()
.nth(item_name_chars)
.map_or(false, |c| !c.is_lowercase())
{
span_lint(cx, lint, var.span, "Variant name starts with the enum's name");
}
if partial_rmatch(item_name, &name) == item_name_chars {
span_lint(cx, lint, var.span, "Variant name ends with the enum's name");
}
}
let first = var2str(&def.variants[0]);
2018-10-11 22:36:40 +00:00
let mut pre = &first[..camel_case::until(&*first)];
let mut post = &first[camel_case::from(&*first)..];
for var in &def.variants {
let name = var2str(var);
let pre_match = partial_match(pre, &name);
pre = &pre[..pre_match];
2018-10-11 22:36:40 +00:00
let pre_camel = camel_case::until(pre);
pre = &pre[..pre_camel];
while let Some((next, last)) = name[pre.len()..].chars().zip(pre.chars().rev()).next() {
if next.is_lowercase() {
let last = pre.len() - last.len_utf8();
2018-10-11 22:36:40 +00:00
let last_camel = camel_case::until(&pre[..last]);
pre = &pre[..last_camel];
} else {
break;
}
}
let post_match = partial_rmatch(post, &name);
let post_end = post.len() - post_match;
post = &post[post_end..];
2018-10-11 22:36:40 +00:00
let post_camel = camel_case::from(post);
post = &post[post_camel..];
}
let (what, value) = match (pre.is_empty(), post.is_empty()) {
(true, true) => return,
(false, _) => ("pre", pre),
(true, false) => ("post", post),
};
2017-08-09 07:30:56 +00:00
span_help_and_lint(
cx,
lint,
span,
&format!("All variants have the same {}fix: `{}`", what, value),
&format!(
"remove the {}fixes and use full paths to \
2017-09-05 09:33:04 +00:00
the variants instead of glob imports",
2017-08-09 07:30:56 +00:00
what
),
);
}
fn to_camel_case(item_name: &str) -> String {
let mut s = String::new();
let mut up = true;
for c in item_name.chars() {
if c.is_uppercase() {
// we only turn snake case text into CamelCase
return item_name.to_string();
}
if c == '_' {
up = true;
continue;
}
if up {
up = false;
s.extend(c.to_uppercase());
} else {
s.push(c);
}
}
s
}
impl EarlyLintPass for EnumVariantNames {
2018-07-23 11:01:12 +00:00
fn check_item_post(&mut self, _cx: &EarlyContext<'_>, _item: &Item) {
let last = self.modules.pop();
assert!(last.is_some());
}
#[allow(clippy::similar_names)]
2018-07-23 11:01:12 +00:00
fn check_item(&mut self, cx: &EarlyContext<'_>, item: &Item) {
2018-06-28 13:46:58 +00:00
let item_name = item.ident.as_str();
let item_name_chars = item_name.chars().count();
let item_camel = to_camel_case(&item_name);
if !in_macro(item.span) {
if let Some(&(ref mod_name, ref mod_camel)) = self.modules.last() {
2016-06-10 14:30:39 +00:00
// constants don't have surrounding modules
if !mod_camel.is_empty() {
2017-03-09 09:58:31 +00:00
if *mod_name == item_name {
if let ItemKind::Mod(..) = item.node {
2017-08-09 07:30:56 +00:00
span_lint(
cx,
MODULE_INCEPTION,
item.span,
"module has the same name as its containing module",
);
}
}
if item.vis.node.is_pub() {
let matching = partial_match(mod_camel, &item_camel);
let rmatching = partial_rmatch(mod_camel, &item_camel);
let nchars = mod_camel.chars().count();
let is_word_beginning = |c: char| {
c == '_' || c.is_uppercase() || c.is_numeric()
};
if matching == nchars {
match item_camel.chars().nth(nchars) {
Some(c) if is_word_beginning(c) =>
span_lint(cx, STUTTER, item.span, "item name starts with its containing module's name"),
_ => ()
}
}
if rmatching == nchars {
span_lint(cx, STUTTER, item.span, "item name ends with its containing module's name");
}
}
}
}
}
if let ItemKind::Enum(ref def, _) = item.node {
2018-02-23 16:59:42 +00:00
let lint = match item.vis.node {
VisibilityKind::Public => PUB_ENUM_VARIANT_NAMES,
_ => ENUM_VARIANT_NAMES,
};
check_variant(cx, self.threshold, def, &item_name, item_name_chars, item.span, lint);
}
self.modules.push((item_name, item_camel));
}
}