rust/clippy_lints/src/single_component_path_imports.rs

180 lines
6.0 KiB
Rust
Raw Normal View History

use clippy_utils::diagnostics::{span_lint_and_help, span_lint_and_sugg};
use rustc_ast::{ptr::P, Crate, Item, ItemKind, MacroDef, ModKind, UseTreeKind, VisibilityKind};
2020-01-29 10:21:29 -06:00
use rustc_errors::Applicability;
use rustc_lint::{EarlyContext, EarlyLintPass};
2021-04-04 07:21:02 -05:00
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::{edition::Edition, symbol::kw, Span, Symbol};
2020-01-29 10:21:29 -06:00
declare_clippy_lint! {
/// ### What it does
/// Checking for imports with single component use path.
2020-01-29 10:21:29 -06:00
///
/// ### Why is this bad?
/// Import with single component use path such as `use cratename;`
2020-01-29 10:21:29 -06:00
/// is not necessary, and thus should be removed.
///
/// ### Example
/// ```rust,ignore
2020-01-29 10:21:29 -06:00
/// use regex;
///
/// fn main() {
/// regex::Regex::new(r"^\d{4}-\d{2}-\d{2}$").unwrap();
/// }
/// ```
/// Better as
/// ```rust,ignore
2020-01-29 10:21:29 -06:00
/// fn main() {
/// regex::Regex::new(r"^\d{4}-\d{2}-\d{2}$").unwrap();
/// }
/// ```
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.43.0"]
2020-01-29 10:21:29 -06:00
pub SINGLE_COMPONENT_PATH_IMPORTS,
style,
"imports with single component path are redundant"
}
2021-04-04 07:21:02 -05:00
declare_lint_pass!(SingleComponentPathImports => [SINGLE_COMPONENT_PATH_IMPORTS]);
2020-01-29 10:21:29 -06:00
impl EarlyLintPass for SingleComponentPathImports {
fn check_crate(&mut self, cx: &EarlyContext<'_>, krate: &Crate) {
if cx.sess.opts.edition < Edition::Edition2018 {
return;
}
2021-04-04 07:21:02 -05:00
check_mod(cx, &krate.items);
2020-01-29 10:21:29 -06:00
}
}
2021-04-04 07:21:02 -05:00
fn check_mod(cx: &EarlyContext<'_>, items: &[P<Item>]) {
// keep track of imports reused with `self` keyword,
// such as `self::crypto_hash` in the example below
// ```rust,ignore
// use self::crypto_hash::{Algorithm, Hasher};
// ```
let mut imports_reused_with_self = Vec::new();
// keep track of single use statements
// such as `crypto_hash` in the example below
// ```rust,ignore
// use crypto_hash;
// ```
let mut single_use_usages = Vec::new();
// keep track of macros defined in the module as we don't want it to trigger on this (#7106)
// ```rust,ignore
// macro_rules! foo { () => {} };
// pub(crate) use foo;
// ```
let mut macros = Vec::new();
2021-04-04 07:21:02 -05:00
for item in items {
track_uses(
cx,
2021-05-19 15:27:06 -05:00
item,
&mut imports_reused_with_self,
&mut single_use_usages,
&mut macros,
);
2021-04-04 07:21:02 -05:00
}
for single_use in &single_use_usages {
if !imports_reused_with_self.contains(&single_use.0) {
let can_suggest = single_use.2;
if can_suggest {
span_lint_and_sugg(
cx,
SINGLE_COMPONENT_PATH_IMPORTS,
single_use.1,
"this import is redundant",
"remove it entirely",
String::new(),
Applicability::MachineApplicable,
);
} else {
span_lint_and_help(
cx,
SINGLE_COMPONENT_PATH_IMPORTS,
single_use.1,
"this import is redundant",
None,
"remove this import",
);
}
2021-03-28 02:35:44 -05:00
}
2021-04-04 07:21:02 -05:00
}
}
fn track_uses(
cx: &EarlyContext<'_>,
item: &Item,
imports_reused_with_self: &mut Vec<Symbol>,
single_use_usages: &mut Vec<(Symbol, Span, bool)>,
macros: &mut Vec<Symbol>,
2021-04-04 07:21:02 -05:00
) {
if item.span.from_expansion() || item.vis.kind.is_pub() {
2021-04-04 07:21:02 -05:00
return;
}
match &item.kind {
ItemKind::Mod(_, ModKind::Loaded(ref items, ..)) => {
2021-05-19 15:27:06 -05:00
check_mod(cx, items);
2021-04-04 07:21:02 -05:00
},
ItemKind::MacroDef(MacroDef { macro_rules: true, .. }) => {
macros.push(item.ident.name);
},
2021-04-04 07:21:02 -05:00
ItemKind::Use(use_tree) => {
let segments = &use_tree.prefix.segments;
2021-03-28 02:35:44 -05:00
let should_report =
|name: &Symbol| !macros.contains(name) || matches!(item.vis.kind, VisibilityKind::Inherited);
2021-04-04 07:21:02 -05:00
// keep track of `use some_module;` usages
if segments.len() == 1 {
if let UseTreeKind::Simple(None, _, _) = use_tree.kind {
let name = segments[0].ident.name;
if should_report(&name) {
single_use_usages.push((name, item.span, true));
}
2021-03-28 02:35:44 -05:00
}
2021-04-04 07:21:02 -05:00
return;
}
if segments.is_empty() {
// keep track of `use {some_module, some_other_module};` usages
2021-04-04 07:21:02 -05:00
if let UseTreeKind::Nested(trees) = &use_tree.kind {
for tree in trees {
let segments = &tree.0.prefix.segments;
if segments.len() == 1 {
if let UseTreeKind::Simple(None, _, _) = tree.0.kind {
let name = segments[0].ident.name;
if should_report(&name) {
single_use_usages.push((name, tree.0.span, false));
}
}
}
}
}
} else {
// keep track of `use self::some_module` usages
if segments[0].ident.name == kw::SelfLower {
// simple case such as `use self::module::SomeStruct`
if segments.len() > 1 {
imports_reused_with_self.push(segments[1].ident.name);
return;
}
// nested case such as `use self::{module1::Struct1, module2::Struct2}`
if let UseTreeKind::Nested(trees) = &use_tree.kind {
for tree in trees {
let segments = &tree.0.prefix.segments;
if !segments.is_empty() {
imports_reused_with_self.push(segments[0].ident.name);
}
}
}
}
2021-04-04 07:21:02 -05:00
}
},
_ => {},
}
}