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_session::lint::builtin::{
35    MACRO_USE_EXTERN_CRATE, UNUSED_EXTERN_CRATES, UNUSED_IMPORTS, UNUSED_QUALIFICATIONS,
36};
37use rustc_span::{DUMMY_SP, Ident, Span, kw};
38
39use crate::imports::{Import, ImportKind};
40use crate::{DeclKind, IdentKey, LateDecl, Resolver, errors, module_to_string};
41
42struct UnusedImport {
43    use_tree: ast::UseTree,
44    use_tree_id: ast::NodeId,
45    item_span: Span,
46    unused: UnordSet<ast::NodeId>,
47}
48
49impl UnusedImport {
50    fn add(&mut self, id: ast::NodeId) {
51        self.unused.insert(id);
52    }
53}
54
55struct UnusedImportCheckVisitor<'a, 'ra, 'tcx> {
56    r: &'a mut Resolver<'ra, 'tcx>,
57    /// All the (so far) unused imports, grouped path list
58    unused_imports: FxIndexMap<ast::NodeId, UnusedImport>,
59    extern_crate_items: Vec<ExternCrateToLint>,
60    base_use_tree: Option<&'a ast::UseTree>,
61    base_id: ast::NodeId,
62    item_span: Span,
63}
64
65struct ExternCrateToLint {
66    id: ast::NodeId,
67    /// Span from the item
68    span: Span,
69    /// Span to use to suggest complete removal.
70    span_with_attributes: Span,
71    /// Span of the visibility, if any.
72    vis_span: Span,
73    /// Whether the item has attrs.
74    has_attrs: bool,
75    /// Name used to refer to the crate.
76    ident: Ident,
77    /// Whether the statement renames the crate `extern crate orig_name as new_name;`.
78    renames: bool,
79}
80
81impl<'a, 'ra, 'tcx> UnusedImportCheckVisitor<'a, 'ra, 'tcx> {
82    // We have information about whether `use` (import) items are actually
83    // used now. If an import is not used at all, we signal a lint error.
84    fn check_import(&mut self, id: ast::NodeId) {
85        let used = self.r.used_imports.contains(&id);
86        let def_id = self.r.local_def_id(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        if self.r.effective_visibilities.is_exported(self.r.local_def_id(id)) {
106            self.check_import_as_underscore(use_tree, id);
107            return;
108        }
109
110        if let ast::UseTreeKind::Nested { ref items, .. } = use_tree.kind {
111            if items.is_empty() {
112                self.unused_import(self.base_id).add(id);
113            }
114        } else {
115            self.check_import(id);
116        }
117    }
118
119    fn unused_import(&mut self, id: ast::NodeId) -> &mut UnusedImport {
120        let use_tree_id = self.base_id;
121        let use_tree = self.base_use_tree.unwrap().clone();
122        let item_span = self.item_span;
123
124        self.unused_imports.entry(id).or_insert_with(|| UnusedImport {
125            use_tree,
126            use_tree_id,
127            item_span,
128            unused: Default::default(),
129        })
130    }
131
132    fn check_import_as_underscore(&mut self, item: &ast::UseTree, id: ast::NodeId) {
133        match item.kind {
134            ast::UseTreeKind::Simple(Some(ident)) => {
135                if ident.name == kw::Underscore
136                    && !self.r.import_res_map.get(&id).is_some_and(|per_ns| {
137                        #[allow(non_exhaustive_omitted_patterns)] match per_ns.type_ns {
    Some(Res::Def(DefKind::Trait | DefKind::TraitAlias, _)) => true,
    _ => false,
}matches!(
138                            per_ns.type_ns,
139                            Some(Res::Def(DefKind::Trait | DefKind::TraitAlias, _))
140                        )
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::errors::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.local_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::errors::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::errors::MacroUseDeprecated,
430                            );
431                        }
432                    }
433                }
434                ImportKind::ExternCrate { id, .. } => {
435                    let def_id = self.local_def_id(id);
436                    if self.extern_crate_map.get(&def_id).is_none_or(|&cnum| {
437                        !tcx.is_compiler_builtins(cnum)
438                            && !tcx.is_panic_runtime(cnum)
439                            && !tcx.has_global_allocator(cnum)
440                            && !tcx.has_panic_handler(cnum)
441                            && tcx.externally_implementable_items(cnum).is_empty()
442                    }) {
443                        maybe_unused_extern_crates.insert(id, import.span);
444                    }
445                }
446                ImportKind::MacroUse { .. } => {
447                    self.lint_buffer.buffer_lint(
448                        UNUSED_IMPORTS,
449                        import.root_id,
450                        import.span,
451                        crate::errors::UnusedMacroUse,
452                    );
453                }
454                _ => {}
455            }
456        }
457
458        let mut visitor = UnusedImportCheckVisitor {
459            r: self,
460            unused_imports: Default::default(),
461            extern_crate_items: Default::default(),
462            base_use_tree: None,
463            base_id: ast::DUMMY_NODE_ID,
464            item_span: DUMMY_SP,
465        };
466        visit::walk_crate(&mut visitor, krate);
467
468        visitor.report_unused_extern_crate_items(maybe_unused_extern_crates);
469
470        for unused in visitor.unused_imports.values() {
471            let (spans, remove_spans) =
472                match calc_unused_spans(unused, &unused.use_tree, unused.use_tree_id) {
473                    UnusedSpanResult::Used => continue,
474                    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]),
475                    UnusedSpanResult::PartialUnused { spans, remove } => (spans, remove),
476                };
477
478            let ms = MultiSpan::from_spans(spans);
479
480            let mut span_snippets = ms
481                .primary_spans()
482                .iter()
483                .filter_map(|span| tcx.sess.source_map().span_to_snippet(*span).ok())
484                .map(|s| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", s))
    })format!("`{s}`"))
