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 /// and the path from `SourceMap::span_to_filename`.
40 #[derive(Debug, Clone)]
41 pub struct MacroRefData {
46 pub fn new(name: String) -> Self {
52 #[expect(clippy::module_name_repetitions)]
53 pub struct MacroUseImports {
54 /// the actual import path used and the span of the attribute above it. The value is
55 /// the location, where the lint should be emitted.
56 imports: Vec<(String, Span, hir::HirId)>,
57 /// the span of the macro reference, kept to ensure only one reference is used per macro call.
58 collected: FxHashSet<Span>,
59 mac_refs: Vec<MacroRefData>,
62 impl_lint_pass!(MacroUseImports => [MACRO_USE_IMPORTS]);
64 impl MacroUseImports {
65 fn push_unique_macro(&mut self, cx: &LateContext<'_>, span: Span) {
66 let call_site = span.source_callsite();
67 let name = snippet(cx, cx.sess().source_map().span_until_char(call_site, '!'), "_");
68 if span.source_callee().is_some() && !self.collected.contains(&call_site) {
69 let name = if name.contains("::") {
70 name.split("::").last().unwrap().to_string()
75 self.mac_refs.push(MacroRefData::new(name));
76 self.collected.insert(call_site);
80 fn push_unique_macro_pat_ty(&mut self, cx: &LateContext<'_>, span: Span) {
81 let call_site = span.source_callsite();
82 let name = snippet(cx, cx.sess().source_map().span_until_char(call_site, '!'), "_");
83 if span.source_callee().is_some() && !self.collected.contains(&call_site) {
84 self.mac_refs.push(MacroRefData::new(name.to_string()));
85 self.collected.insert(call_site);
90 impl<'tcx> LateLintPass<'tcx> for MacroUseImports {
91 fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) {
93 if cx.sess().opts.edition >= Edition::Edition2018;
94 if let hir::ItemKind::Use(path, _kind) = &item.kind;
95 let hir_id = item.hir_id();
96 let attrs = cx.tcx.hir().attrs(hir_id);
97 if let Some(mac_attr) = attrs.iter().find(|attr| attr.has_name(sym::macro_use));
98 if let Res::Def(DefKind::Mod, id) = path.res;
101 for kid in cx.tcx.module_children(id).iter() {
102 if let Res::Def(DefKind::Macro(_mac_type), mac_id) = kid.res {
103 let span = mac_attr.span;
104 let def_path = cx.tcx.def_path_str(mac_id);
105 self.imports.push((def_path, span, hir_id));
109 if item.span.from_expansion() {
110 self.push_unique_macro_pat_ty(cx, item.span);
115 fn check_attribute(&mut self, cx: &LateContext<'_>, attr: &ast::Attribute) {
116 if attr.span.from_expansion() {
117 self.push_unique_macro(cx, attr.span);
120 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &hir::Expr<'_>) {
121 if expr.span.from_expansion() {
122 self.push_unique_macro(cx, expr.span);
125 fn check_stmt(&mut self, cx: &LateContext<'_>, stmt: &hir::Stmt<'_>) {
126 if stmt.span.from_expansion() {
127 self.push_unique_macro(cx, stmt.span);
130 fn check_pat(&mut self, cx: &LateContext<'_>, pat: &hir::Pat<'_>) {
131 if pat.span.from_expansion() {
132 self.push_unique_macro_pat_ty(cx, pat.span);
135 fn check_ty(&mut self, cx: &LateContext<'_>, ty: &hir::Ty<'_>) {
136 if ty.span.from_expansion() {
137 self.push_unique_macro_pat_ty(cx, ty.span);
140 fn check_crate_post(&mut self, cx: &LateContext<'_>) {
141 let mut used = FxHashMap::default();
142 let mut check_dup = vec![];
143 for (import, span, hir_id) in &self.imports {
144 let found_idx = self.mac_refs.iter().position(|mac| import.ends_with(&mac.name));
146 if let Some(idx) = found_idx {
147 self.mac_refs.remove(idx);
148 let seg = import.split("::").collect::<Vec<_>>();
150 match seg.as_slice() {
151 // an empty path is impossible
152 // a path should always consist of 2 or more segments
155 if !check_dup.contains(&(*item).to_string()) {
156 used.entry(((*root).to_string(), span, hir_id))
157 .or_insert_with(Vec::new)
158 .push((*item).to_string());
159 check_dup.push((*item).to_string());
162 [root, rest @ ..] => {
163 if rest.iter().all(|item| !check_dup.contains(&(*item).to_string())) {
167 if check_dup.contains(&(*item).to_string()) {
170 Some((*item).to_string())
173 .collect::<Vec<_>>();
174 used.entry(((*root).to_string(), span, hir_id))
175 .or_insert_with(Vec::new)
176 .push(filtered.join("::"));
177 check_dup.extend(filtered);
179 let rest = rest.to_vec();
180 used.entry(((*root).to_string(), span, hir_id))
181 .or_insert_with(Vec::new)
182 .push(rest.join("::"));
183 check_dup.extend(rest.iter().map(ToString::to_string));
190 let mut suggestions = vec![];
191 for ((root, span, hir_id), path) in used {
193 suggestions.push((span, format!("{}::{}", root, path[0]), hir_id));
195 suggestions.push((span, format!("{}::{{{}}}", root, path.join(", ")), hir_id));
199 // If mac_refs is not empty we have encountered an import we could not handle
200 // such as `std::prelude::v1::foo` or some other macro that expands to an import.
201 if self.mac_refs.is_empty() {
202 for (span, import, hir_id) in suggestions {
203 let help = format!("use {};", import);
204 span_lint_hir_and_then(
209 "`macro_use` attributes are no longer needed in the Rust 2018 edition",
211 diag.span_suggestion(
213 "remove the attribute and import the macro directly, try",
215 Applicability::MaybeIncorrect,