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