]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_resolve/src/check_unused.rs
Rollup merge of #94586 - sunfishcode:sunfishcode/io-lifetimes-tests, r=davidtwco
[rust.git] / compiler / rustc_resolve / src / check_unused.rs
1 //
2 // Unused import checking
3 //
4 // Although this is mostly a lint pass, it lives in here because it depends on
5 // resolve data structures and because it finalises the privacy information for
6 // `use` items.
7 //
8 // Unused trait imports can't be checked until the method resolution. We save
9 // candidates here, and do the actual check in librustc_typeck/check_unused.rs.
10 //
11 // Checking for unused imports is split into three steps:
12 //
13 //  - `UnusedImportCheckVisitor` walks the AST to find all the unused imports
14 //    inside of `UseTree`s, recording their `NodeId`s and grouping them by
15 //    the parent `use` item
16 //
17 //  - `calc_unused_spans` then walks over all the `use` items marked in the
18 //    previous step to collect the spans associated with the `NodeId`s and to
19 //    calculate the spans that can be removed by rustfix; This is done in a
20 //    separate step to be able to collapse the adjacent spans that rustfix
21 //    will remove
22 //
23 //  - `check_crate` finally emits the diagnostics based on the data generated
24 //    in the last step
25
26 use crate::imports::ImportKind;
27 use crate::module_to_string;
28 use crate::Resolver;
29
30 use rustc_ast as ast;
31 use rustc_ast::node_id::NodeMap;
32 use rustc_ast::visit::{self, Visitor};
33 use rustc_ast_lowering::ResolverAstLowering;
34 use rustc_data_structures::fx::FxHashSet;
35 use rustc_errors::pluralize;
36 use rustc_session::lint::builtin::{MACRO_USE_EXTERN_CRATE, UNUSED_IMPORTS};
37 use rustc_session::lint::BuiltinLintDiagnostics;
38 use rustc_span::{MultiSpan, Span, DUMMY_SP};
39
40 struct UnusedImport<'a> {
41     use_tree: &'a ast::UseTree,
42     use_tree_id: ast::NodeId,
43     item_span: Span,
44     unused: FxHashSet<ast::NodeId>,
45 }
46
47 impl<'a> UnusedImport<'a> {
48     fn add(&mut self, id: ast::NodeId) {
49         self.unused.insert(id);
50     }
51 }
52
53 struct UnusedImportCheckVisitor<'a, 'b> {
54     r: &'a mut Resolver<'b>,
55     /// All the (so far) unused imports, grouped path list
56     unused_imports: NodeMap<UnusedImport<'a>>,
57     base_use_tree: Option<&'a ast::UseTree>,
58     base_id: ast::NodeId,
59     item_span: Span,
60 }
61
62 impl<'a, 'b> UnusedImportCheckVisitor<'a, 'b> {
63     // We have information about whether `use` (import) items are actually
64     // used now. If an import is not used at all, we signal a lint error.
65     fn check_import(&mut self, id: ast::NodeId) {
66         let used = self.r.used_imports.contains(&id);
67         let def_id = self.r.local_def_id(id);
68         if !used {
69             if self.r.maybe_unused_trait_imports.contains(&def_id) {
70                 // Check later.
71                 return;
72             }
73             self.unused_import(self.base_id).add(id);
74         } else {
75             // This trait import is definitely used, in a way other than
76             // method resolution.
77             self.r.maybe_unused_trait_imports.remove(&def_id);
78             if let Some(i) = self.unused_imports.get_mut(&self.base_id) {
79                 i.unused.remove(&id);
80             }
81         }
82     }
83
84     fn unused_import(&mut self, id: ast::NodeId) -> &mut UnusedImport<'a> {
85         let use_tree_id = self.base_id;
86         let use_tree = self.base_use_tree.unwrap();
87         let item_span = self.item_span;
88
89         self.unused_imports.entry(id).or_insert_with(|| UnusedImport {
90             use_tree,
91             use_tree_id,
92             item_span,
93             unused: FxHashSet::default(),
94         })
95     }
96 }
97
98 impl<'a, 'b> Visitor<'a> for UnusedImportCheckVisitor<'a, 'b> {
99     fn visit_item(&mut self, item: &'a ast::Item) {
100         self.item_span = item.span_with_attributes();
101
102         // Ignore is_public import statements because there's no way to be sure
103         // whether they're used or not. Also ignore imports with a dummy span
104         // because this means that they were generated in some fashion by the
105         // compiler and we don't need to consider them.
106         if let ast::ItemKind::Use(..) = item.kind {
107             if item.vis.kind.is_pub() || item.span.is_dummy() {
108                 return;
109             }
110         }
111
112         visit::walk_item(self, item);
113     }
114
115     fn visit_use_tree(&mut self, use_tree: &'a ast::UseTree, id: ast::NodeId, nested: bool) {
116         // Use the base UseTree's NodeId as the item id
117         // This allows the grouping of all the lints in the same item
118         if !nested {
119             self.base_id = id;
120             self.base_use_tree = Some(use_tree);
121         }
122
123         if let ast::UseTreeKind::Nested(ref items) = use_tree.kind {
124             if items.is_empty() {
125                 self.unused_import(self.base_id).add(id);
126             }
127         } else {
128             self.check_import(id);
129         }
130
131         visit::walk_use_tree(self, use_tree, id);
132     }
133 }
134
135 enum UnusedSpanResult {
136     Used,
137     FlatUnused(Span, Span),
138     NestedFullUnused(Vec<Span>, Span),
139     NestedPartialUnused(Vec<Span>, Vec<Span>),
140 }
141
142 fn calc_unused_spans(
143     unused_import: &UnusedImport<'_>,
144     use_tree: &ast::UseTree,
145     use_tree_id: ast::NodeId,
146 ) -> UnusedSpanResult {
147     // The full span is the whole item's span if this current tree is not nested inside another
148     // This tells rustfix to remove the whole item if all the imports are unused
149     let full_span = if unused_import.use_tree.span == use_tree.span {
150         unused_import.item_span
151     } else {
152         use_tree.span
153     };
154     match use_tree.kind {
155         ast::UseTreeKind::Simple(..) | ast::UseTreeKind::Glob => {
156             if unused_import.unused.contains(&use_tree_id) {
157                 UnusedSpanResult::FlatUnused(use_tree.span, full_span)
158             } else {
159                 UnusedSpanResult::Used
160             }
161         }
162         ast::UseTreeKind::Nested(ref nested) => {
163             if nested.is_empty() {
164                 return UnusedSpanResult::FlatUnused(use_tree.span, full_span);
165             }
166
167             let mut unused_spans = Vec::new();
168             let mut to_remove = Vec::new();
169             let mut all_nested_unused = true;
170             let mut previous_unused = false;
171             for (pos, (use_tree, use_tree_id)) in nested.iter().enumerate() {
172                 let remove = match calc_unused_spans(unused_import, use_tree, *use_tree_id) {
173                     UnusedSpanResult::Used => {
174                         all_nested_unused = false;
175                         None
176                     }
177                     UnusedSpanResult::FlatUnused(span, remove) => {
178                         unused_spans.push(span);
179                         Some(remove)
180                     }
181                     UnusedSpanResult::NestedFullUnused(mut spans, remove) => {
182                         unused_spans.append(&mut spans);
183                         Some(remove)
184                     }
185                     UnusedSpanResult::NestedPartialUnused(mut spans, mut to_remove_extra) => {
186                         all_nested_unused = false;
187                         unused_spans.append(&mut spans);
188                         to_remove.append(&mut to_remove_extra);
189                         None
190                     }
191                 };
192                 if let Some(remove) = remove {
193                     let remove_span = if nested.len() == 1 {
194                         remove
195                     } else if pos == nested.len() - 1 || !all_nested_unused {
196                         // Delete everything from the end of the last import, to delete the
197                         // previous comma
198                         nested[pos - 1].0.span.shrink_to_hi().to(use_tree.span)
199                     } else {
200                         // Delete everything until the next import, to delete the trailing commas
201                         use_tree.span.to(nested[pos + 1].0.span.shrink_to_lo())
202                     };
203
204                     // Try to collapse adjacent spans into a single one. This prevents all cases of
205                     // overlapping removals, which are not supported by rustfix
206                     if previous_unused && !to_remove.is_empty() {
207                         let previous = to_remove.pop().unwrap();
208                         to_remove.push(previous.to(remove_span));
209                     } else {
210                         to_remove.push(remove_span);
211                     }
212                 }
213                 previous_unused = remove.is_some();
214             }
215             if unused_spans.is_empty() {
216                 UnusedSpanResult::Used
217             } else if all_nested_unused {
218                 UnusedSpanResult::NestedFullUnused(unused_spans, full_span)
219             } else {
220                 UnusedSpanResult::NestedPartialUnused(unused_spans, to_remove)
221             }
222         }
223     }
224 }
225
226 impl Resolver<'_> {
227     crate fn check_unused(&mut self, krate: &ast::Crate) {
228         for import in self.potentially_unused_imports.iter() {
229             match import.kind {
230                 _ if import.used.get()
231                     || import.vis.get().is_public()
232                     || import.span.is_dummy() =>
233                 {
234                     if let ImportKind::MacroUse = import.kind {
235                         if !import.span.is_dummy() {
236                             self.lint_buffer.buffer_lint(
237                                 MACRO_USE_EXTERN_CRATE,
238                                 import.id,
239                                 import.span,
240                                 "deprecated `#[macro_use]` attribute used to \
241                                 import macros should be replaced at use sites \
242                                 with a `use` item to import the macro \
243                                 instead",
244                             );
245                         }
246                     }
247                 }
248                 ImportKind::ExternCrate { .. } => {
249                     let def_id = self.local_def_id(import.id);
250                     self.maybe_unused_extern_crates.push((def_id, import.span));
251                 }
252                 ImportKind::MacroUse => {
253                     let msg = "unused `#[macro_use]` import";
254                     self.lint_buffer.buffer_lint(UNUSED_IMPORTS, import.id, import.span, msg);
255                 }
256                 _ => {}
257             }
258         }
259
260         let mut visitor = UnusedImportCheckVisitor {
261             r: self,
262             unused_imports: Default::default(),
263             base_use_tree: None,
264             base_id: ast::DUMMY_NODE_ID,
265             item_span: DUMMY_SP,
266         };
267         visit::walk_crate(&mut visitor, krate);
268
269         for unused in visitor.unused_imports.values() {
270             let mut fixes = Vec::new();
271             let mut spans = match calc_unused_spans(unused, unused.use_tree, unused.use_tree_id) {
272                 UnusedSpanResult::Used => continue,
273                 UnusedSpanResult::FlatUnused(span, remove) => {
274                     fixes.push((remove, String::new()));
275                     vec![span]
276                 }
277                 UnusedSpanResult::NestedFullUnused(spans, remove) => {
278                     fixes.push((remove, String::new()));
279                     spans
280                 }
281                 UnusedSpanResult::NestedPartialUnused(spans, remove) => {
282                     for fix in &remove {
283                         fixes.push((*fix, String::new()));
284                     }
285                     spans
286                 }
287             };
288
289             let len = spans.len();
290             spans.sort();
291             let ms = MultiSpan::from_spans(spans.clone());
292             let mut span_snippets = spans
293                 .iter()
294                 .filter_map(|s| match visitor.r.session.source_map().span_to_snippet(*s) {
295                     Ok(s) => Some(format!("`{}`", s)),
296                     _ => None,
297                 })
298                 .collect::<Vec<String>>();
299             span_snippets.sort();
300             let msg = format!(
301                 "unused import{}{}",
302                 pluralize!(len),
303                 if !span_snippets.is_empty() {
304                     format!(": {}", span_snippets.join(", "))
305                 } else {
306                     String::new()
307                 }
308             );
309
310             let fix_msg = if fixes.len() == 1 && fixes[0].0 == unused.item_span {
311                 "remove the whole `use` item"
312             } else if spans.len() > 1 {
313                 "remove the unused imports"
314             } else {
315                 "remove the unused import"
316             };
317
318             let parent_module = visitor.r.get_nearest_non_block_module(
319                 visitor.r.local_def_id(unused.use_tree_id).to_def_id(),
320             );
321             let test_module_span = match module_to_string(parent_module) {
322                 Some(module)
323                     if module == "test"
324                         || module == "tests"
325                         || module.starts_with("test_")
326                         || module.starts_with("tests_")
327                         || module.ends_with("_test")
328                         || module.ends_with("_tests") =>
329                 {
330                     Some(parent_module.span)
331                 }
332                 _ => None,
333             };
334
335             visitor.r.lint_buffer.buffer_lint_with_diagnostic(
336                 UNUSED_IMPORTS,
337                 unused.use_tree_id,
338                 ms,
339                 &msg,
340                 BuiltinLintDiagnostics::UnusedImports(fix_msg.into(), fixes, test_module_span),
341             );
342         }
343     }
344 }