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