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` visits the `use` items collected during late
14//    resolution to find all the unused imports inside of `UseTree`s, recording
15//    their `NodeId`s and grouping them by 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_lint_defs::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, with_owner};
42
43struct UnusedImport {
44    use_tree: ast::UseTree,
45    use_tree_id: ast::NodeId,
46    item_span: Span,
47    unused: UnordSet<ast::NodeId>,
48    use_tree_def_id: LocalDefId,
49}
50
51impl UnusedImport {
52    fn add(&mut self, id: ast::NodeId) {
53        self.unused.insert(id);
54    }
55}
56
57struct UnusedImportCheckVisitor<'a, 'ra, 'tcx> {
58    r: &'a mut Resolver<'ra, 'tcx>,
59    /// All the (so far) unused imports, grouped path list
60    unused_imports: FxIndexMap<ast::NodeId, UnusedImport>,
61    extern_crate_items: Vec<ExternCrateToLint>,
62    base_use_tree: Option<&'a ast::UseTree>,
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().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.r.current_owner.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, def_id: LocalDefId) {
105        if self.r.effective_visibilities.is_exported(def_id) {
106            self.check_import_as_underscore(use_tree, id);
107            self.r.maybe_unused_trait_imports.swap_remove(&def_id);
108            return;
109        }
110
111        if let ast::UseTreeKind::Nested { ref items, .. } = use_tree.kind {
112            if items.is_empty() {
113                self.unused_import().add(id);
114            }
115        } else {
116            self.check_import(id, def_id);
117        }
118    }
119
120    fn unused_import(&mut self) -> &mut UnusedImport {
121        let use_tree_id = self.r.current_owner.id;
122        let use_tree = self.base_use_tree.unwrap().clone();
123        let item_span = self.item_span;
124
125        self.unused_imports.entry(use_tree_id).or_insert_with(|| UnusedImport {
126            use_tree,
127            use_tree_id,
128            item_span,
129            unused: Default::default(),
130            use_tree_def_id: self.r.current_owner.def_id,
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.current_owner.import_res.get(&id).and_then(|res|
            res.type_ns) {
    Some(Res::Def(DefKind::Trait | DefKind::TraitAlias, _)) => true,
    _ => false,
}matches!(
139                        self.r.current_owner.import_res.get(&id).and_then(|res| res.type_ns),
140                        Some(Res::Def(DefKind::Trait | DefKind::TraitAlias, _))
141                    )
142                {
143                    self.unused_import().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::UseTreeAndId]) {
152        for use_tree in items {
153            self.check_import_as_underscore(&use_tree.inner, use_tree.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> AsMut<Resolver<'ra, 'tcx>> for UnusedImportCheckVisitor<'a, 'ra, 'tcx> {
247    fn as_mut(&mut self) -> &mut Resolver<'ra, 'tcx> {
248        self.r
249    }
250}
251
252impl<'a, 'ra, 'tcx> Visitor<'a> for UnusedImportCheckVisitor<'a, 'ra, 'tcx> {
253    fn visit_item(&mut self, item: &'a ast::Item) {
254        self.item_span = item.span_with_attributes();
255        match &item.kind {
256            // Ignore imports with a dummy span because this means that they
257            // were generated in some fashion by the compiler and we don't need
258            // to consider them.
259            ast::ItemKind::Use(..) if item.span.is_dummy() => return,
260            // Use the base UseTree's NodeId as the item id
261            // This allows the grouping of all the lints in the same item
262            ast::ItemKind::Use(use_tree) => {
263                self.base_use_tree = Some(use_tree);
264                self.check_use_tree(use_tree, item.id, self.r.current_owner.def_id);
265            }
266            &ast::ItemKind::ExternCrate(orig_name, ident) => {
267                self.extern_crate_items.push(ExternCrateToLint {
268                    id: item.id,
269                    span: item.span,
270                    vis_span: item.vis.span,
271                    span_with_attributes: item.span_with_attributes(),
272                    has_attrs: !item.attrs.is_empty(),
273                    ident,
274                    renames: orig_name.is_some(),
275                });
276            }
277            _ => {}
278        }
279
280        visit::walk_item(self, item);
281    }
282
283    fn visit_use_tree_and_id(&mut self, tree: &'a ast::UseTreeAndId) {
284        self.check_use_tree(&tree.inner, tree.id, self.r.local_def_id(tree.id));
285        visit::walk_use_tree_and_id(self, tree);
286    }
287}
288
289enum UnusedSpanResult {
290    Used,
291    Unused { spans: Vec<Span>, remove: Span },
292    PartialUnused { spans: Vec<Span>, remove: Vec<Span> },
293}
294
295fn calc_unused_spans(
296    unused_import: &UnusedImport,
297    use_tree: &ast::UseTree,
298    use_tree_id: ast::NodeId,
299) -> UnusedSpanResult {
300    // The full span is the whole item's span if this current tree is not nested inside another
301    // This tells rustfix to remove the whole item if all the imports are unused
302    let full_span = if unused_import.use_tree.span() == use_tree.span() {
303        unused_import.item_span
304    } else {
305        use_tree.span()
306    };
307    match use_tree.kind {
308        ast::UseTreeKind::Simple(..) | ast::UseTreeKind::Glob(_) => {
309            if unused_import.unused.contains(&use_tree_id) {
310                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 }
311            } else {
312                UnusedSpanResult::Used
313            }
314        }
315        ast::UseTreeKind::Nested { items: ref nested, span: tree_span } => {
316            if nested.is_empty() {
317                return UnusedSpanResult::Unused {
318                    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()],
319                    remove: full_span,
320                };
321            }
322
323            let mut unused_spans = Vec::new();
324            let mut to_remove = Vec::new();
325            let mut used_children = 0;
326            let mut contains_self = false;
327            let mut previous_unused = false;
328            for (pos, use_tree) in nested.iter().enumerate() {
329                let remove = match calc_unused_spans(unused_import, &use_tree.inner, use_tree.id) {
330                    UnusedSpanResult::Used => {
331                        used_children += 1;
332                        None
333                    }
334                    UnusedSpanResult::Unused { mut spans, remove } => {
335                        unused_spans.append(&mut spans);
336                        Some(remove)
337                    }
338                    UnusedSpanResult::PartialUnused { mut spans, remove: mut to_remove_extra } => {
339                        used_children += 1;
340                        unused_spans.append(&mut spans);
341                        to_remove.append(&mut to_remove_extra);
342                        None
343                    }
344                };
345                if let Some(remove) = remove {
346                    let remove_span = if nested.len() == 1 {
347                        remove
348                    } else if pos == nested.len() - 1 || used_children > 0 {
349                        // Delete everything from the end of the last import, to delete the
350                        // previous comma
351                        nested[pos - 1].inner.hi_span().shrink_to_hi().to(use_tree.inner.hi_span())
352                    } else {
353                        // Delete everything until the next import, to delete the trailing commas
354                        let inner = &nested[pos + 1].inner;
355                        use_tree.inner.prefix.span.to(inner.prefix.span.shrink_to_lo())
356                    };
357
358                    // Try to collapse adjacent spans into a single one. This prevents all cases of
359                    // overlapping removals, which are not supported by rustfix
360                    if previous_unused && !to_remove.is_empty() {
361                        let previous = to_remove.pop().unwrap();
362                        to_remove.push(previous.to(remove_span));
363                    } else {
364                        to_remove.push(remove_span);
365                    }
366                }
367                contains_self |= use_tree.inner.prefix == kw::SelfLower
368                    && #[allow(non_exhaustive_omitted_patterns)] match use_tree.inner.kind {
    ast::UseTreeKind::Simple(_) => true,
    _ => false,
}matches!(use_tree.inner.kind, ast::UseTreeKind::Simple(_))
369                    && !unused_import.unused.contains(&use_tree.id);
370                previous_unused = remove.is_some();
371            }
372            if unused_spans.is_empty() {
373                UnusedSpanResult::Used
374            } else if used_children == 0 {
375                UnusedSpanResult::Unused { spans: unused_spans, remove: full_span }
376            } else {
377                // If there is only one remaining child that is used, the braces around the use
378                // tree are not needed anymore. In that case, we determine the span of the left
379                // brace and the right brace, and tell rustfix to remove them as well.
380                //
381                // This means that `use a::{B, C};` will be turned into `use a::B;` rather than
382                // `use a::{B};`, removing a rustfmt roundtrip.
383                //
384                // Note that we cannot remove the braces if the only item inside the use tree is
385                // `self`: `use foo::{self};` is valid Rust syntax, while `use foo::self;` errors
386                // out. We also cannot turn `use foo::{self}` into `use foo`, as the former doesn't
387                // import types with the same name as the module.
388                if used_children == 1 && !contains_self {
389                    // Left brace, from the start of the nested group to the first item.
390                    to_remove.push(
391                        tree_span.shrink_to_lo().to(nested
392                            .first()
393                            .unwrap()
394                            .inner
395                            .prefix
396                            .span
397                            .shrink_to_lo()),
398                    );
399                    // Right brace, from the end of the last item to the end of the nested group.
400                    to_remove.push(
401                        nested
402                            .last()
403                            .unwrap()
404                            .inner
405                            .hi_span()
406                            .shrink_to_hi()
407                            .to(tree_span.shrink_to_hi()),
408                    );
409                }
410
411                UnusedSpanResult::PartialUnused { spans: unused_spans, remove: to_remove }
412            }
413        }
414    }
415}
416
417impl Resolver<'_, '_> {
418    pub(crate) fn check_unused(&mut self, use_items: Vec<&ast::Item>) {
419        let tcx = self.tcx;
420        let mut maybe_unused_extern_crates = FxHashMap::default();
421
422        for import in self.potentially_unused_imports.iter() {
423            match import.kind {
424                _ if import.vis.is_public()
425                    || import.span.is_dummy()
426                    || self.import_use_map.contains_key(import) =>
427                {
428                    if let ImportKind::MacroUse { .. } = import.kind {
429                        if !import.span.is_dummy() {
430                            self.lint_buffer.buffer_lint(
431                                MACRO_USE_EXTERN_CRATE,
432                                import.root_id,
433                                import.span,
434                                crate::diagnostics::MacroUseDeprecated,
435                            );
436                        }
437                    }
438                }
439                ImportKind::ExternCrate { id, def_id, .. } => {
440                    if self.extern_crate_map.get(&def_id).is_none_or(|&cnum| {
441                        !tcx.is_compiler_builtins(cnum)
442                            && !tcx.is_panic_runtime(cnum)
443                            && !tcx.has_global_allocator(cnum)
444                            && !tcx.has_panic_handler(cnum)
445                            && tcx
446                                .externally_implementable_items(cnum)
447                                .values()
448                                .all(|(_, defs)| defs.is_empty())
449                    }) {
450                        maybe_unused_extern_crates.insert(id, import.span);
451                    }
452                }
453                ImportKind::MacroUse { .. } => {
454                    self.lint_buffer.buffer_lint(
455                        UNUSED_IMPORTS,
456                        import.root_id,
457                        import.span,
458                        crate::diagnostics::UnusedMacroUse,
459                    );
460                }
461                _ => {}
462            }
463        }
464
465        let mut visitor = UnusedImportCheckVisitor {
466            r: self,
467            unused_imports: Default::default(),
468            extern_crate_items: Default::default(),
469            base_use_tree: None,
470            item_span: DUMMY_SP,
471        };
472        // `use_items` is in crate DFS order, so diagnostics and side effects are unchanged.
473        for item in use_items {
474            with_owner(&mut visitor, item.id, |visitor| visitor.visit_item(item))
475        }
476
477        visitor.report_unused_extern_crate_items(maybe_unused_extern_crates);
478
479        for unused in visitor.unused_imports.values() {
480            let (spans, remove_spans) =
481                match calc_unused_spans(unused, &unused.use_tree, unused.use_tree_id) {
482                    UnusedSpanResult::Used => continue,
483                    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]),
484                    UnusedSpanResult::PartialUnused { spans, remove } => (spans, remove),
485                };
486
487            let ms = MultiSpan::from_spans(spans);
488
489            let mut span_snippets = ms
490                .primary_spans()
491                .iter()
492                .filter_map(|span| tcx.sess.source_map().span_to_snippet(*span).ok())
493                .map(|s| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", s))
    })format!("`{s}`"))
494                .collect::<Vec<String>>();
495            span_snippets.sort();
496
497            let remove_whole_use = remove_spans.len() == 1 && remove_spans[0] == unused.item_span;
498            let num_to_remove = ms.primary_spans().len();
499            // Only offer rustfix suggestions for spans that point at directly editable code.
500            let can_suggest_removal =
501                remove_spans.iter().all(|span| span.can_be_used_for_suggestions());
502
503            // If we are in the `--test` mode, suppress a help that adds the `#[cfg(test)]`
504            // attribute; however, if not, suggest adding the attribute. There is no way to
505            // retrieve attributes here because we do not have a `TyCtxt` yet.
506            let test_module_span = if tcx.sess.is_test_crate() {
507                None
508            } else {
509                let parent_module =
510                    visitor.r.get_nearest_non_block_module(unused.use_tree_def_id.to_def_id());
511                match module_to_string(parent_module) {
512                    Some(module)
513                        if module == "test"
514                            || module == "tests"
515                            || module.starts_with("test_")
516                            || module.starts_with("tests_")
517                            || module.ends_with("_test")
518                            || module.ends_with("_tests") =>
519                    {
520                        Some(parent_module.span)
521                    }
522                    _ => None,
523                }
524            };
525
526            visitor.r.lint_buffer.dyn_buffer_lint_any(
527                UNUSED_IMPORTS,
528                unused.use_tree_id,
529                ms,
530                move |dcx, level, sess| {
531                    let sugg = can_suggest_removal.then(|| {
532                        if remove_whole_use {
533                            diagnostics::UnusedImportsSugg::RemoveWholeUse { span: remove_spans[0] }
534                        } else {
535                            diagnostics::UnusedImportsSugg::RemoveImports {
536                                remove_spans,
537                                num_to_remove,
538                            }
539                        }
540                    });
541                    let test_module_span = test_module_span.map(|span| {
542                        sess.downcast_ref::<rustc_session::Session>()
543                            .expect("expected a `Session`")
544                            .source_map()
545                            .guess_head_span(span)
546                    });
547
548                    diagnostics::UnusedImports {
549                        sugg,
550                        test_module_span,
551                        num_snippets: span_snippets.len(),
552                        span_snippets: DiagArgValue::StrListSepByAnd(
553                            span_snippets.into_iter().map(Cow::Owned).collect(),
554                        ),
555                    }
556                    .into_diag(dcx, level)
557                },
558            );
559        }
560
561        let unused_imports = visitor.unused_imports;
562        let mut check_redundant_imports = FxIndexSet::default();
563        for module in &self.local_modules {
564            for (_key, resolution) in self.resolutions(module.to_module()).iter() {
565                if let Some(decl) = resolution.borrow_checked(self).best_decl()
566                    && let DeclKind::Import { import, .. } = decl.kind
567                    && let ImportKind::Single { id, .. } = import.kind
568                {
569                    if let Some(unused_import) = unused_imports.get(&import.root_id)
570                        && unused_import.unused.contains(&id)
571                    {
572                        continue;
573                    }
574
575                    check_redundant_imports.insert(import);
576                }
577            }
578        }
579
580        let mut redundant_imports = UnordSet::default();
581        for import in check_redundant_imports {
582            if self.check_for_redundant_imports(import)
583                && let Some(id) = import.id()
584            {
585                redundant_imports.insert(id);
586            }
587        }
588
589        // The lint fixes for unused_import and unnecessary_qualification may conflict.
590        // Deleting both unused imports and unnecessary segments of an item may result
591        // in the item not being found.
592        for unn_qua in &self.potentially_unnecessary_qualifications {
593            if let LateDecl::Decl(decl) = unn_qua.decl
594                && let DeclKind::Import { import, .. } = decl.kind
595                && (is_unused_import(import, &unused_imports)
596                    || is_redundant_import(import, &redundant_imports))
597            {
598                continue;
599            }
600
601            self.lint_buffer.buffer_lint(
602                UNUSED_QUALIFICATIONS,
603                unn_qua.node_id,
604                unn_qua.path_span,
605                diagnostics::UnusedQualifications { removal_span: unn_qua.removal_span },
606            );
607        }
608
609        fn is_redundant_import(
610            import: Import<'_>,
611            redundant_imports: &UnordSet<ast::NodeId>,
612        ) -> bool {
613            if let Some(id) = import.id()
614                && redundant_imports.contains(&id)
615            {
616                return true;
617            }
618            false
619        }
620
621        fn is_unused_import(
622            import: Import<'_>,
623            unused_imports: &FxIndexMap<ast::NodeId, UnusedImport>,
624        ) -> bool {
625            if let Some(unused_import) = unused_imports.get(&import.root_id)
626                && let Some(id) = import.id()
627                && unused_import.unused.contains(&id)
628            {
629                return true;
630            }
631            false
632        }
633    }
634}