rustc_resolve/
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 rustc_hir_analysis/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_unused` finally emits the diagnostics based on the data generated
24//    in the last step
25
26use rustc_ast as ast;
27use rustc_ast::visit::{self, Visitor};
28use rustc_data_structures::fx::{FxHashMap, FxIndexMap, FxIndexSet};
29use rustc_data_structures::unord::UnordSet;
30use rustc_errors::MultiSpan;
31use rustc_hir::def::{DefKind, Res};
32use rustc_session::lint::BuiltinLintDiag;
33use rustc_session::lint::builtin::{
34    MACRO_USE_EXTERN_CRATE, UNUSED_EXTERN_CRATES, UNUSED_IMPORTS, UNUSED_QUALIFICATIONS,
35};
36use rustc_span::{DUMMY_SP, Ident, Span, kw};
37
38use crate::imports::{Import, ImportKind};
39use crate::{LexicalScopeBinding, NameBindingKind, Resolver, module_to_string};
40
41struct UnusedImport {
42    use_tree: ast::UseTree,
43    use_tree_id: ast::NodeId,
44    item_span: Span,
45    unused: UnordSet<ast::NodeId>,
46}
47
48impl UnusedImport {
49    fn add(&mut self, id: ast::NodeId) {
50        self.unused.insert(id);
51    }
52}
53
54struct UnusedImportCheckVisitor<'a, 'ra, 'tcx> {
55    r: &'a mut Resolver<'ra, 'tcx>,
56    /// All the (so far) unused imports, grouped path list
57    unused_imports: FxIndexMap<ast::NodeId, UnusedImport>,
58    extern_crate_items: Vec<ExternCrateToLint>,
59    base_use_tree: Option<&'a ast::UseTree>,
60    base_id: ast::NodeId,
61    item_span: Span,
62}
63
64struct ExternCrateToLint {
65    id: ast::NodeId,
66    /// Span from the item
67    span: Span,
68    /// Span to use to suggest complete removal.
69    span_with_attributes: Span,
70    /// Span of the visibility, if any.
71    vis_span: Span,
72    /// Whether the item has attrs.
73    has_attrs: bool,
74    /// Name used to refer to the crate.
75    ident: Ident,
76    /// Whether the statement renames the crate `extern crate orig_name as new_name;`.
77    renames: bool,
78}
79
80impl<'a, 'ra, 'tcx> UnusedImportCheckVisitor<'a, 'ra, 'tcx> {
81    // We have information about whether `use` (import) items are actually
82    // used now. If an import is not used at all, we signal a lint error.
83    fn check_import(&mut self, id: ast::NodeId) {
84        let used = self.r.used_imports.contains(&id);
85        let def_id = self.r.local_def_id(id);
86        if !used {
87            if self.r.maybe_unused_trait_imports.contains(&def_id) {
88                // Check later.
89                return;
90            }
91            self.unused_import(self.base_id).add(id);
92        } else {
93            // This trait import is definitely used, in a way other than
94            // method resolution.
95            // FIXME(#120456) - is `swap_remove` correct?
96            self.r.maybe_unused_trait_imports.swap_remove(&def_id);
97            if let Some(i) = self.unused_imports.get_mut(&self.base_id) {
98                i.unused.remove(&id);
99            }
100        }
101    }
102
103    fn unused_import(&mut self, id: ast::NodeId) -> &mut UnusedImport {
104        let use_tree_id = self.base_id;
105        let use_tree = self.base_use_tree.unwrap().clone();
106        let item_span = self.item_span;
107
108        self.unused_imports.entry(id).or_insert_with(|| UnusedImport {
109            use_tree,
110            use_tree_id,
111            item_span,
112            unused: Default::default(),
113        })
114    }
115
116    fn check_import_as_underscore(&mut self, item: &ast::UseTree, id: ast::NodeId) {
117        match item.kind {
118            ast::UseTreeKind::Simple(Some(ident)) => {
119                if ident.name == kw::Underscore
120                    && !self.r.import_res_map.get(&id).is_some_and(|per_ns| {
121                        matches!(
122                            per_ns.type_ns,
123                            Some(Res::Def(DefKind::Trait | DefKind::TraitAlias, _))
124                        )
125                    })
126                {
127                    self.unused_import(self.base_id).add(id);
128                }
129            }
130            ast::UseTreeKind::Nested { ref items, .. } => self.check_imports_as_underscore(items),
131            _ => {}
132        }
133    }
134
135    fn check_imports_as_underscore(&mut self, items: &[(ast::UseTree, ast::NodeId)]) {
136        for (item, id) in items {
137            self.check_import_as_underscore(item, *id);
138        }
139    }
140
141    fn report_unused_extern_crate_items(
142        &mut self,
143        maybe_unused_extern_crates: FxHashMap<ast::NodeId, Span>,
144    ) {
145        let tcx = self.r.tcx();
146        for extern_crate in &self.extern_crate_items {
147            let warn_if_unused = !extern_crate.ident.name.as_str().starts_with('_');
148
149            // If the crate is fully unused, we suggest removing it altogether.
150            // We do this in any edition.
151            if warn_if_unused {
152                if let Some(&span) = maybe_unused_extern_crates.get(&extern_crate.id) {
153                    self.r.lint_buffer.buffer_lint(
154                        UNUSED_EXTERN_CRATES,
155                        extern_crate.id,
156                        span,
157                        BuiltinLintDiag::UnusedExternCrate {
158                            span: extern_crate.span,
159                            removal_span: extern_crate.span_with_attributes,
160                        },
161                    );
162                    continue;
163                }
164            }
165
166            // If we are not in Rust 2018 edition, then we don't make any further
167            // suggestions.
168            if !tcx.sess.at_least_rust_2018() {
169                continue;
170            }
171
172            // If the extern crate has any attributes, they may have funky
173            // semantics we can't faithfully represent using `use` (most
174            // notably `#[macro_use]`). Ignore it.
175            if extern_crate.has_attrs {
176                continue;
177            }
178
179            // If the extern crate is renamed, then we cannot suggest replacing it with a use as this
180            // would not insert the new name into the prelude, where other imports in the crate may be
181            // expecting it.
182            if extern_crate.renames {
183                continue;
184            }
185
186            // If the extern crate isn't in the extern prelude,
187            // there is no way it can be written as a `use`.
188            if self
189                .r
190                .extern_prelude
191                .get(&extern_crate.ident)
192                .is_none_or(|entry| entry.introduced_by_item)
193            {
194                continue;
195            }
196
197            let module = self
198                .r
199                .get_nearest_non_block_module(self.r.local_def_id(extern_crate.id).to_def_id());
200            if module.no_implicit_prelude {
201                // If the module has `no_implicit_prelude`, then we don't suggest
202                // replacing the extern crate with a use, as it would not be
203                // inserted into the prelude. User writes `extern` style deliberately.
204                continue;
205            }
206
207            let vis_span = extern_crate
208                .vis_span
209                .find_ancestor_inside(extern_crate.span)
210                .unwrap_or(extern_crate.vis_span);
211            let ident_span = extern_crate
212                .ident
213                .span
214                .find_ancestor_inside(extern_crate.span)
215                .unwrap_or(extern_crate.ident.span);
216            self.r.lint_buffer.buffer_lint(
217                UNUSED_EXTERN_CRATES,
218                extern_crate.id,
219                extern_crate.span,
220                BuiltinLintDiag::ExternCrateNotIdiomatic { vis_span, ident_span },
221            );
222        }
223    }
224}
225
226impl<'a, 'ra, 'tcx> Visitor<'a> for UnusedImportCheckVisitor<'a, 'ra, 'tcx> {
227    fn visit_item(&mut self, item: &'a ast::Item) {
228        match item.kind {
229            // Ignore is_public import statements because there's no way to be sure
230            // whether they're used or not. Also ignore imports with a dummy span
231            // because this means that they were generated in some fashion by the
232            // compiler and we don't need to consider them.
233            ast::ItemKind::Use(..) if item.span.is_dummy() => return,
234            ast::ItemKind::ExternCrate(orig_name, ident) => {
235                self.extern_crate_items.push(ExternCrateToLint {
236                    id: item.id,
237                    span: item.span,
238                    vis_span: item.vis.span,
239                    span_with_attributes: item.span_with_attributes(),
240                    has_attrs: !item.attrs.is_empty(),
241                    ident,
242                    renames: orig_name.is_some(),
243                });
244            }
245            _ => {}
246        }
247
248        self.item_span = item.span_with_attributes();
249        visit::walk_item(self, item);
250    }
251
252    fn visit_use_tree(&mut self, use_tree: &'a ast::UseTree, id: ast::NodeId, nested: bool) {
253        // Use the base UseTree's NodeId as the item id
254        // This allows the grouping of all the lints in the same item
255        if !nested {
256            self.base_id = id;
257            self.base_use_tree = Some(use_tree);
258        }
259
260        if self.r.effective_visibilities.is_exported(self.r.local_def_id(id)) {
261            self.check_import_as_underscore(use_tree, id);
262            return;
263        }
264
265        if let ast::UseTreeKind::Nested { ref items, .. } = use_tree.kind {
266            if items.is_empty() {
267                self.unused_import(self.base_id).add(id);
268            }
269        } else {
270            self.check_import(id);
271        }
272
273        visit::walk_use_tree(self, use_tree, id);
274    }
275}
276
277enum UnusedSpanResult {
278    Used,
279    Unused { spans: Vec<Span>, remove: Span },
280    PartialUnused { spans: Vec<Span>, remove: Vec<Span> },
281}
282
283fn calc_unused_spans(
284    unused_import: &UnusedImport,
285    use_tree: &ast::UseTree,
286    use_tree_id: ast::NodeId,
287) -> UnusedSpanResult {
288    // The full span is the whole item's span if this current tree is not nested inside another
289    // This tells rustfix to remove the whole item if all the imports are unused
290    let full_span = if unused_import.use_tree.span == use_tree.span {
291        unused_import.item_span
292    } else {
293        use_tree.span
294    };
295    match use_tree.kind {
296        ast::UseTreeKind::Simple(..) | ast::UseTreeKind::Glob => {
297            if unused_import.unused.contains(&use_tree_id) {
298                UnusedSpanResult::Unused { spans: vec![use_tree.span], remove: full_span }
299            } else {
300                UnusedSpanResult::Used
301            }
302        }
303        ast::UseTreeKind::Nested { items: ref nested, span: tree_span } => {
304            if nested.is_empty() {
305                return UnusedSpanResult::Unused { spans: vec![use_tree.span], remove: full_span };
306            }
307
308            let mut unused_spans = Vec::new();
309            let mut to_remove = Vec::new();
310            let mut used_children = 0;
311            let mut contains_self = false;
312            let mut previous_unused = false;
313            for (pos, (use_tree, use_tree_id)) in nested.iter().enumerate() {
314                let remove = match calc_unused_spans(unused_import, use_tree, *use_tree_id) {
315                    UnusedSpanResult::Used => {
316                        used_children += 1;
317                        None
318                    }
319                    UnusedSpanResult::Unused { mut spans, remove } => {
320                        unused_spans.append(&mut spans);
321                        Some(remove)
322                    }
323                    UnusedSpanResult::PartialUnused { mut spans, remove: mut to_remove_extra } => {
324                        used_children += 1;
325                        unused_spans.append(&mut spans);
326                        to_remove.append(&mut to_remove_extra);
327                        None
328                    }
329                };
330                if let Some(remove) = remove {
331                    let remove_span = if nested.len() == 1 {
332                        remove
333                    } else if pos == nested.len() - 1 || used_children > 0 {
334                        // Delete everything from the end of the last import, to delete the
335                        // previous comma
336                        nested[pos - 1].0.span.shrink_to_hi().to(use_tree.span)
337                    } else {
338                        // Delete everything until the next import, to delete the trailing commas
339                        use_tree.span.to(nested[pos + 1].0.span.shrink_to_lo())
340                    };
341
342                    // Try to collapse adjacent spans into a single one. This prevents all cases of
343                    // overlapping removals, which are not supported by rustfix
344                    if previous_unused && !to_remove.is_empty() {
345                        let previous = to_remove.pop().unwrap();
346                        to_remove.push(previous.to(remove_span));
347                    } else {
348                        to_remove.push(remove_span);
349                    }
350                }
351                contains_self |= use_tree.prefix == kw::SelfLower
352                    && matches!(use_tree.kind, ast::UseTreeKind::Simple(_))
353                    && !unused_import.unused.contains(&use_tree_id);
354                previous_unused = remove.is_some();
355            }
356            if unused_spans.is_empty() {
357                UnusedSpanResult::Used
358            } else if used_children == 0 {
359                UnusedSpanResult::Unused { spans: unused_spans, remove: full_span }
360            } else {
361                // If there is only one remaining child that is used, the braces around the use
362                // tree are not needed anymore. In that case, we determine the span of the left
363                // brace and the right brace, and tell rustfix to remove them as well.
364                //
365                // This means that `use a::{B, C};` will be turned into `use a::B;` rather than
366                // `use a::{B};`, removing a rustfmt roundtrip.
367                //
368                // Note that we cannot remove the braces if the only item inside the use tree is
369                // `self`: `use foo::{self};` is valid Rust syntax, while `use foo::self;` errors
370                // out. We also cannot turn `use foo::{self}` into `use foo`, as the former doesn't
371                // import types with the same name as the module.
372                if used_children == 1 && !contains_self {
373                    // Left brace, from the start of the nested group to the first item.
374                    to_remove.push(
375                        tree_span.shrink_to_lo().to(nested.first().unwrap().0.span.shrink_to_lo()),
376                    );
377                    // Right brace, from the end of the last item to the end of the nested group.
378                    to_remove.push(
379                        nested.last().unwrap().0.span.shrink_to_hi().to(tree_span.shrink_to_hi()),
380                    );
381                }
382
383                UnusedSpanResult::PartialUnused { spans: unused_spans, remove: to_remove }
384            }
385        }
386    }
387}
388
389impl Resolver<'_, '_> {
390    pub(crate) fn check_unused(&mut self, krate: &ast::Crate) {
391        let tcx = self.tcx;
392        let mut maybe_unused_extern_crates = FxHashMap::default();
393
394        for import in self.potentially_unused_imports.iter() {
395            match import.kind {
396                _ if import.vis.is_public()
397                    || import.span.is_dummy()
398                    || self.import_use_map.contains_key(import) =>
399                {
400                    if let ImportKind::MacroUse { .. } = import.kind {
401                        if !import.span.is_dummy() {
402                            self.lint_buffer.buffer_lint(
403                                MACRO_USE_EXTERN_CRATE,
404                                import.root_id,
405                                import.span,
406                                BuiltinLintDiag::MacroUseDeprecated,
407                            );
408                        }
409                    }
410                }
411                ImportKind::ExternCrate { id, .. } => {
412                    let def_id = self.local_def_id(id);
413                    if self.extern_crate_map.get(&def_id).is_none_or(|&cnum| {
414                        !tcx.is_compiler_builtins(cnum)
415                            && !tcx.is_panic_runtime(cnum)
416                            && !tcx.has_global_allocator(cnum)
417                            && !tcx.has_panic_handler(cnum)
418                    }) {
419                        maybe_unused_extern_crates.insert(id, import.span);
420                    }
421                }
422                ImportKind::MacroUse { .. } => {
423                    self.lint_buffer.buffer_lint(
424                        UNUSED_IMPORTS,
425                        import.root_id,
426                        import.span,
427                        BuiltinLintDiag::UnusedMacroUse,
428                    );
429                }
430                _ => {}
431            }
432        }
433
434        let mut visitor = UnusedImportCheckVisitor {
435            r: self,
436            unused_imports: Default::default(),
437            extern_crate_items: Default::default(),
438            base_use_tree: None,
439            base_id: ast::DUMMY_NODE_ID,
440            item_span: DUMMY_SP,
441        };
442        visit::walk_crate(&mut visitor, krate);
443
444        visitor.report_unused_extern_crate_items(maybe_unused_extern_crates);
445
446        for unused in visitor.unused_imports.values() {
447            let (spans, remove_spans) =
448                match calc_unused_spans(unused, &unused.use_tree, unused.use_tree_id) {
449                    UnusedSpanResult::Used => continue,
450                    UnusedSpanResult::Unused { spans, remove } => (spans, vec![remove]),
451                    UnusedSpanResult::PartialUnused { spans, remove } => (spans, remove),
452                };
453
454            let ms = MultiSpan::from_spans(spans);
455
456            let mut span_snippets = ms
457                .primary_spans()
458                .iter()
459                .filter_map(|span| tcx.sess.source_map().span_to_snippet(*span).ok())
460                .map(|s| format!("`{s}`"))
461                .collect::<Vec<String>>();
462            span_snippets.sort();
463
464            let remove_whole_use = remove_spans.len() == 1 && remove_spans[0] == unused.item_span;
465            let num_to_remove = ms.primary_spans().len();
466
467            // If we are in the `--test` mode, suppress a help that adds the `#[cfg(test)]`
468            // attribute; however, if not, suggest adding the attribute. There is no way to
469            // retrieve attributes here because we do not have a `TyCtxt` yet.
470            let test_module_span = if tcx.sess.is_test_crate() {
471                None
472            } else {
473                let parent_module = visitor.r.get_nearest_non_block_module(
474                    visitor.r.local_def_id(unused.use_tree_id).to_def_id(),
475                );
476                match module_to_string(parent_module) {
477                    Some(module)
478                        if module == "test"
479                            || module == "tests"
480                            || module.starts_with("test_")
481                            || module.starts_with("tests_")
482                            || module.ends_with("_test")
483                            || module.ends_with("_tests") =>
484                    {
485                        Some(parent_module.span)
486                    }
487                    _ => None,
488                }
489            };
490
491            visitor.r.lint_buffer.buffer_lint(
492                UNUSED_IMPORTS,
493                unused.use_tree_id,
494                ms,
495                BuiltinLintDiag::UnusedImports {
496                    remove_whole_use,
497                    num_to_remove,
498                    remove_spans,
499                    test_module_span,
500                    span_snippets,
501                },
502            );
503        }
504
505        let unused_imports = visitor.unused_imports;
506        let mut check_redundant_imports = FxIndexSet::default();
507        for module in self.arenas.local_modules().iter() {
508            for (_key, resolution) in self.resolutions(*module).borrow().iter() {
509                let resolution = resolution.borrow();
510
511                if let Some(binding) = resolution.binding
512                    && let NameBindingKind::Import { import, .. } = binding.kind
513                    && let ImportKind::Single { id, .. } = import.kind
514                {
515                    if let Some(unused_import) = unused_imports.get(&import.root_id)
516                        && unused_import.unused.contains(&id)
517                    {
518                        continue;
519                    }
520
521                    check_redundant_imports.insert(import);
522                }
523            }
524        }
525
526        let mut redundant_imports = UnordSet::default();
527        for import in check_redundant_imports {
528            if self.check_for_redundant_imports(import)
529                && let Some(id) = import.id()
530            {
531                redundant_imports.insert(id);
532            }
533        }
534
535        // The lint fixes for unused_import and unnecessary_qualification may conflict.
536        // Deleting both unused imports and unnecessary segments of an item may result
537        // in the item not being found.
538        for unn_qua in &self.potentially_unnecessary_qualifications {
539            if let LexicalScopeBinding::Item(name_binding) = unn_qua.binding
540                && let NameBindingKind::Import { import, .. } = name_binding.kind
541                && (is_unused_import(import, &unused_imports)
542                    || is_redundant_import(import, &redundant_imports))
543            {
544                continue;
545            }
546
547            self.lint_buffer.buffer_lint(
548                UNUSED_QUALIFICATIONS,
549                unn_qua.node_id,
550                unn_qua.path_span,
551                BuiltinLintDiag::UnusedQualifications { removal_span: unn_qua.removal_span },
552            );
553        }
554
555        fn is_redundant_import(
556            import: Import<'_>,
557            redundant_imports: &UnordSet<ast::NodeId>,
558        ) -> bool {
559            if let Some(id) = import.id()
560                && redundant_imports.contains(&id)
561            {
562                return true;
563            }
564            false
565        }
566
567        fn is_unused_import(
568            import: Import<'_>,
569            unused_imports: &FxIndexMap<ast::NodeId, UnusedImport>,
570        ) -> bool {
571            if let Some(unused_import) = unused_imports.get(&import.root_id)
572                && let Some(id) = import.id()
573                && unused_import.unused.contains(&id)
574            {
575                return true;
576            }
577            false
578        }
579    }
580}