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! {
16 /// Checks for `#[macro_use] use...`.
18 /// ### Why is this bad?
19 /// Since the Rust 2018 edition you can import
20 /// macro's directly, this is considered idiomatic.
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 #[allow(clippy::module_name_repetitions)]
53 pub struct MacroUseImports {
54 /// the actual import path used and the span of the attribute above it.
55 imports: Vec<(String, Span)>,
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 attrs = cx.tcx.hir().attrs(item.hir_id());
95 if let Some(mac_attr) = attrs.iter().find(|attr| attr.has_name(sym::macro_use));
96 if let Res::Def(DefKind::Mod, id) = path.res;
99 for kid in cx.tcx.item_children(id).iter() {
100 if let Res::Def(DefKind::Macro(_mac_type), mac_id) = kid.res {
101 let span = mac_attr.span;
102 let def_path = cx.tcx.def_path_str(mac_id);
103 self.imports.push((def_path, span));
107 if in_macro(item.span) {
108 self.push_unique_macro_pat_ty(cx, item.span);
113 fn check_attribute(&mut self, cx: &LateContext<'_>, attr: &ast::Attribute) {
114 if in_macro(attr.span) {
115 self.push_unique_macro(cx, attr.span);
118 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &hir::Expr<'_>) {
119 if in_macro(expr.span) {
120 self.push_unique_macro(cx, expr.span);
123 fn check_stmt(&mut self, cx: &LateContext<'_>, stmt: &hir::Stmt<'_>) {
124 if in_macro(stmt.span) {
125 self.push_unique_macro(cx, stmt.span);
128 fn check_pat(&mut self, cx: &LateContext<'_>, pat: &hir::Pat<'_>) {
129 if in_macro(pat.span) {
130 self.push_unique_macro_pat_ty(cx, pat.span);
133 fn check_ty(&mut self, cx: &LateContext<'_>, ty: &hir::Ty<'_>) {
134 if in_macro(ty.span) {
135 self.push_unique_macro_pat_ty(cx, ty.span);
138 #[allow(clippy::too_many_lines)]
139 fn check_crate_post(&mut self, cx: &LateContext<'_>, _krate: &hir::Crate<'_>) {
140 let mut used = FxHashMap::default();
141 let mut check_dup = vec![];
142 for (import, span) in &self.imports {
143 let found_idx = self.mac_refs.iter().position(|mac| import.ends_with(&mac.name));
145 if let Some(idx) = found_idx {
146 self.mac_refs.remove(idx);
147 let seg = import.split("::").collect::<Vec<_>>();
149 match seg.as_slice() {
150 // an empty path is impossible
151 // a path should always consist of 2 or more segments
154 if !check_dup.contains(&(*item).to_string()) {
155 used.entry(((*root).to_string(), span))
156 .or_insert_with(Vec::new)
157 .push((*item).to_string());
158 check_dup.push((*item).to_string());
161 [root, rest @ ..] => {
162 if rest.iter().all(|item| !check_dup.contains(&(*item).to_string())) {
166 if check_dup.contains(&(*item).to_string()) {
169 Some((*item).to_string())
172 .collect::<Vec<_>>();
173 used.entry(((*root).to_string(), span))
174 .or_insert_with(Vec::new)
175 .push(filtered.join("::"));
176 check_dup.extend(filtered);
178 let rest = rest.to_vec();
179 used.entry(((*root).to_string(), span))
180 .or_insert_with(Vec::new)
181 .push(rest.join("::"));
182 check_dup.extend(rest.iter().map(ToString::to_string));
189 let mut suggestions = vec![];
190 for ((root, span), path) in used {
192 suggestions.push((span, format!("{}::{}", root, path[0])));
194 suggestions.push((span, format!("{}::{{{}}}", root, path.join(", "))));
198 // If mac_refs is not empty we have encountered an import we could not handle
199 // such as `std::prelude::v1::foo` or some other macro that expands to an import.
200 if self.mac_refs.is_empty() {
201 for (span, import) in suggestions {
202 let help = format!("use {};", import);
207 "`macro_use` attributes are no longer needed in the Rust 2018 edition",
208 "remove the attribute and import the macro directly, try",
210 Applicability::MaybeIncorrect,