1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::in_macro;
3 use clippy_utils::source::snippet;
4 use hir::def::{DefKind, Res};
5 use if_chain::if_chain;
7 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
8 use rustc_errors::Applicability;
10 use rustc_lint::{LateContext, LateLintPass, LintContext};
11 use rustc_session::{declare_tool_lint, impl_lint_pass};
12 use rustc_span::{edition::Edition, sym, Span};
14 declare_clippy_lint! {
15 /// **What it does:** Checks for `#[macro_use] use...`.
17 /// **Why is this bad?** Since the Rust 2018 edition you can import
18 /// macro's directly, this is considered idiomatic.
20 /// **Known problems:** None.
27 pub MACRO_USE_IMPORTS,
29 "#[macro_use] is no longer needed"
32 const BRACKETS: &[char] = &['<', '>'];
34 #[derive(Clone, Debug, PartialEq, Eq)]
40 /// `MacroRefData` includes the name of the macro
41 /// and the path from `SourceMap::span_to_filename`.
42 #[derive(Debug, Clone)]
43 pub struct MacroRefData {
49 pub fn new(name: String, callee: Span, cx: &LateContext<'_>) -> Self {
50 let mut path = cx.sess().source_map().span_to_filename(callee).to_string();
52 // std lib paths are <::std::module::file type>
53 // so remove brackets, space and type.
54 if path.contains('<') {
55 path = path.replace(BRACKETS, "");
57 if path.contains(' ') {
58 path = path.split(' ').next().unwrap().to_string();
65 #[allow(clippy::module_name_repetitions)]
66 pub struct MacroUseImports {
67 /// the actual import path used and the span of the attribute above it.
68 imports: Vec<(String, Span)>,
69 /// the span of the macro reference, kept to ensure only one reference is used per macro call.
70 collected: FxHashSet<Span>,
71 mac_refs: Vec<MacroRefData>,
74 impl_lint_pass!(MacroUseImports => [MACRO_USE_IMPORTS]);
76 impl MacroUseImports {
77 fn push_unique_macro(&mut self, cx: &LateContext<'_>, span: Span) {
78 let call_site = span.source_callsite();
79 let name = snippet(cx, cx.sess().source_map().span_until_char(call_site, '!'), "_");
80 if let Some(callee) = span.source_callee() {
81 if !self.collected.contains(&call_site) {
82 let name = if name.contains("::") {
83 name.split("::").last().unwrap().to_string()
88 self.mac_refs.push(MacroRefData::new(name, callee.def_site, cx));
89 self.collected.insert(call_site);
94 fn push_unique_macro_pat_ty(&mut self, cx: &LateContext<'_>, span: Span) {
95 let call_site = span.source_callsite();
96 let name = snippet(cx, cx.sess().source_map().span_until_char(call_site, '!'), "_");
97 if let Some(callee) = span.source_callee() {
98 if !self.collected.contains(&call_site) {
100 .push(MacroRefData::new(name.to_string(), callee.def_site, cx));
101 self.collected.insert(call_site);
107 impl<'tcx> LateLintPass<'tcx> for MacroUseImports {
108 fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) {
110 if cx.sess().opts.edition >= Edition::Edition2018;
111 if let hir::ItemKind::Use(path, _kind) = &item.kind;
112 let attrs = cx.tcx.hir().attrs(item.hir_id());
113 if let Some(mac_attr) = attrs.iter().find(|attr| attr.has_name(sym::macro_use));
114 if let Res::Def(DefKind::Mod, id) = path.res;
117 for kid in cx.tcx.item_children(id).iter() {
118 if let Res::Def(DefKind::Macro(_mac_type), mac_id) = kid.res {
119 let span = mac_attr.span;
120 let def_path = cx.tcx.def_path_str(mac_id);
121 self.imports.push((def_path, span));
125 if in_macro(item.span) {
126 self.push_unique_macro_pat_ty(cx, item.span);
131 fn check_attribute(&mut self, cx: &LateContext<'_>, attr: &ast::Attribute) {
132 if in_macro(attr.span) {
133 self.push_unique_macro(cx, attr.span);
136 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &hir::Expr<'_>) {
137 if in_macro(expr.span) {
138 self.push_unique_macro(cx, expr.span);
141 fn check_stmt(&mut self, cx: &LateContext<'_>, stmt: &hir::Stmt<'_>) {
142 if in_macro(stmt.span) {
143 self.push_unique_macro(cx, stmt.span);
146 fn check_pat(&mut self, cx: &LateContext<'_>, pat: &hir::Pat<'_>) {
147 if in_macro(pat.span) {
148 self.push_unique_macro_pat_ty(cx, pat.span);
151 fn check_ty(&mut self, cx: &LateContext<'_>, ty: &hir::Ty<'_>) {
152 if in_macro(ty.span) {
153 self.push_unique_macro_pat_ty(cx, ty.span);
156 #[allow(clippy::too_many_lines)]
157 fn check_crate_post(&mut self, cx: &LateContext<'_>, _krate: &hir::Crate<'_>) {
158 let mut used = FxHashMap::default();
159 let mut check_dup = vec![];
160 for (import, span) in &self.imports {
161 let found_idx = self.mac_refs.iter().position(|mac| import.ends_with(&mac.name));
163 if let Some(idx) = found_idx {
164 self.mac_refs.remove(idx);
165 let seg = import.split("::").collect::<Vec<_>>();
167 match seg.as_slice() {
168 // an empty path is impossible
169 // a path should always consist of 2 or more segments
172 if !check_dup.contains(&(*item).to_string()) {
173 used.entry(((*root).to_string(), span))
174 .or_insert_with(Vec::new)
175 .push((*item).to_string());
176 check_dup.push((*item).to_string());
179 [root, rest @ ..] => {
180 if rest.iter().all(|item| !check_dup.contains(&(*item).to_string())) {
184 if check_dup.contains(&(*item).to_string()) {
187 Some((*item).to_string())
190 .collect::<Vec<_>>();
191 used.entry(((*root).to_string(), span))
192 .or_insert_with(Vec::new)
193 .push(filtered.join("::"));
194 check_dup.extend(filtered);
196 let rest = rest.to_vec();
197 used.entry(((*root).to_string(), span))
198 .or_insert_with(Vec::new)
199 .push(rest.join("::"));
200 check_dup.extend(rest.iter().map(ToString::to_string));
207 let mut suggestions = vec![];
208 for ((root, span), path) in used {
210 suggestions.push((span, format!("{}::{}", root, path[0])))
212 suggestions.push((span, format!("{}::{{{}}}", root, path.join(", "))))
216 // If mac_refs is not empty we have encountered an import we could not handle
217 // such as `std::prelude::v1::foo` or some other macro that expands to an import.
218 if self.mac_refs.is_empty() {
219 for (span, import) in suggestions {
220 let help = format!("use {};", import);
225 "`macro_use` attributes are no longer needed in the Rust 2018 edition",
226 "remove the attribute and import the macro directly, try",
228 Applicability::MaybeIncorrect,