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 #[derive(Debug, Clone)]
40 pub struct MacroRefData {
45 pub fn new(name: String) -> Self {
51 #[allow(clippy::module_name_repetitions)]
52 pub struct MacroUseImports {
53 /// the actual import path used and the span of the attribute above it.
54 imports: Vec<(String, Span)>,
55 /// the span of the macro reference, kept to ensure only one reference is used per macro call.
56 collected: FxHashSet<Span>,
57 mac_refs: Vec<MacroRefData>,
60 impl_lint_pass!(MacroUseImports => [MACRO_USE_IMPORTS]);
62 impl MacroUseImports {
63 fn push_unique_macro(&mut self, cx: &LateContext<'_>, span: Span) {
64 let call_site = span.source_callsite();
65 let name = snippet(cx, cx.sess().source_map().span_until_char(call_site, '!'), "_");
66 if span.source_callee().is_some() && !self.collected.contains(&call_site) {
67 let name = if name.contains("::") {
68 name.split("::").last().unwrap().to_string()
73 self.mac_refs.push(MacroRefData::new(name));
74 self.collected.insert(call_site);
78 fn push_unique_macro_pat_ty(&mut self, cx: &LateContext<'_>, span: Span) {
79 let call_site = span.source_callsite();
80 let name = snippet(cx, cx.sess().source_map().span_until_char(call_site, '!'), "_");
81 if span.source_callee().is_some() && !self.collected.contains(&call_site) {
82 self.mac_refs.push(MacroRefData::new(name.to_string()));
83 self.collected.insert(call_site);
88 impl<'tcx> LateLintPass<'tcx> for MacroUseImports {
89 fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) {
91 if cx.sess().opts.edition >= Edition::Edition2018;
92 if let hir::ItemKind::Use(path, _kind) = &item.kind;
93 let attrs = cx.tcx.hir().attrs(item.hir_id());
94 if let Some(mac_attr) = attrs.iter().find(|attr| attr.has_name(sym::macro_use));
95 if let Res::Def(DefKind::Mod, id) = path.res;
98 for kid in cx.tcx.item_children(id).iter() {
99 if let Res::Def(DefKind::Macro(_mac_type), mac_id) = kid.res {
100 let span = mac_attr.span;
101 let def_path = cx.tcx.def_path_str(mac_id);
102 self.imports.push((def_path, span));
106 if in_macro(item.span) {
107 self.push_unique_macro_pat_ty(cx, item.span);
112 fn check_attribute(&mut self, cx: &LateContext<'_>, attr: &ast::Attribute) {
113 if in_macro(attr.span) {
114 self.push_unique_macro(cx, attr.span);
117 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &hir::Expr<'_>) {
118 if in_macro(expr.span) {
119 self.push_unique_macro(cx, expr.span);
122 fn check_stmt(&mut self, cx: &LateContext<'_>, stmt: &hir::Stmt<'_>) {
123 if in_macro(stmt.span) {
124 self.push_unique_macro(cx, stmt.span);
127 fn check_pat(&mut self, cx: &LateContext<'_>, pat: &hir::Pat<'_>) {
128 if in_macro(pat.span) {
129 self.push_unique_macro_pat_ty(cx, pat.span);
132 fn check_ty(&mut self, cx: &LateContext<'_>, ty: &hir::Ty<'_>) {
133 if in_macro(ty.span) {
134 self.push_unique_macro_pat_ty(cx, ty.span);
137 #[allow(clippy::too_many_lines)]
138 fn check_crate_post(&mut self, cx: &LateContext<'_>) {
139 let mut used = FxHashMap::default();
140 let mut check_dup = vec![];
141 for (import, span) in &self.imports {
142 let found_idx = self.mac_refs.iter().position(|mac| import.ends_with(&mac.name));
144 if let Some(idx) = found_idx {
145 self.mac_refs.remove(idx);
146 let seg = import.split("::").collect::<Vec<_>>();
148 match seg.as_slice() {
149 // an empty path is impossible
150 // a path should always consist of 2 or more segments
153 if !check_dup.contains(&(*item).to_string()) {
154 used.entry(((*root).to_string(), span))
155 .or_insert_with(Vec::new)
156 .push((*item).to_string());
157 check_dup.push((*item).to_string());
160 [root, rest @ ..] => {
161 if rest.iter().all(|item| !check_dup.contains(&(*item).to_string())) {
165 if check_dup.contains(&(*item).to_string()) {
168 Some((*item).to_string())
171 .collect::<Vec<_>>();
172 used.entry(((*root).to_string(), span))
173 .or_insert_with(Vec::new)
174 .push(filtered.join("::"));
175 check_dup.extend(filtered);
177 let rest = rest.to_vec();
178 used.entry(((*root).to_string(), span))
179 .or_insert_with(Vec::new)
180 .push(rest.join("::"));
181 check_dup.extend(rest.iter().map(ToString::to_string));
188 let mut suggestions = vec![];
189 for ((root, span), path) in used {
191 suggestions.push((span, format!("{}::{}", root, path[0])));
193 suggestions.push((span, format!("{}::{{{}}}", root, path.join(", "))));
197 // If mac_refs is not empty we have encountered an import we could not handle
198 // such as `std::prelude::v1::foo` or some other macro that expands to an import.
199 if self.mac_refs.is_empty() {
200 for (span, import) in suggestions {
201 let help = format!("use {};", import);
206 "`macro_use` attributes are no longer needed in the Rust 2018 edition",
207 "remove the attribute and import the macro directly, try",
209 Applicability::MaybeIncorrect,