]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/macro_use.rs
Rollup merge of #7420 - xFrednet:7172-update-lint-documentation, r=flip1995
[rust.git] / clippy_lints / src / macro_use.rs
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;
6 use rustc_ast::ast;
7 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
8 use rustc_errors::Applicability;
9 use rustc_hir as hir;
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};
13
14 declare_clippy_lint! {
15     /// ### What it does
16     /// Checks for `#[macro_use] use...`.
17     ///
18     /// ### Why is this bad?
19     /// Since the Rust 2018 edition you can import
20     /// macro's directly, this is considered idiomatic.
21     ///
22     /// ### Example
23     /// ```rust,ignore
24     /// #[macro_use]
25     /// use some_macro;
26     /// ```
27     pub MACRO_USE_IMPORTS,
28     pedantic,
29     "#[macro_use] is no longer needed"
30 }
31
32 const BRACKETS: &[char] = &['<', '>'];
33
34 #[derive(Clone, Debug, PartialEq, Eq)]
35 struct PathAndSpan {
36     path: String,
37     span: Span,
38 }
39
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 {
44     name: String,
45     path: String,
46 }
47
48 impl MacroRefData {
49     pub fn new(name: String, callee: Span, cx: &LateContext<'_>) -> Self {
50         let mut path = cx
51             .sess()
52             .source_map()
53             .span_to_filename(callee)
54             .prefer_local()
55             .to_string();
56
57         // std lib paths are <::std::module::file type>
58         // so remove brackets, space and type.
59         if path.contains('<') {
60             path = path.replace(BRACKETS, "");
61         }
62         if path.contains(' ') {
63             path = path.split(' ').next().unwrap().to_string();
64         }
65         Self { name, path }
66     }
67 }
68
69 #[derive(Default)]
70 #[allow(clippy::module_name_repetitions)]
71 pub struct MacroUseImports {
72     /// the actual import path used and the span of the attribute above it.
73     imports: Vec<(String, Span)>,
74     /// the span of the macro reference, kept to ensure only one reference is used per macro call.
75     collected: FxHashSet<Span>,
76     mac_refs: Vec<MacroRefData>,
77 }
78
79 impl_lint_pass!(MacroUseImports => [MACRO_USE_IMPORTS]);
80
81 impl MacroUseImports {
82     fn push_unique_macro(&mut self, cx: &LateContext<'_>, span: Span) {
83         let call_site = span.source_callsite();
84         let name = snippet(cx, cx.sess().source_map().span_until_char(call_site, '!'), "_");
85         if let Some(callee) = span.source_callee() {
86             if !self.collected.contains(&call_site) {
87                 let name = if name.contains("::") {
88                     name.split("::").last().unwrap().to_string()
89                 } else {
90                     name.to_string()
91                 };
92
93                 self.mac_refs.push(MacroRefData::new(name, callee.def_site, cx));
94                 self.collected.insert(call_site);
95             }
96         }
97     }
98
99     fn push_unique_macro_pat_ty(&mut self, cx: &LateContext<'_>, span: Span) {
100         let call_site = span.source_callsite();
101         let name = snippet(cx, cx.sess().source_map().span_until_char(call_site, '!'), "_");
102         if let Some(callee) = span.source_callee() {
103             if !self.collected.contains(&call_site) {
104                 self.mac_refs
105                     .push(MacroRefData::new(name.to_string(), callee.def_site, cx));
106                 self.collected.insert(call_site);
107             }
108         }
109     }
110 }
111
112 impl<'tcx> LateLintPass<'tcx> for MacroUseImports {
113     fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) {
114         if_chain! {
115             if cx.sess().opts.edition >= Edition::Edition2018;
116             if let hir::ItemKind::Use(path, _kind) = &item.kind;
117             let attrs = cx.tcx.hir().attrs(item.hir_id());
118             if let Some(mac_attr) = attrs.iter().find(|attr| attr.has_name(sym::macro_use));
119             if let Res::Def(DefKind::Mod, id) = path.res;
120             if !id.is_local();
121             then {
122                 for kid in cx.tcx.item_children(id).iter() {
123                     if let Res::Def(DefKind::Macro(_mac_type), mac_id) = kid.res {
124                         let span = mac_attr.span;
125                         let def_path = cx.tcx.def_path_str(mac_id);
126                         self.imports.push((def_path, span));
127                     }
128                 }
129             } else {
130                 if in_macro(item.span) {
131                     self.push_unique_macro_pat_ty(cx, item.span);
132                 }
133             }
134         }
135     }
136     fn check_attribute(&mut self, cx: &LateContext<'_>, attr: &ast::Attribute) {
137         if in_macro(attr.span) {
138             self.push_unique_macro(cx, attr.span);
139         }
140     }
141     fn check_expr(&mut self, cx: &LateContext<'_>, expr: &hir::Expr<'_>) {
142         if in_macro(expr.span) {
143             self.push_unique_macro(cx, expr.span);
144         }
145     }
146     fn check_stmt(&mut self, cx: &LateContext<'_>, stmt: &hir::Stmt<'_>) {
147         if in_macro(stmt.span) {
148             self.push_unique_macro(cx, stmt.span);
149         }
150     }
151     fn check_pat(&mut self, cx: &LateContext<'_>, pat: &hir::Pat<'_>) {
152         if in_macro(pat.span) {
153             self.push_unique_macro_pat_ty(cx, pat.span);
154         }
155     }
156     fn check_ty(&mut self, cx: &LateContext<'_>, ty: &hir::Ty<'_>) {
157         if in_macro(ty.span) {
158             self.push_unique_macro_pat_ty(cx, ty.span);
159         }
160     }
161     #[allow(clippy::too_many_lines)]
162     fn check_crate_post(&mut self, cx: &LateContext<'_>, _krate: &hir::Crate<'_>) {
163         let mut used = FxHashMap::default();
164         let mut check_dup = vec![];
165         for (import, span) in &self.imports {
166             let found_idx = self.mac_refs.iter().position(|mac| import.ends_with(&mac.name));
167
168             if let Some(idx) = found_idx {
169                 self.mac_refs.remove(idx);
170                 let seg = import.split("::").collect::<Vec<_>>();
171
172                 match seg.as_slice() {
173                     // an empty path is impossible
174                     // a path should always consist of 2 or more segments
175                     [] | [_] => return,
176                     [root, item] => {
177                         if !check_dup.contains(&(*item).to_string()) {
178                             used.entry(((*root).to_string(), span))
179                                 .or_insert_with(Vec::new)
180                                 .push((*item).to_string());
181                             check_dup.push((*item).to_string());
182                         }
183                     },
184                     [root, rest @ ..] => {
185                         if rest.iter().all(|item| !check_dup.contains(&(*item).to_string())) {
186                             let filtered = rest
187                                 .iter()
188                                 .filter_map(|item| {
189                                     if check_dup.contains(&(*item).to_string()) {
190                                         None
191                                     } else {
192                                         Some((*item).to_string())
193                                     }
194                                 })
195                                 .collect::<Vec<_>>();
196                             used.entry(((*root).to_string(), span))
197                                 .or_insert_with(Vec::new)
198                                 .push(filtered.join("::"));
199                             check_dup.extend(filtered);
200                         } else {
201                             let rest = rest.to_vec();
202                             used.entry(((*root).to_string(), span))
203                                 .or_insert_with(Vec::new)
204                                 .push(rest.join("::"));
205                             check_dup.extend(rest.iter().map(ToString::to_string));
206                         }
207                     },
208                 }
209             }
210         }
211
212         let mut suggestions = vec![];
213         for ((root, span), path) in used {
214             if path.len() == 1 {
215                 suggestions.push((span, format!("{}::{}", root, path[0])));
216             } else {
217                 suggestions.push((span, format!("{}::{{{}}}", root, path.join(", "))));
218             }
219         }
220
221         // If mac_refs is not empty we have encountered an import we could not handle
222         // such as `std::prelude::v1::foo` or some other macro that expands to an import.
223         if self.mac_refs.is_empty() {
224             for (span, import) in suggestions {
225                 let help = format!("use {};", import);
226                 span_lint_and_sugg(
227                     cx,
228                     MACRO_USE_IMPORTS,
229                     *span,
230                     "`macro_use` attributes are no longer needed in the Rust 2018 edition",
231                     "remove the attribute and import the macro directly, try",
232                     help,
233                     Applicability::MaybeIncorrect,
234                 );
235             }
236         }
237     }
238 }