485                .collect::<Vec<String>>();
486            span_snippets.sort();
487
488            let remove_whole_use = remove_spans.len() == 1 && remove_spans[0] == unused.item_span;
489            let num_to_remove = ms.primary_spans().len();
490
491            // If we are in the `--test` mode, suppress a help that adds the `#[cfg(test)]`
492            // attribute; however, if not, suggest adding the attribute. There is no way to
493            // retrieve attributes here because we do not have a `TyCtxt` yet.
494            let test_module_span = if tcx.sess.is_test_crate() {
495                None
496            } else {
497                let parent_module = visitor.r.get_nearest_non_block_module(
498                    visitor.r.local_def_id(unused.use_tree_id).to_def_id(),
499                );
500                match module_to_string(parent_module) {
501                    Some(module)
502                        if module == "test"
503                            || module == "tests"
504                            || module.starts_with("test_")
505                            || module.starts_with("tests_")
506                            || module.ends_with("_test")
507                            || module.ends_with("_tests") =>
508                    {
509                        Some(parent_module.span)
510                    }
511                    _ => None,
512                }
513            };
514
515            visitor.r.lint_buffer.dyn_buffer_lint_any(
516                UNUSED_IMPORTS,
517                unused.use_tree_id,
518                ms,
519                move |dcx, level, sess| {
520                    let sugg = if remove_whole_use {
521                        errors::UnusedImportsSugg::RemoveWholeUse { span: remove_spans[0] }
522                    } else {
523                        errors::UnusedImportsSugg::RemoveImports { remove_spans, num_to_remove }
524                    };
525                    let test_module_span = test_module_span.map(|span| {
526                        sess.downcast_ref::<rustc_session::Session>()
527                            .expect("expected a `Session`")
528                            .source_map()
529                            .guess_head_span(span)
530                    });
531
532                    errors::UnusedImports {
533                        sugg,
534                        test_module_span,
535                        num_snippets: span_snippets.len(),
536                        span_snippets: DiagArgValue::StrListSepByAnd(
537                            span_snippets.into_iter().map(Cow::Owned).collect(),
538                        ),
539                    }
540                    .into_diag(dcx, level)
541                },
542            );
543        }
544
545        let unused_imports = visitor.unused_imports;
546        let mut check_redundant_imports = FxIndexSet::default();
547        for module in &self.local_modules {
548            for (_key, resolution) in self.resolutions(module.to_module()).borrow().iter() {
549                if let Some(decl) = resolution.borrow().best_decl()
550                    && let DeclKind::Import { import, .. } = decl.kind
551                    && let ImportKind::Single { id, .. } = import.kind
552                {
553                    if let Some(unused_import) = unused_imports.get(&import.root_id)
554                        && unused_import.unused.contains(&id)
555                    {
556                        continue;
557                    }
558
559                    check_redundant_imports.insert(import);
560                }
561            }
562        }
563
564        let mut redundant_imports = UnordSet::default();
565        for import in check_redundant_imports {
566            if self.check_for_redundant_imports(import)
567                && let Some(id) = import.id()
568            {
569                redundant_imports.insert(id);
570            }
571        }
572
573        // The lint fixes for unused_import and unnecessary_qualification may conflict.
574        // Deleting both unused imports and unnecessary segments of an item may result
575        // in the item not being found.
576        for unn_qua in &self.potentially_unnecessary_qualifications {
577            if let LateDecl::Decl(decl) = unn_qua.decl
578                && let DeclKind::Import { import, .. } = decl.kind
579                && (is_unused_import(import, &unused_imports)
580                    || is_redundant_import(import, &redundant_imports))
581            {
582                continue;
583            }
584
585            self.lint_buffer.buffer_lint(
586                UNUSED_QUALIFICATIONS,
587                unn_qua.node_id,
588                unn_qua.path_span,
589                errors::UnusedQualifications { removal_span: unn_qua.removal_span },
590            );
591        }
592
593        fn is_redundant_import(
594            import: Import<'_>,
595            redundant_imports: &UnordSet<ast::NodeId>,
596        ) -> bool {
597            if let Some(id) = import.id()
598                && redundant_imports.contains(&id)
599            {
600                return true;
601            }
602            false
603        }
604
605        fn is_unused_import(
606            import: Import<'_>,
607            unused_imports: &FxIndexMap<ast::NodeId, UnusedImport>,
608        ) -> bool {
609            if let Some(unused_import) = unused_imports.get(&import.root_id)
610                && let Some(id) = import.id()
611                && unused_import.unused.contains(&id)
612            {
613                return true;
614            }
615            false
616        }
617    }
618}