1 use clippy_utils::{diagnostics::span_lint_and_sugg, source::snippet_opt};
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;
10 use crate::utils::conf::Rename;
12 declare_clippy_lint! {
14 /// Checks for imports that do not rename the item as specified
15 /// in the `enforce-import-renames` config option.
17 /// ### Why is this bad?
18 /// Consistency is important, if a project has defined import
19 /// renames they should be followed. More practically, some item names are too
20 /// vague outside of their defining scope this can enforce a more meaningful naming.
23 /// An example clippy.toml configuration:
26 /// enforced-import-renames = [ { path = "serde_json::Value", rename = "JsonValue" }]
30 /// use serde_json::Value;
34 /// use serde_json::Value as JsonValue;
36 pub MISSING_ENFORCED_IMPORT_RENAMES,
38 "enforce import renames"
41 pub struct ImportRename {
42 conf_renames: Vec<Rename>,
43 renames: FxHashMap<DefId, Symbol>,
47 pub fn new(conf_renames: Vec<Rename>) -> Self {
50 renames: FxHashMap::default(),
55 impl_lint_pass!(ImportRename => [MISSING_ENFORCED_IMPORT_RENAMES]);
57 impl LateLintPass<'_> for ImportRename {
58 fn check_crate(&mut self, cx: &LateContext<'_>, _: &Crate<'_>) {
59 for Rename { path, rename } in &self.conf_renames {
60 if let Res::Def(_, id) = clippy_utils::path_to_res(cx, &path.split("::").collect::<Vec<_>>()) {
61 self.renames.insert(id, Symbol::intern(rename));
66 fn check_item(&mut self, cx: &LateContext<'_>, item: &Item<'_>) {
68 if let ItemKind::Use(path, UseKind::Single) = &item.kind;
69 if let Res::Def(_, id) = path.res;
70 if let Some(name) = self.renames.get(&id);
71 // Remove semicolon since it is not present for nested imports
72 let span_without_semi = cx.sess().source_map().span_until_char(item.span, ';');
73 if let Some(snip) = snippet_opt(cx, span_without_semi);
74 if let Some(import) = match snip.split_once(" as ") {
75 None => Some(snip.as_str()),
76 Some((import, rename)) => {
77 if rename.trim() == &*name.as_str() {
87 MISSING_ENFORCED_IMPORT_RENAMES,
89 "this import should be renamed",
96 Applicability::MachineApplicable,