]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/macro_use.rs
Auto merge of #9487 - kraktus:question_mark, r=Jarcho
[rust.git] / clippy_lints / src / macro_use.rs
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;
5 use rustc_ast::ast;
6 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
7 use rustc_errors::Applicability;
8 use rustc_hir as hir;
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};
12
13 declare_clippy_lint! {
14     /// ### What it does
15     /// Checks for `#[macro_use] use...`.
16     ///
17     /// ### Why is this bad?
18     /// Since the Rust 2018 edition you can import
19     /// macro's directly, this is considered idiomatic.
20     ///
21     /// ### Example
22     /// ```rust,ignore
23     /// #[macro_use]
24     /// use some_macro;
25     /// ```
26     #[clippy::version = "1.44.0"]
27     pub MACRO_USE_IMPORTS,
28     pedantic,
29     "#[macro_use] is no longer needed"
30 }
31
32 #[derive(Clone, Debug, PartialEq, Eq)]
33 struct PathAndSpan {
34     path: String,
35     span: Span,
36 }
37
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 {
42     name: String,
43 }
44
45 impl MacroRefData {
46     pub fn new(name: String) -> Self {
47         Self { name }
48     }
49 }
50
51 #[derive(Default)]
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>,
60 }
61
62 impl_lint_pass!(MacroUseImports => [MACRO_USE_IMPORTS]);
63
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()
71             } else {
72                 name.to_string()
73             };
74
75             self.mac_refs.push(MacroRefData::new(name));
76             self.collected.insert(call_site);
77         }
78     }
79
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);
86         }
87     }
88 }
89
90 impl<'tcx> LateLintPass<'tcx> for MacroUseImports {
91     fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) {
92         if_chain! {
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;
99             if !id.is_local();
100             then {
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));
106                     }
107                 }
108             } else {
109                 if item.span.from_expansion() {
110                     self.push_unique_macro_pat_ty(cx, item.span);
111                 }
112             }
113         }
114     }
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);
118         }
119     }
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);
123         }
124     }
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);
128         }
129     }
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);
133         }
134     }
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);
138         }
139     }
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));
145
146             if let Some(idx) = found_idx {
147                 self.mac_refs.remove(idx);
148                 let seg = import.split("::").collect::<Vec<_>>();
149
150                 match seg.as_slice() {
151                     // an empty path is impossible
152                     // a path should always consist of 2 or more segments
153                     [] | [_] => return,
154                     [root, item] => {
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());
160                         }
161                     },
162                     [root, rest @ ..] => {
163                         if rest.iter().all(|item| !check_dup.contains(&(*item).to_string())) {
164                             let filtered = rest
165                                 .iter()
166                                 .filter_map(|item| {
167                                     if check_dup.contains(&(*item).to_string()) {
168                                         None
169                                     } else {
170                                         Some((*item).to_string())
171                                     }
172                                 })
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);
178                         } else {
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));
184                         }
185                     },
186                 }
187             }
188         }
189
190         let mut suggestions = vec![];
191         for ((root, span, hir_id), path) in used {
192             if path.len() == 1 {
193                 suggestions.push((span, format!("{root}::{}", path[0]), hir_id));
194             } else {
195                 suggestions.push((span, format!("{root}::{{{}}}", path.join(", ")), hir_id));
196             }
197         }
198
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(
205                     cx,
206                     MACRO_USE_IMPORTS,
207                     *hir_id,
208                     *span,
209                     "`macro_use` attributes are no longer needed in the Rust 2018 edition",
210                     |diag| {
211                         diag.span_suggestion(
212                             *span,
213                             "remove the attribute and import the macro directly, try",
214                             help,
215                             Applicability::MaybeIncorrect,
216                         );
217                     },
218                 );
219             }
220         }
221     }
222 }