]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/macro_use.rs
Rollup merge of #88729 - estebank:struct-literal-using-parens, r=oli-obk
[rust.git] / src / tools / clippy / 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 #[derive(Clone, Debug, PartialEq, Eq)]
33 struct PathAndSpan {
34     path: String,
35     span: Span,
36 }
37
38 /// `MacroRefData` includes the name of the macro.
39 #[derive(Debug, Clone)]
40 pub struct MacroRefData {
41     name: String,
42 }
43
44 impl MacroRefData {
45     pub fn new(name: String) -> Self {
46         Self { name }
47     }
48 }
49
50 #[derive(Default)]
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>,
58 }
59
60 impl_lint_pass!(MacroUseImports => [MACRO_USE_IMPORTS]);
61
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 let Some(_callee) = span.source_callee() {
67             if !self.collected.contains(&call_site) {
68                 let name = if name.contains("::") {
69                     name.split("::").last().unwrap().to_string()
70                 } else {
71                     name.to_string()
72                 };
73
74                 self.mac_refs.push(MacroRefData::new(name));
75                 self.collected.insert(call_site);
76             }
77         }
78     }
79
80     fn push_unique_macro_pat_ty(&mut self, cx: &LateContext<'_>, span: Span) {
81         let call_site = span.source_callsite();
82         let name = snippet(cx, cx.sess().source_map().span_until_char(call_site, '!'), "_");
83         if let Some(_callee) = span.source_callee() {
84             if !self.collected.contains(&call_site) {
85                 self.mac_refs
86                     .push(MacroRefData::new(name.to_string()));
87                 self.collected.insert(call_site);
88             }
89         }
90     }
91 }
92
93 impl<'tcx> LateLintPass<'tcx> for MacroUseImports {
94     fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) {
95         if_chain! {
96             if cx.sess().opts.edition >= Edition::Edition2018;
97             if let hir::ItemKind::Use(path, _kind) = &item.kind;
98             let attrs = cx.tcx.hir().attrs(item.hir_id());
99             if let Some(mac_attr) = attrs.iter().find(|attr| attr.has_name(sym::macro_use));
100             if let Res::Def(DefKind::Mod, id) = path.res;
101             if !id.is_local();
102             then {
103                 for kid in cx.tcx.item_children(id).iter() {
104                     if let Res::Def(DefKind::Macro(_mac_type), mac_id) = kid.res {
105                         let span = mac_attr.span;
106                         let def_path = cx.tcx.def_path_str(mac_id);
107                         self.imports.push((def_path, span));
108                     }
109                 }
110             } else {
111                 if in_macro(item.span) {
112                     self.push_unique_macro_pat_ty(cx, item.span);
113                 }
114             }
115         }
116     }
117     fn check_attribute(&mut self, cx: &LateContext<'_>, attr: &ast::Attribute) {
118         if in_macro(attr.span) {
119             self.push_unique_macro(cx, attr.span);
120         }
121     }
122     fn check_expr(&mut self, cx: &LateContext<'_>, expr: &hir::Expr<'_>) {
123         if in_macro(expr.span) {
124             self.push_unique_macro(cx, expr.span);
125         }
126     }
127     fn check_stmt(&mut self, cx: &LateContext<'_>, stmt: &hir::Stmt<'_>) {
128         if in_macro(stmt.span) {
129             self.push_unique_macro(cx, stmt.span);
130         }
131     }
132     fn check_pat(&mut self, cx: &LateContext<'_>, pat: &hir::Pat<'_>) {
133         if in_macro(pat.span) {
134             self.push_unique_macro_pat_ty(cx, pat.span);
135         }
136     }
137     fn check_ty(&mut self, cx: &LateContext<'_>, ty: &hir::Ty<'_>) {
138         if in_macro(ty.span) {
139             self.push_unique_macro_pat_ty(cx, ty.span);
140         }
141     }
142     #[allow(clippy::too_many_lines)]
143     fn check_crate_post(&mut self, cx: &LateContext<'_>, _krate: &hir::Crate<'_>) {
144         let mut used = FxHashMap::default();
145         let mut check_dup = vec![];
146         for (import, span) in &self.imports {
147             let found_idx = self.mac_refs.iter().position(|mac| import.ends_with(&mac.name));
148
149             if let Some(idx) = found_idx {
150                 self.mac_refs.remove(idx);
151                 let seg = import.split("::").collect::<Vec<_>>();
152
153                 match seg.as_slice() {
154                     // an empty path is impossible
155                     // a path should always consist of 2 or more segments
156                     [] | [_] => return,
157                     [root, item] => {
158                         if !check_dup.contains(&(*item).to_string()) {
159                             used.entry(((*root).to_string(), span))
160                                 .or_insert_with(Vec::new)
161                                 .push((*item).to_string());
162                             check_dup.push((*item).to_string());
163                         }
164                     },
165                     [root, rest @ ..] => {
166                         if rest.iter().all(|item| !check_dup.contains(&(*item).to_string())) {
167                             let filtered = rest
168                                 .iter()
169                                 .filter_map(|item| {
170                                     if check_dup.contains(&(*item).to_string()) {
171                                         None
172                                     } else {
173                                         Some((*item).to_string())
174                                     }
175                                 })
176                                 .collect::<Vec<_>>();
177                             used.entry(((*root).to_string(), span))
178                                 .or_insert_with(Vec::new)
179                                 .push(filtered.join("::"));
180                             check_dup.extend(filtered);
181                         } else {
182                             let rest = rest.to_vec();
183                             used.entry(((*root).to_string(), span))
184                                 .or_insert_with(Vec::new)
185                                 .push(rest.join("::"));
186                             check_dup.extend(rest.iter().map(ToString::to_string));
187                         }
188                     },
189                 }
190             }
191         }
192
193         let mut suggestions = vec![];
194         for ((root, span), path) in used {
195             if path.len() == 1 {
196                 suggestions.push((span, format!("{}::{}", root, path[0])));
197             } else {
198                 suggestions.push((span, format!("{}::{{{}}}", root, path.join(", "))));
199             }
200         }
201
202         // If mac_refs is not empty we have encountered an import we could not handle
203         // such as `std::prelude::v1::foo` or some other macro that expands to an import.
204         if self.mac_refs.is_empty() {
205             for (span, import) in suggestions {
206                 let help = format!("use {};", import);
207                 span_lint_and_sugg(
208                     cx,
209                     MACRO_USE_IMPORTS,
210                     *span,
211                     "`macro_use` attributes are no longer needed in the Rust 2018 edition",
212                     "remove the attribute and import the macro directly, try",
213                     help,
214                     Applicability::MaybeIncorrect,
215                 );
216             }
217         }
218     }
219 }