rust/clippy_lints/src/enum_variants.rs

295 lines
9.6 KiB
Rust
Raw Normal View History

//! lint on enum variants that are prefixed or suffixed by the same characters
use clippy_utils::diagnostics::{span_lint, span_lint_and_help};
use clippy_utils::source::is_present_in_source;
use clippy_utils::str_utils::{self, count_match_end, count_match_start};
2021-12-14 22:08:13 -06:00
use rustc_hir::{EnumDef, Item, ItemKind, Variant};
use rustc_lint::{LateContext, LateLintPass};
2020-01-11 05:37:08 -06:00
use rustc_session::{declare_tool_lint, impl_lint_pass};
use rustc_span::source_map::Span;
use rustc_span::symbol::Symbol;
2018-03-28 08:24:26 -05:00
declare_clippy_lint! {
/// ### 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.
///
/// ### Example
/// ```rust
/// enum Cake {
/// BlackForestCake,
/// HummingbirdCake,
/// BattenbergCake,
/// }
/// ```
/// Could be written as:
/// ```rust
/// enum Cake {
/// BlackForest,
/// Hummingbird,
/// Battenberg,
/// }
/// ```
Added `clippy::version` attribute to all normal lints So, some context for this, well, more a story. I'm not used to scripting, I've never really scripted anything, even if it's a valuable skill. I just never really needed it. Now, `@flip1995` correctly suggested using a script for this in `rust-clippy#7813`... And I decided to write a script using nushell because why not? This was a mistake... I spend way more time on this than I would like to admit. It has definitely been more than 4 hours. It shouldn't take that long, but me being new to scripting and nushell just wasn't a good mixture... Anyway, here is the script that creates another script which adds the versions. Fun... Just execute this on the `gh-pages` branch and the resulting `replacer.sh` in `clippy_lints` and it should all work. ```nu mv v0.0.212 rust-1.00.0; mv beta rust-1.57.0; mv master rust-1.58.0; let paths = (open ./rust-1.58.0/lints.json | select id id_span | flatten | select id path); let versions = ( ls | where name =~ "rust-" | select name | format {name}/lints.json | each { open $it | select id | insert version $it | str substring "5,11" version} | group-by id | rotate counter-clockwise id version | update version {get version | first 1} | flatten | select id version); $paths | each { |row| let version = ($versions | where id == ($row.id) | format {version}) let idu = ($row.id | str upcase) $"sed -i '0,/($idu),/{s/pub ($idu),/#[clippy::version = "($version)"]\n pub ($idu),/}' ($row.path)" } | str collect ";" | str find-replace --all '1.00.0' 'pre 1.29.0' | save "replacer.sh"; ``` And this still has some problems, but at this point I just want to be done -.-
2021-10-21 14:06:26 -05:00
#[clippy::version = "pre 1.29.0"]
pub ENUM_VARIANT_NAMES,
2018-03-28 08:24:26 -05:00
style,
"enums where all variants share a prefix/postfix"
}
2018-03-28 08:24:26 -05:00
declare_clippy_lint! {
/// ### What it does
/// Detects type names that are prefixed or suffixed by the
/// containing module's name.
///
/// ### Why is this bad?
/// It requires the user to type the module name twice.
///
/// ### Example
/// ```rust
/// mod cake {
/// struct BlackForestCake;
/// }
/// ```
/// Could be written as:
/// ```rust
/// mod cake {
/// struct BlackForest;
/// }
/// ```
Added `clippy::version` attribute to all normal lints So, some context for this, well, more a story. I'm not used to scripting, I've never really scripted anything, even if it's a valuable skill. I just never really needed it. Now, `@flip1995` correctly suggested using a script for this in `rust-clippy#7813`... And I decided to write a script using nushell because why not? This was a mistake... I spend way more time on this than I would like to admit. It has definitely been more than 4 hours. It shouldn't take that long, but me being new to scripting and nushell just wasn't a good mixture... Anyway, here is the script that creates another script which adds the versions. Fun... Just execute this on the `gh-pages` branch and the resulting `replacer.sh` in `clippy_lints` and it should all work. ```nu mv v0.0.212 rust-1.00.0; mv beta rust-1.57.0; mv master rust-1.58.0; let paths = (open ./rust-1.58.0/lints.json | select id id_span | flatten | select id path); let versions = ( ls | where name =~ "rust-" | select name | format {name}/lints.json | each { open $it | select id | insert version $it | str substring "5,11" version} | group-by id | rotate counter-clockwise id version | update version {get version | first 1} | flatten | select id version); $paths | each { |row| let version = ($versions | where id == ($row.id) | format {version}) let idu = ($row.id | str upcase) $"sed -i '0,/($idu),/{s/pub ($idu),/#[clippy::version = "($version)"]\n pub ($idu),/}' ($row.path)" } | str collect ";" | str find-replace --all '1.00.0' 'pre 1.29.0' | save "replacer.sh"; ``` And this still has some problems, but at this point I just want to be done -.-
2021-10-21 14:06:26 -05:00
#[clippy::version = "1.33.0"]
2018-12-17 07:29:19 -06:00
pub MODULE_NAME_REPETITIONS,
2018-03-28 08:24:26 -05:00
pedantic,
"type names prefixed/postfixed with their containing module's name"
2016-06-16 11:37:56 -05:00
}
2018-03-28 08:24:26 -05:00
declare_clippy_lint! {
/// ### What it does
/// Checks for modules that have the same name as their
/// parent module
///
/// ### 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
/// 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.
///
/// ### Example
2019-03-05 16:23:50 -06:00
/// ```ignore
/// // lib.rs
/// mod foo;
/// // foo.rs
/// mod foo {
/// ...
/// }
/// ```
Added `clippy::version` attribute to all normal lints So, some context for this, well, more a story. I'm not used to scripting, I've never really scripted anything, even if it's a valuable skill. I just never really needed it. Now, `@flip1995` correctly suggested using a script for this in `rust-clippy#7813`... And I decided to write a script using nushell because why not? This was a mistake... I spend way more time on this than I would like to admit. It has definitely been more than 4 hours. It shouldn't take that long, but me being new to scripting and nushell just wasn't a good mixture... Anyway, here is the script that creates another script which adds the versions. Fun... Just execute this on the `gh-pages` branch and the resulting `replacer.sh` in `clippy_lints` and it should all work. ```nu mv v0.0.212 rust-1.00.0; mv beta rust-1.57.0; mv master rust-1.58.0; let paths = (open ./rust-1.58.0/lints.json | select id id_span | flatten | select id path); let versions = ( ls | where name =~ "rust-" | select name | format {name}/lints.json | each { open $it | select id | insert version $it | str substring "5,11" version} | group-by id | rotate counter-clockwise id version | update version {get version | first 1} | flatten | select id version); $paths | each { |row| let version = ($versions | where id == ($row.id) | format {version}) let idu = ($row.id | str upcase) $"sed -i '0,/($idu),/{s/pub ($idu),/#[clippy::version = "($version)"]\n pub ($idu),/}' ($row.path)" } | str collect ";" | str find-replace --all '1.00.0' 'pre 1.29.0' | save "replacer.sh"; ``` And this still has some problems, but at this point I just want to be done -.-
2021-10-21 14:06:26 -05:00
#[clippy::version = "pre 1.29.0"]
pub MODULE_INCEPTION,
2018-03-28 08:24:26 -05:00
style,
"modules that have the same name as their parent module"
}
pub struct EnumVariantNames {
modules: Vec<(Symbol, String)>,
threshold: u64,
avoid_breaking_exported_api: bool,
}
impl EnumVariantNames {
#[must_use]
pub fn new(threshold: u64, avoid_breaking_exported_api: bool) -> Self {
2017-08-21 06:32:12 -05:00
Self {
2016-12-20 11:21:30 -06:00
modules: Vec::new(),
threshold,
avoid_breaking_exported_api,
2016-12-20 11:21:30 -06:00
}
}
}
2019-04-08 15:43:55 -05:00
impl_lint_pass!(EnumVariantNames => [
2021-12-14 22:08:13 -06:00
ENUM_VARIANT_NAMES,
MODULE_NAME_REPETITIONS,
MODULE_INCEPTION
2019-04-08 15:43:55 -05:00
]);
2021-12-14 22:08:13 -06:00
fn check_enum_start(cx: &LateContext<'_>, item_name: &str, variant: &Variant<'_>) {
let name = variant.ident.name.as_str();
let item_name_chars = item_name.chars().count();
if count_match_start(item_name, &name).char_count == item_name_chars
&& name.chars().nth(item_name_chars).map_or(false, |c| !c.is_lowercase())
&& name.chars().nth(item_name_chars + 1).map_or(false, |c| !c.is_numeric())
{
span_lint(
cx,
ENUM_VARIANT_NAMES,
variant.span,
"variant name starts with the enum's name",
);
}
}
fn check_enum_end(cx: &LateContext<'_>, item_name: &str, variant: &Variant<'_>) {
let name = variant.ident.name.as_str();
let item_name_chars = item_name.chars().count();
if count_match_end(item_name, &name).char_count == item_name_chars {
span_lint(
cx,
ENUM_VARIANT_NAMES,
variant.span,
"variant name ends with the enum's name",
);
}
}
fn check_variant(cx: &LateContext<'_>, threshold: u64, def: &EnumDef<'_>, item_name: &str, span: Span) {
if (def.variants.len() as u64) < threshold {
return;
}
2021-12-14 22:08:13 -06:00
let first = &def.variants[0].ident.name.as_str();
let mut pre = &first[..str_utils::camel_case_until(&*first).byte_index];
let mut post = &first[str_utils::camel_case_start(&*first).byte_index..];
for var in def.variants {
2021-12-14 22:08:13 -06:00
check_enum_start(cx, item_name, var);
check_enum_end(cx, item_name, var);
let name = var.ident.name.as_str();
let pre_match = count_match_start(pre, &name).byte_count;
pre = &pre[..pre_match];
let pre_camel = str_utils::camel_case_until(pre).byte_index;
pre = &pre[..pre_camel];
while let Some((next, last)) = name[pre.len()..].chars().zip(pre.chars().rev()).next() {
if next.is_numeric() {
return;
}
if next.is_lowercase() {
let last = pre.len() - last.len_utf8();
let last_camel = str_utils::camel_case_until(&pre[..last]);
pre = &pre[..last_camel.byte_index];
} else {
break;
}
}
let post_match = count_match_end(post, &name);
let post_end = post.len() - post_match.byte_count;
post = &post[post_end..];
let post_camel = str_utils::camel_case_start(post);
post = &post[post_camel.byte_index..];
}
let (what, value) = match (pre.is_empty(), post.is_empty()) {
(true, true) => return,
(false, _) => ("pre", pre),
(true, false) => ("post", post),
};
span_lint_and_help(
2017-08-09 02:30:56 -05:00
cx,
ENUM_VARIANT_NAMES,
2017-08-09 02:30:56 -05:00
span,
&format!("all variants have the same {}fix: `{}`", what, value),
None,
2017-08-09 02:30:56 -05:00
&format!(
"remove the {}fixes and use full paths to \
2017-09-05 04:33:04 -05:00
the variants instead of glob imports",
2017-08-09 02:30:56 -05:00
what
),
);
}
#[must_use]
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 LateLintPass<'_> for EnumVariantNames {
fn check_item_post(&mut self, _cx: &LateContext<'_>, _item: &Item<'_>) {
let last = self.modules.pop();
assert!(last.is_some());
}
#[allow(clippy::similar_names)]
fn check_item(&mut self, cx: &LateContext<'_>, item: &Item<'_>) {
let item_name = item.ident.name.as_str();
let item_camel = to_camel_case(&item_name);
2019-08-19 11:30:32 -05:00
if !item.span.from_expansion() && is_present_in_source(cx, item.span) {
if let Some(&(ref mod_name, ref mod_camel)) = self.modules.last() {
2016-06-10 09:30:39 -05:00
// constants don't have surrounding modules
if !mod_camel.is_empty() {
if mod_name == &item.ident.name {
2019-09-27 10:16:06 -05:00
if let ItemKind::Mod(..) = item.kind {
2017-08-09 02:30:56 -05:00
span_lint(
cx,
MODULE_INCEPTION,
item.span,
"module has the same name as its containing module",
);
}
}
// The `module_name_repetitions` lint should only trigger if the item has the module in its
// name. Having the same name is accepted.
if item.vis.node.is_pub() && item_camel.len() > mod_camel.len() {
let matching = count_match_start(mod_camel, &item_camel);
let rmatching = count_match_end(mod_camel, &item_camel);
let nchars = mod_camel.chars().count();
2018-11-27 14:14:15 -06:00
let is_word_beginning = |c: char| c == '_' || c.is_uppercase() || c.is_numeric();
if matching.char_count == nchars {
match item_camel.chars().nth(nchars) {
2018-11-27 14:14:15 -06:00
Some(c) if is_word_beginning(c) => span_lint(
cx,
2018-12-17 07:29:19 -06:00
MODULE_NAME_REPETITIONS,
2018-11-27 14:14:15 -06:00
item.span,
"item name starts with its containing module's name",
),
_ => (),
}
}
if rmatching.char_count == nchars {
2018-11-27 14:14:15 -06:00
span_lint(
cx,
2018-12-17 07:29:19 -06:00
MODULE_NAME_REPETITIONS,
2018-11-27 14:14:15 -06:00
item.span,
"item name ends with its containing module's name",
);
}
}
}
}
}
2019-09-27 10:16:06 -05:00
if let ItemKind::Enum(ref def, _) = item.kind {
2021-07-28 17:07:32 -05:00
if !(self.avoid_breaking_exported_api && cx.access_levels.is_exported(item.def_id)) {
2021-12-14 22:08:13 -06:00
check_variant(cx, self.threshold, def, &item_name, item.span);
}
}
self.modules.push((item.ident.name, item_camel));
}
}