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