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