-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add import_rename lint, this adds a field on the Conf struct
- Loading branch information
Showing
8 changed files
with
156 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,97 @@ | ||
use clippy_utils::{diagnostics::span_lint_and_sugg, source::snippet_opt}; | ||
|
||
use rustc_data_structures::fx::FxHashSet; | ||
use rustc_errors::Applicability; | ||
use rustc_hir::{def::Res, Item, ItemKind, UseKind}; | ||
use rustc_lint::{LateContext, LateLintPass}; | ||
use rustc_session::{declare_tool_lint, impl_lint_pass}; | ||
use rustc_span::Symbol; | ||
|
||
declare_clippy_lint! { | ||
/// **What it does:** Checks that any import matching `import_renames` is renamed. | ||
/// | ||
/// **Why is this bad?** This is purely about consistency, it is not bad. | ||
/// | ||
/// **Known problems:** Any import must use the original fully qualified path. | ||
/// | ||
/// For example, if you want to rename `serde_json::Value`, your clippy.toml | ||
/// configuration would look like | ||
/// `import-renames = [ { path: "serde_json::value::Value", rename = "JsonValue" }]` and not | ||
/// `import-renames = [ { path: "serde_json::Value", rename = "JsonValue" }]` as you might expect. | ||
/// | ||
/// | ||
/// **Example:** | ||
/// | ||
/// ```rust,ignore | ||
/// use serde_json::Value; | ||
/// ``` | ||
/// Use instead: | ||
/// ```rust,ignore | ||
/// use serde_json::Value as JsonValue; | ||
/// ``` | ||
pub IMPORT_RENAME, | ||
restriction, | ||
"enforce import renames" | ||
} | ||
|
||
pub struct ImportRename { | ||
imports: FxHashSet<(Vec<Symbol>, Symbol)>, | ||
} | ||
|
||
impl ImportRename { | ||
pub fn new(imports: &FxHashSet<(String, String)>) -> Self { | ||
Self { | ||
imports: imports | ||
.iter() | ||
.map(|(orig, rename)| { | ||
( | ||
orig.split("::").map(|seg| Symbol::intern(seg)).collect::<Vec<_>>(), | ||
Symbol::intern(rename), | ||
) | ||
}) | ||
.collect(), | ||
} | ||
} | ||
} | ||
|
||
impl_lint_pass!(ImportRename => [IMPORT_RENAME]); | ||
|
||
impl LateLintPass<'_> for ImportRename { | ||
fn check_item(&mut self, cx: &LateContext<'_>, item: &Item<'_>) { | ||
if_chain! { | ||
if let ItemKind::Use(path, UseKind::Single) = &item.kind; | ||
if let Res::Def(_, id) = path.res; | ||
if let Some(snip) = snippet_opt(cx, item.span); | ||
let use_path = cx.get_def_path(id); | ||
if let Some((_, name)) = self.imports.iter().find(|(path, _)| path == &use_path); | ||
|
||
// TODO: alternatively we could use the def_path_str() instead of the full path which would somewhat fix the | ||
// problem of having to use fully qualified paths... although then nested imports kinda breaks down | ||
// | ||
// let orig_import = cx.tcx.def_path_str(id) | ||
// .map(|seg| Symbol::intern(seg)).collect::<Vec<_>>(); | ||
// if let Some((_, name)) = self.imports.iter().find(|(path, _)| { | ||
// path == &orig_import | ||
// }); | ||
|
||
// Remove semicolon since it is not present for nested imports | ||
if !snip.replace(";", "").ends_with(&format!("{}", name)); | ||
then { | ||
span_lint_and_sugg( | ||
cx, | ||
IMPORT_RENAME, | ||
item.span, | ||
"this import should be renamed", | ||
"try", | ||
format!( | ||
"{} as {}{}", | ||
snip.split_whitespace().take(2).collect::<Vec<_>>().join(" "), | ||
name, | ||
if snip.ends_with(';') { ";" } else { "" }, | ||
), | ||
Applicability::MachineApplicable, | ||
); | ||
} | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
import-renames = [ | ||
{ path = "syn::path::Path", rename = "SynPath" }, | ||
{ path = "serde::de::Deserializer", rename = "SomethingElse" }, | ||
{ path = "serde::ser::Serializer", rename = "DarkTower" }, | ||
{ path = "alloc::collections::btree::map::BTreeMap", rename = "Map" }, | ||
{ path = "regex::bytes", rename = "foo" }, | ||
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
#![allow(unused_imports, dead_code)] | ||
#![warn(clippy::import_rename)] | ||
|
||
extern crate regex; | ||
extern crate serde; | ||
extern crate syn; | ||
|
||
use regex::bytes as xegersetyb; | ||
use serde::{de::Deserializer as WrongRename, ser::Serializer as DarkTower}; | ||
use syn::Path as SynPath; | ||
|
||
fn main() { | ||
use std::collections::BTreeMap as OopsWrongRename; | ||
} |
22 changes: 22 additions & 0 deletions
22
tests/ui-toml/toml_import_rename/conf_import_rename.stderr
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
error: this import should be renamed | ||
--> $DIR/conf_import_rename.rs:8:1 | ||
| | ||
LL | use regex::bytes as xegersetyb; | ||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `use regex::bytes as foo;` | ||
| | ||
= note: `-D clippy::import-rename` implied by `-D warnings` | ||
|
||
error: this import should be renamed | ||
--> $DIR/conf_import_rename.rs:9:13 | ||
| | ||
LL | use serde::{de::Deserializer as WrongRename, ser::Serializer as DarkTower}; | ||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `de::Deserializer as as SomethingElse` | ||
|
||
error: this import should be renamed | ||
--> $DIR/conf_import_rename.rs:13:5 | ||
| | ||
LL | use std::collections::BTreeMap as OopsWrongRename; | ||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `use std::collections::BTreeMap as Map;` | ||
|
||
error: aborting due to 3 previous errors | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,4 @@ | ||
error: error reading Clippy's configuration file `$DIR/clippy.toml`: unknown field `foobar`, expected one of `avoid-breaking-exported-api`, `msrv`, `blacklisted-names`, `cognitive-complexity-threshold`, `cyclomatic-complexity-threshold`, `doc-valid-idents`, `too-many-arguments-threshold`, `type-complexity-threshold`, `single-char-binding-names-threshold`, `too-large-for-stack`, `enum-variant-name-threshold`, `enum-variant-size-threshold`, `verbose-bit-mask-threshold`, `literal-representation-threshold`, `trivial-copy-size-limit`, `pass-by-value-size-limit`, `too-many-lines-threshold`, `array-size-threshold`, `vec-box-size-threshold`, `max-trait-bounds`, `max-struct-bools`, `max-fn-params-bools`, `warn-on-all-wildcard-imports`, `disallowed-methods`, `unreadable-literal-lint-fractions`, `upper-case-acronyms-aggressive`, `cargo-ignore-publish`, `third-party` at line 5 column 1 | ||
error: error reading Clippy's configuration file `$DIR/clippy.toml`: unknown field `foobar`, expected one of `avoid-breaking-exported-api`, `msrv`, `blacklisted-names`, `cognitive-complexity-threshold`, `cyclomatic-complexity-threshold`, `doc-valid-idents`, `too-many-arguments-threshold`, `type-complexity-threshold`, `single-char-binding-names-threshold`, `too-large-for-stack`, `enum-variant-name-threshold`, `enum-variant-size-threshold`, `verbose-bit-mask-threshold`, `literal-representation-threshold`, `trivial-copy-size-limit`, `pass-by-value-size-limit`, `too-many-lines-threshold`, `array-size-threshold`, `vec-box-size-threshold`, `max-trait-bounds`, `max-struct-bools`, `max-fn-params-bools`, `warn-on-all-wildcard-imports`, `disallowed-methods`, `unreadable-literal-lint-fractions`, `upper-case-acronyms-aggressive`, `cargo-ignore-publish`, `import-renames`, `third-party` at line 5 column 1 | ||
|
||
error: aborting due to previous error | ||
|