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, Macros20NormalizedIdent, 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                        crate::errors::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(&Macros20NormalizedIdent::new(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
232            self.r.lint_buffer.buffer_lint(
233                UNUSED_EXTERN_CRATES,
234                extern_crate.id,
235                extern_crate.span,
236                crate::errors::ExternCrateNotIdiomatic {
237                    span: vis_span.between(ident_span),
238                    code: if vis_span.is_empty() { "use " } else { " use " },
239                },
240            );
241        }
242    }
243}
244
245impl<'a, 'ra, 'tcx> Visitor<'a> for UnusedImportCheckVisitor<'a, 'ra, 'tcx> {
246    fn visit_item(&mut self, item: &'a ast::Item) {
247        self.item_span = item.span_with_attributes();
248        match &item.kind {
249            // Ignore is_public import statements because there's no way to be sure
250            // whether they're used or not. Also ignore imports with a dummy span
251            // because this means that they were generated in some fashion by the
252            // compiler and we don't need to consider them.
253            ast::ItemKind::Use(..) if item.span.is_dummy() => return,
254            // Use the base UseTree's NodeId as the item id
255            // This allows the grouping of all the lints in the same item
256            ast::ItemKind::Use(use_tree) => {
257                self.base_id = item.id;
258                self.base_use_tree = Some(use_tree);
259                self.check_use_tree(use_tree, item.id);
260            }
261            &ast::ItemKind::ExternCrate(orig_name, ident) => {
262                self.extern_crate_items.push(ExternCrateToLint {
263                    id: item.id,
264                    span: item.span,
265                    vis_span: item.vis.span,
266                    span_with_attributes: item.span_with_attributes(),
267                    has_attrs: !item.attrs.is_empty(),
268                    ident,
269                    renames: orig_name.is_some(),
270                });
271            }
272            _ => {}
273        }
274
275        visit::walk_item(self, item);
276    }
277
278    fn visit_nested_use_tree(&mut self, use_tree: &'a ast::UseTree, id: ast::NodeId) {
279        self.check_use_tree(use_tree, id);
280        visit::walk_use_tree(self, use_tree);
281    }
282}
283
284enum UnusedSpanResult {
285    Used,
286    Unused { spans: Vec<Span>, remove: Span },
287    PartialUnused { spans: Vec<Span>, remove: Vec<Span> },
288}
289
290fn calc_unused_spans(
291    unused_import: &UnusedImport,
292    use_tree: &ast::UseTree,
293    use_tree_id: ast::NodeId,
294) -> UnusedSpanResult {
295    // The full span is the whole item's span if this current tree is not nested inside another
296    // This tells rustfix to remove the whole item if all the imports are unused
297    let full_span = if unused_import.use_tree.span == use_tree.span {
298        unused_import.item_span
299    } else {
300        use_tree.span
301    };
302    match use_tree.kind {
303        ast::UseTreeKind::Simple(..) | ast::UseTreeKind::Glob => {
304            if unused_import.unused.contains(&use_tree_id) {
305                UnusedSpanResult::Unused { spans: vec![use_tree.span], remove: full_span }
306            } else {
307                UnusedSpanResult::Used
308            }
309        }
310        ast::UseTreeKind::Nested { items: ref nested, span: tree_span } => {
311            if nested.is_empty() {
312                return UnusedSpanResult::Unused { spans: vec![use_tree.span], remove: full_span };
313            }
314
315            let mut unused_spans = Vec::new();
316            let mut to_remove = Vec::new();
317            let mut used_children = 0;
318            let mut contains_self = false;
319            let mut previous_unused = false;
320            for (pos, (use_tree, use_tree_id)) in nested.iter().enumerate() {
321                let remove = match calc_unused_spans(unused_import, use_tree, *use_tree_id) {
322                    UnusedSpanResult::Used => {
323                        used_children += 1;
324                        None
325                    }
326                    UnusedSpanResult::Unused { mut spans, remove } => {
327                        unused_spans.append(&mut spans);
328                        Some(remove)
329                    }
330                    UnusedSpanResult::PartialUnused { mut spans, remove: mut to_remove_extra } => {
331                        used_children += 1;
332                        unused_spans.append(&mut spans);
333                        to_remove.append(&mut to_remove_extra);
334                        None
335                    }
336                };
337                if let Some(remove) = remove {
338                    let remove_span = if nested.len() == 1 {
339                        remove
340                    } else if pos == nested.len() - 1 || used_children > 0 {
341                        // Delete everything from the end of the last import, to delete the
342                        // previous comma
343                        nested[pos - 1].0.span.shrink_to_hi().to(use_tree.span)
344                    } else {
345                        // Delete everything until the next import, to delete the trailing commas
346                        use_tree.span.to(nested[pos + 1].0.span.shrink_to_lo())
347                    };
348
349                    // Try to collapse adjacent spans into a single one. This prevents all cases of
350                    // overlapping removals, which are not supported by rustfix
351                    if previous_unused && !to_remove.is_empty() {
352                        let previous = to_remove.pop().unwrap();
353                        to_remove.push(previous.to(remove_span));
354                    } else {
355                        to_remove.push(remove_span);
356                    }
357                }
358                contains_self |= use_tree.prefix == kw::SelfLower
359                    && matches!(use_tree.kind, ast::UseTreeKind::Simple(_))
360                    && !unused_import.unused.contains(&use_tree_id);
361                previous_unused = remove.is_some();
362            }
363            if unused_spans.is_empty() {
364                UnusedSpanResult::Used
365            } else if used_children == 0 {
366                UnusedSpanResult::Unused { spans: unused_spans, remove: full_span }
367            } else {
368                // If there is only one remaining child that is used, the braces around the use
369                // tree are not needed anymore. In that case, we determine the span of the left
370                // brace and the right brace, and tell rustfix to remove them as well.
371                //
372                // This means that `use a::{B, C};` will be turned into `use a::B;` rather than
373                // `use a::{B};`, removing a rustfmt roundtrip.
374                //
375                // Note that we cannot remove the braces if the only item inside the use tree is
376                // `self`: `use foo::{self};` is valid Rust syntax, while `use foo::self;` errors
377                // out. We also cannot turn `use foo::{self}` into `use foo`, as the former doesn't
378                // import types with the same name as the module.
379                if used_children == 1 && !contains_self {
380                    // Left brace, from the start of the nested group to the first item.
381                    to_remove.push(
382                        tree_span.shrink_to_lo().to(nested.first().unwrap().0.span.shrink_to_lo()),
383                    );
384                    // Right brace, from the end of the last item to the end of the nested group.
385                    to_remove.push(
386                        nested.last().unwrap().0.span.shrink_to_hi().to(tree_span.shrink_to_hi()),
387                    );
388                }
389
390                UnusedSpanResult::PartialUnused { spans: unused_spans, remove: to_remove }
391            }
392        }
393    }
394}
395
396impl Resolver<'_, '_> {
397    pub(crate) fn check_unused(&mut self, krate: &ast::Crate) {
398        let tcx = self.tcx;
399        let mut maybe_unused_extern_crates = FxHashMap::default();
400
401        for import in self.potentially_unused_imports.iter() {
402            match import.kind {
403                _ if import.vis.is_public()
404                    || import.span.is_dummy()
405                    || self.import_use_map.contains_key(import) =>
406                {
407                    if let ImportKind::MacroUse { .. } = import.kind {
408                        if !import.span.is_dummy() {
409                            self.lint_buffer.buffer_lint(
410                                MACRO_USE_EXTERN_CRATE,
411                                import.root_id,
412                                import.span,
413                                crate::errors::MacroUseDeprecated,
414                            );
415                        }
416                    }
417                }
418                ImportKind::ExternCrate { id, .. } => {
419                    let def_id = self.local_def_id(id);
420                    if self.extern_crate_map.get(&def_id).is_none_or(|&cnum| {
421                        !tcx.is_compiler_builtins(cnum)
422                            && !tcx.is_panic_runtime(cnum)
423                            && !tcx.has_global_allocator(cnum)
424                            && !tcx.has_panic_handler(cnum)
425                    }) {
426                        maybe_unused_extern_crates.insert(id, import.span);
427                    }
428                }
429                ImportKind::MacroUse { .. } => {
430                    self.lint_buffer.buffer_lint(
431                        UNUSED_IMPORTS,
432                        import.root_id,
433                        import.span,
434                        crate::errors::UnusedMacroUse,
435                    );
436                }
437                _ => {}
438            }
439        }
440
441        let mut visitor = UnusedImportCheckVisitor {
442            r: self,
443            unused_imports: Default::default(),
444            extern_crate_items: Default::default(),
445            base_use_tree: None,
446            base_id: ast::DUMMY_NODE_ID,
447            item_span: DUMMY_SP,
448        };
449        visit::walk_crate(&mut visitor, krate);
450
451        visitor.report_unused_extern_crate_items(maybe_unused_extern_crates);
452
453        for unused in visitor.unused_imports.values() {
454            let (spans, remove_spans) =
455                match calc_unused_spans(unused, &unused.use_tree, unused.use_tree_id) {
456                    UnusedSpanResult::Used => continue,
457                    UnusedSpanResult::Unused { spans, remove } => (spans, vec![remove]),
458                    UnusedSpanResult::PartialUnused { spans, remove } => (spans, remove),
459                };
460
461            let ms = MultiSpan::from_spans(spans);
462
463            let mut span_snippets = ms
464                .primary_spans()
465                .iter()
466                .filter_map(|span| tcx.sess.source_map().span_to_snippet(*span).ok())
467                .map(|s| format!("`{s}`"))
468                .collect::<Vec<String>>();
469            span_snippets.sort();
470
471            let remove_whole_use = remove_spans.len() == 1 && remove_spans[0] == unused.item_span;
472            let num_to_remove = ms.primary_spans().len();
473
474            // If we are in the `--test` mode, suppress a help that adds the `#[cfg(test)]`
475            // attribute; however, if not, suggest adding the attribute. There is no way to
476            // retrieve attributes here because we do not have a `TyCtxt` yet.
477            let test_module_span = if tcx.sess.is_test_crate() {
478                None
479            } else {
480                let parent_module = visitor.r.get_nearest_non_block_module(
481                    visitor.r.local_def_id(unused.use_tree_id).to_def_id(),
482                );
483                match module_to_string(parent_module) {
484                    Some(module)
485                        if module == "test"
486                            || module == "tests"
487                            || module.starts_with("test_")
488                            || module.starts_with("tests_")
489                            || module.ends_with("_test")
490                            || module.ends_with("_tests") =>
491                    {
492                        Some(parent_module.span)
493                    }
494                    _ => None,
495                }
496            };
497
498            visitor.r.lint_buffer.buffer_lint(
499                UNUSED_IMPORTS,
500                unused.use_tree_id,
501                ms,
502                BuiltinLintDiag::UnusedImports {
503                    remove_whole_use,
504                    num_to_remove,
505                    remove_spans,
506                    test_module_span,
507                    span_snippets,
508                },
509            );
510        }
511
512        let unused_imports = visitor.unused_imports;
513        let mut check_redundant_imports = FxIndexSet::default();
514        for module in &self.local_modules {
515            for (_key, resolution) in self.resolutions(*module).borrow().iter() {
516                if let Some(binding) = resolution.borrow().best_binding()
517                    && let NameBindingKind::Import { import, .. } = binding.kind
518                    && let ImportKind::Single { id, .. } = import.kind
519                {
520                    if let Some(unused_import) = unused_imports.get(&import.root_id)
521                        && unused_import.unused.contains(&id)
522                    {
523                        continue;
524                    }
525
526                    check_redundant_imports.insert(import);
527                }
528            }
529        }
530
531        let mut redundant_imports = UnordSet::default();
532        for import in check_redundant_imports {
533            if self.check_for_redundant_imports(import)
534                && let Some(id) = import.id()
535            {
536                redundant_imports.insert(id);
537            }
538        }
539
540        // The lint fixes for unused_import and unnecessary_qualification may conflict.
541        // Deleting both unused imports and unnecessary segments of an item may result
542        // in the item not being found.
543        for unn_qua in &self.potentially_unnecessary_qualifications {
544            if let LexicalScopeBinding::Item(name_binding) = unn_qua.binding
545                && let NameBindingKind::Import { import, .. } = name_binding.kind
546                && (is_unused_import(import, &unused_imports)
547                    || is_redundant_import(import, &redundant_imports))
548            {
549                continue;
550            }
551
552            self.lint_buffer.buffer_lint(
553                UNUSED_QUALIFICATIONS,
554                unn_qua.node_id,
555                unn_qua.path_span,
556                BuiltinLintDiag::UnusedQualifications { removal_span: unn_qua.removal_span },
557            );
558        }
559
560        fn is_redundant_import(
561            import: Import<'_>,
562            redundant_imports: &UnordSet<ast::NodeId>,
563        ) -> bool {
564            if let Some(id) = import.id()
565                && redundant_imports.contains(&id)
566            {
567                return true;
568            }
569            false
570        }
571
572        fn is_unused_import(
573            import: Import<'_>,
574            unused_imports: &FxIndexMap<ast::NodeId, UnusedImport>,
575        ) -> bool {
576            if let Some(unused_import) = unused_imports.get(&import.root_id)
577                && let Some(id) = import.id()
578                && unused_import.unused.contains(&id)
579            {
580                return true;
581            }
582            false
583        }
584    }
585}