1 use clippy_utils::diagnostics::span_lint_hir_and_then;
2 use clippy_utils::source::snippet;
3 use hir::def::{DefKind, Res};
4 use if_chain::if_chain;
6 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
7 use rustc_errors::Applicability;
9 use rustc_lint::{LateContext, LateLintPass, LintContext};
10 use rustc_session::{declare_tool_lint, impl_lint_pass};
11 use rustc_span::{edition::Edition, sym, Span};
13 declare_clippy_lint! {
15 /// Checks for `#[macro_use] use...`.
17 /// ### Why is this bad?
18 /// Since the Rust 2018 edition you can import
19 /// macro's directly, this is considered idiomatic.
26 #[clippy::version = "1.44.0"]
27 pub MACRO_USE_IMPORTS,
29 "#[macro_use] is no longer needed"
32 #[derive(Clone, Debug, PartialEq, Eq)]
38 /// `MacroRefData` includes the name of the macro.
39 #[derive(Debug, Clone)]
40 pub struct MacroRefData {
45 pub fn new(name: String) -> Self {
51 #[expect(clippy::module_name_repetitions)]
52 pub struct MacroUseImports {
53 /// the actual import path used and the span of the attribute above it. The value is
54 /// the location, where the lint should be emitted.
55 imports: Vec<(String, Span, hir::HirId)>,
56 /// the span of the macro reference, kept to ensure only one reference is used per macro call.
57 collected: FxHashSet<Span>,
58 mac_refs: Vec<MacroRefData>,
61 impl_lint_pass!(MacroUseImports => [MACRO_USE_IMPORTS]);
63 impl MacroUseImports {
64 fn push_unique_macro(&mut self, cx: &LateContext<'_>, span: Span) {
65 let call_site = span.source_callsite();
66 let name = snippet(cx, cx.sess().source_map().span_until_char(call_site, '!'), "_");
67 if span.source_callee().is_some() && !self.collected.contains(&call_site) {
68 let name = if name.contains("::") {
69 name.split("::").last().unwrap().to_string()
74 self.mac_refs.push(MacroRefData::new(name));
75 self.collected.insert(call_site);
79 fn push_unique_macro_pat_ty(&mut self, cx: &LateContext<'_>, span: Span) {
80 let call_site = span.source_callsite();
81 let name = snippet(cx, cx.sess().source_map().span_until_char(call_site, '!'), "_");
82 if span.source_callee().is_some() && !self.collected.contains(&call_site) {
83 self.mac_refs.push(MacroRefData::new(name.to_string()));
84 self.collected.insert(call_site);
89 impl<'tcx> LateLintPass<'tcx> for MacroUseImports {
90 fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) {
92 if cx.sess().opts.edition >= Edition::Edition2018;
93 if let hir::ItemKind::Use(path, _kind) = &item.kind;
94 let hir_id = item.hir_id();
95 let attrs = cx.tcx.hir().attrs(hir_id);
96 if let Some(mac_attr) = attrs.iter().find(|attr| attr.has_name(sym::macro_use));
97 if let Some(id) = path.res.iter().find_map(|res| match res {
98 Res::Def(DefKind::Mod, id) => Some(id),
103 for kid in cx.tcx.module_children(id).iter() {
104 if let Res::Def(DefKind::Macro(_mac_type), mac_id) = kid.res {
105 let span = mac_attr.span;
106 let def_path = cx.tcx.def_path_str(mac_id);
107 self.imports.push((def_path, span, hir_id));
111 if item.span.from_expansion() {
112 self.push_unique_macro_pat_ty(cx, item.span);
117 fn check_attribute(&mut self, cx: &LateContext<'_>, attr: &ast::Attribute) {
118 if attr.span.from_expansion() {
119 self.push_unique_macro(cx, attr.span);
122 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &hir::Expr<'_>) {
123 if expr.span.from_expansion() {
124 self.push_unique_macro(cx, expr.span);
127 fn check_stmt(&mut self, cx: &LateContext<'_>, stmt: &hir::Stmt<'_>) {
128 if stmt.span.from_expansion() {
129 self.push_unique_macro(cx, stmt.span);
132 fn check_pat(&mut self, cx: &LateContext<'_>, pat: &hir::Pat<'_>) {
133 if pat.span.from_expansion() {
134 self.push_unique_macro_pat_ty(cx, pat.span);
137 fn check_ty(&mut self, cx: &LateContext<'_>, ty: &hir::Ty<'_>) {
138 if ty.span.from_expansion() {
139 self.push_unique_macro_pat_ty(cx, ty.span);
142 fn check_crate_post(&mut self, cx: &LateContext<'_>) {
143 let mut used = FxHashMap::default();
144 let mut check_dup = vec![];
145 for (import, span, hir_id) in &self.imports {
146 let found_idx = self.mac_refs.iter().position(|mac| import.ends_with(&mac.name));
148 if let Some(idx) = found_idx {
149 self.mac_refs.remove(idx);
150 let seg = import.split("::").collect::<Vec<_>>();
152 match seg.as_slice() {
153 // an empty path is impossible
154 // a path should always consist of 2 or more segments
157 if !check_dup.contains(&(*item).to_string()) {
158 used.entry(((*root).to_string(), span, hir_id))
159 .or_insert_with(Vec::new)
160 .push((*item).to_string());
161 check_dup.push((*item).to_string());
164 [root, rest @ ..] => {
165 if rest.iter().all(|item| !check_dup.contains(&(*item).to_string())) {
169 if check_dup.contains(&(*item).to_string()) {
172 Some((*item).to_string())
175 .collect::<Vec<_>>();
176 used.entry(((*root).to_string(), span, hir_id))
177 .or_insert_with(Vec::new)
178 .push(filtered.join("::"));
179 check_dup.extend(filtered);
181 let rest = rest.to_vec();
182 used.entry(((*root).to_string(), span, hir_id))
183 .or_insert_with(Vec::new)
184 .push(rest.join("::"));
185 check_dup.extend(rest.iter().map(ToString::to_string));
192 let mut suggestions = vec![];
193 for ((root, span, hir_id), path) in used {
195 suggestions.push((span, format!("{root}::{}", path[0]), hir_id));
197 suggestions.push((span, format!("{root}::{{{}}}", path.join(", ")), hir_id));
201 // If mac_refs is not empty we have encountered an import we could not handle
202 // such as `std::prelude::v1::foo` or some other macro that expands to an import.
203 if self.mac_refs.is_empty() {
204 for (span, import, hir_id) in suggestions {
205 let help = format!("use {import};");
206 span_lint_hir_and_then(
211 "`macro_use` attributes are no longer needed in the Rust 2018 edition",
213 diag.span_suggestion(
215 "remove the attribute and import the macro directly, try",
217 Applicability::MaybeIncorrect,