Skip to main content

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