Skip to content

Commit b286b38

Browse files
committed
Auto merge of rust-lang#7300 - DevinR528:import-rename, r=camsteffen
Add import_rename lint, this adds a field on the Conf struct fixes rust-lang#7276 changelog: Add ``[`import_rename`]`` a lint that enforces import renaming defined in the config file.
2 parents d568387 + 9492de5 commit b286b38

File tree

8 files changed

+184
-1
lines changed

8 files changed

+184
-1
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -2657,6 +2657,7 @@ Released 2018-09-13
26572657
[`misrefactored_assign_op`]: https://rust-lang.github.io/rust-clippy/master/index.html#misrefactored_assign_op
26582658
[`missing_const_for_fn`]: https://rust-lang.github.io/rust-clippy/master/index.html#missing_const_for_fn
26592659
[`missing_docs_in_private_items`]: https://rust-lang.github.io/rust-clippy/master/index.html#missing_docs_in_private_items
2660+
[`missing_enforced_import_renames`]: https://rust-lang.github.io/rust-clippy/master/index.html#missing_enforced_import_renames
26602661
[`missing_errors_doc`]: https://rust-lang.github.io/rust-clippy/master/index.html#missing_errors_doc
26612662
[`missing_inline_in_public_items`]: https://rust-lang.github.io/rust-clippy/master/index.html#missing_inline_in_public_items
26622663
[`missing_panics_doc`]: https://rust-lang.github.io/rust-clippy/master/index.html#missing_panics_doc

clippy_lints/src/lib.rs

+5
Original file line numberDiff line numberDiff line change
@@ -267,6 +267,7 @@ mod misc;
267267
mod misc_early;
268268
mod missing_const_for_fn;
269269
mod missing_doc;
270+
mod missing_enforced_import_rename;
270271
mod missing_inline;
271272
mod modulo_arithmetic;
272273
mod multiple_crate_versions;
@@ -813,6 +814,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
813814
misc_early::ZERO_PREFIXED_LITERAL,
814815
missing_const_for_fn::MISSING_CONST_FOR_FN,
815816
missing_doc::MISSING_DOCS_IN_PRIVATE_ITEMS,
817+
missing_enforced_import_rename::MISSING_ENFORCED_IMPORT_RENAMES,
816818
missing_inline::MISSING_INLINE_IN_PUBLIC_ITEMS,
817819
modulo_arithmetic::MODULO_ARITHMETIC,
818820
multiple_crate_versions::MULTIPLE_CRATE_VERSIONS,
@@ -1017,6 +1019,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
10171019
LintId::of(misc::FLOAT_CMP_CONST),
10181020
LintId::of(misc_early::UNNEEDED_FIELD_PATTERN),
10191021
LintId::of(missing_doc::MISSING_DOCS_IN_PRIVATE_ITEMS),
1022+
LintId::of(missing_enforced_import_rename::MISSING_ENFORCED_IMPORT_RENAMES),
10201023
LintId::of(missing_inline::MISSING_INLINE_IN_PUBLIC_ITEMS),
10211024
LintId::of(modulo_arithmetic::MODULO_ARITHMETIC),
10221025
LintId::of(panic_in_result_fn::PANIC_IN_RESULT_FN),
@@ -2077,6 +2080,8 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
20772080
store.register_late_pass(|| box unused_async::UnusedAsync);
20782081
let disallowed_types = conf.disallowed_types.iter().cloned().collect::<FxHashSet<_>>();
20792082
store.register_late_pass(move || box disallowed_type::DisallowedType::new(&disallowed_types));
2083+
let import_renames = conf.enforced_import_renames.clone();
2084+
store.register_late_pass(move || box missing_enforced_import_rename::ImportRename::new(import_renames.clone()));
20802085

