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