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