20812086
}
20822087

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
use clippy_utils::{diagnostics::span_lint_and_sugg, source::snippet_opt};
2+
3+
use rustc_data_structures::fx::FxHashMap;
4+
use rustc_errors::Applicability;
5+
use rustc_hir::{def::Res, def_id::DefId, Crate, Item, ItemKind, UseKind};
6+
use rustc_lint::{LateContext, LateLintPass, LintContext};
7+
use rustc_session::{declare_tool_lint, impl_lint_pass};
8+
use rustc_span::Symbol;
9+
10+
use crate::utils::conf::Rename;
11+
12+
declare_clippy_lint! {
13+
/// **What it does:** Checks for imports that do not rename the item as specified
14+
/// in the `enforce-import-renames` config option.
15+
///
16+
/// **Why is this bad?** Consistency is important, if a project has defined import
17+
/// renames they should be followed. More practically, some item names are too
18+
/// vague outside of their defining scope this can enforce a more meaningful naming.
19+
///
20+
/// **Known problems:** None
21+
///
22+
/// **Example:**
23+
///
24+
/// An example clippy.toml configuration:
25+
/// ```toml
26+
/// # clippy.toml
27+
/// enforced-import-renames = [ { path = "serde_json::Value", rename = "JsonValue" }]
28+
/// ```
29+
///
30+
/// ```rust,ignore
31+
/// use serde_json::Value;
32+
/// ```
33+
/// Use instead:
34+
/// ```rust,ignore
35+
/// use serde_json::Value as JsonValue;
36+
/// ```
37+
pub MISSING_ENFORCED_IMPORT_RENAMES,
38+
restriction,
39+
"enforce import renames"
40+
}
41+
42+
pub struct ImportRename {
43+
conf_renames: Vec<Rename>,
44+
renames: FxHashMap<DefId, Symbol>,
45+
}
46+
47+
impl ImportRename {
48+
pub fn new(conf_renames: Vec<Rename>) -> Self {
49+
Self {
50+
conf_renames,
51+
renames: FxHashMap::default(),
52+
}
53+
}
54+
}
55+
56+
impl_lint_pass!(ImportRename => [MISSING_ENFORCED_IMPORT_RENAMES]);
57+
58+
impl LateLintPass<'_> for ImportRename {
59+
fn check_crate(&mut self, cx: &LateContext<'_>, _: &Crate<'_>) {
60+
for Rename { path, rename } in &self.conf_renames {
61+
if let Res::Def(_, id) = clippy_utils::path_to_res(cx, &path.split("::").collect::<Vec<_>>()) {
62+
self.renames.insert(id, Symbol::intern(rename));
63+
}
64+
}
65+
}
66+
67+
fn check_item(&mut self, cx: &LateContext<'_>, item: &Item<'_>) {
68+
if_chain! {
69+
if let ItemKind::Use(path, UseKind::Single) = &item.kind;
70+
if let Res::Def(_, id) = path.res;
71+
if let Some(name) = self.renames.get(&id);
72+
// Remove semicolon since it is not present for nested imports
73+
let span_without_semi = cx.sess().source_map().span_until_char(item.span, ';');
74+
if let Some(snip) = snippet_opt(cx, span_without_semi);
75+
if let Some(import) = match snip.split_once(" as ") {
76+
None => Some(snip.as_str()),
77+
Some((import, rename)) => {
78+
if rename.trim() == &*name.as_str() {
79+
None
80+
} else {
81+
Some(import.trim())
82+
}
83+
},
84+
};
85+
then {
86+
span_lint_and_sugg(
87+
cx,
88+
MISSING_ENFORCED_IMPORT_RENAMES,
89+
span_without_semi,
90+
"this import should be renamed",
91+
"try",
92+
format!(
93+
"{} as {}",
94+
import,
95+
name,
96+
),
97+
Applicability::MachineApplicable,
98+
);
99+
}
100+
}
101+
}
102+
}

clippy_lints/src/utils/conf.rs

+9
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,13 @@ use std::error::Error;
88
use std::path::{Path, PathBuf};
99
use std::{env, fmt, fs, io};
1010

