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