11+
/// Holds information used by `MISSING_ENFORCED_IMPORT_RENAMES` lint.
12+
#[derive(Clone, Debug, Deserialize)]
13+
pub struct Rename {
14+
pub path: String,
15+
pub rename: String,
16+
}
17+
1118
/// Conf with parse errors
1219
#[derive(Default)]
1320
pub struct TryConf {
@@ -203,6 +210,8 @@ define_Conf! {
203210
(cargo_ignore_publish: bool = false),
204211
/// Lint: NONSTANDARD_MACRO_BRACES. Enforce the named macros always use the braces specified. <br> A `MacroMatcher` can be added like so `{ name = "macro_name", brace = "(" }`. If the macro is could be used with a full path two `MacroMatcher`s have to be added one with the full path `crate_name::macro_name` and one with just the macro name.
205212
(standard_macro_braces: Vec<crate::nonstandard_macro_braces::MacroMatcher> = Vec::new()),
213+
/// Lint: MISSING_ENFORCED_IMPORT_RENAMES. The list of imports to always rename, a fully qualified path followed by the rename.
214+
(enforced_import_renames: Vec<crate::utils::conf::Rename> = Vec::new()),
206215
}
207216

208217
/// Search for the configuration file.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
enforced-import-renames = [
2+
{ path = "std::option::Option", rename = "Maybe" },
3+
{ path = "std::process::Child", rename = "Kid" },
4+
{ path = "std::process::exit", rename = "goodbye" },
5+
{ path = "std::collections::BTreeMap", rename = "Map" },
6+
{ path = "std::clone", rename = "foo" },
7+
{ path = "std::thread::sleep", rename = "thread_sleep" },
8+
{ path = "std::any::type_name", rename = "ident" },
9+
{ path = "std::sync::Mutex", rename = "StdMutie" }
10+
]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
#![warn(clippy::missing_enforced_import_renames)]
2+
3+
use std::alloc as colla;
4+
use std::option::Option as Maybe;
5+
use std::process::{exit as wrong_exit, Child as Kid};
6+
use std::thread::sleep;
7+
#[rustfmt::skip]
8+
use std::{
9+
any::{type_name, Any},
10+
clone,
11+
sync :: Mutex,
12+
};
13+
14+
fn main() {
15+
use std::collections::BTreeMap as OopsWrongRename;
16+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
error: this import should be renamed
2+
--> $DIR/conf_missing_enforced_import_rename.rs:5:20
3+
|
4+
LL | use std::process::{exit as wrong_exit, Child as Kid};
5+
| ^^^^^^^^^^^^^^^^^^ help: try: `exit as goodbye`
6+
|
7+
= note: `-D clippy::missing-enforced-import-renames` implied by `-D warnings`
8+
9+
error: this import should be renamed
10+
--> $DIR/conf_missing_enforced_import_rename.rs:6:1
11+
|
12+
LL | use std::thread::sleep;
13+
| ^^^^^^^^^^^^^^^^^^^^^^ help: try: `use std::thread::sleep as thread_sleep`
14+
15+
error: this import should be renamed
16+
--> $DIR/conf_missing_enforced_import_rename.rs:9:11
17+
|
18+
LL | any::{type_name, Any},
19+
| ^^^^^^^^^ help: try: `type_name as ident`
20+
21+
error: this import should be renamed
22+
--> $DIR/conf_missing_enforced_import_rename.rs:10:5
23+
|
24+
LL | clone,
25+
| ^^^^^ help: try: `clone as foo`
26+
27+
error: this import should be renamed
28+
--> $DIR/conf_missing_enforced_import_rename.rs:11:5
29+
|
30+
LL | sync :: Mutex,
31+
| ^^^^^^^^^^^^^ help: try: `sync :: Mutex as StdMutie`
32+
33+
error: this import should be renamed
34+
--> $DIR/conf_missing_enforced_import_rename.rs:15:5
35+
|
36+
LL | use std::collections::BTreeMap as OopsWrongRename;
37+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `use std::collections::BTreeMap as Map`
38+
39+
error: aborting due to 6 previous errors
40+
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
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`, `disallowed-types`, `unreadable-literal-lint-fractions`, `upper-case-acronyms-aggressive`, `cargo-ignore-publish`, `standard-macro-braces`, `third-party` at line 5 column 1
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`, `disallowed-types`, `unreadable-literal-lint-fractions`, `upper-case-acronyms-aggressive`, `cargo-ignore-publish`, `standard-macro-braces`, `enforced-import-renames`, `third-party` at line 5 column 1
22

33
error: aborting due to previous error
44

0 commit comments

Comments
 (0)