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(_))
341                    && !unused_import.unused.contains(&use_tree_id);
342                previous_unused = remove.is_some();
343            }
344            if unused_spans.is_empty() {
345                UnusedSpanResult::Used
346            } else if used_children == 0 {
347                UnusedSpanResult::Unused { spans: unused_spans, remove: full_span }
348            } else {
349                // If there is only one remaining child that is used, the braces around the use
350                // tree are not needed anymore. In that case, we determine the span of the left
351                // brace and the right brace, and tell rustfix to remove them as well.
352                //
353                // This means that `use a::{B, C};` will be turned into `use a::B;` rather than
354                // `use a::{B};`, removing a rustfmt roundtrip.
355                //
356                // Note that we cannot remove the braces if the only item inside the use tree is
357                // `self`: `use foo::{self};` is valid Rust syntax, while `use foo::self;` errors
358                // out. We also cannot turn `use foo::{self}` into `use foo`, as the former doesn't
359                // import types with the same name as the module.
360                if used_children == 1 && !contains_self {
361                    // Left brace, from the start of the nested group to the first item.
362                    to_remove.push(
363                        tree_span.shrink_to_lo().to(nested.first().unwrap().0.span.shrink_to_lo()),
364                    );
365                    // Right brace, from the end of the last item to the end of the nested group.
366                    to_remove.push(
367                        nested.last().unwrap().0.span.shrink_to_hi().to(tree_span.shrink_to_hi()),
368                    );
369                }
370
371                UnusedSpanResult::PartialUnused { spans: unused_spans, remove: to_remove }
372            }
373        }
374    }
375}
376
377impl Resolver<'_, '_> {
378    pub(crate) fn check_unused(&mut self, krate: &ast::Crate) {
379        let tcx = self.tcx;
380        let mut maybe_unused_extern_crates = FxHashMap::default();
381
382        for import in self.potentially_unused_imports.iter() {
383            match import.kind {
384                _ if import.vis.is_public()
385                    || import.span.is_dummy()
386                    || self.import_use_map.contains_key(import) =>
387                {
388                    if let ImportKind::MacroUse { .. } = import.kind {
389                        if !import.span.is_dummy() {
390                            self.lint_buffer.buffer_lint(
391                                MACRO_USE_EXTERN_CRATE,
392                                import.root_id,
393                                import.span,
394                                BuiltinLintDiag::MacroUseDeprecated,
395                            );
396                        }
397                    }
398                }
399                ImportKind::ExternCrate { id, .. } => {
400                    let def_id = self.local_def_id(id);
401                    if self.extern_crate_map.get(&def_id).is_none_or(|&cnum| {
402                        !tcx.is_compiler_builtins(cnum)
403                            && !tcx.is_panic_runtime(cnum)
404                            && !tcx.has_global_allocator(cnum)
405                            && !tcx.has_panic_handler(cnum)
406                    }) {
407                        maybe_unused_extern_crates.insert(id, import.span);
408                    }
409                }
410                ImportKind::MacroUse { .. } => {
411                    self.lint_buffer.buffer_lint(
412                        UNUSED_IMPORTS,
413                        import.root_id,
414                        import.span,
415                        BuiltinLintDiag::UnusedMacroUse,
416                    );
417                }
418                _ => {}
419            }
420        }
421
422        let mut visitor = UnusedImportCheckVisitor {
423            r: self,
424            unused_imports: Default::default(),
425            extern_crate_items: Default::default(),
426            base_use_tree: None,
427            base_id: ast::DUMMY_NODE_ID,
428            item_span: DUMMY_SP,
429        };
430        visit::walk_crate(&mut visitor, krate);
431
432        visitor.report_unused_extern_crate_items(maybe_unused_extern_crates);
433
434        for unused in visitor.unused_imports.values() {
435            let (spans, remove_spans) =
436                match calc_unused_spans(unused, &unused.use_tree, unused.use_tree_id) {
437                    UnusedSpanResult::Used => continue,
438                    UnusedSpanResult::Unused { spans, remove } => (spans, vec![remove]),
439                    UnusedSpanResult::PartialUnused { spans, remove } => (spans, remove),
440                };
441
442            let ms = MultiSpan::from_spans(spans);
443
444            let mut span_snippets = ms
445                .primary_spans()
446                .iter()
447                .filter_map(|span| tcx.sess.source_map().span_to_snippet(*span).ok())
448                .map(|s| format!("`{s}`"))
449                .collect::<Vec<String>>();
450            span_snippets.sort();
451
452            let remove_whole_use = remove_spans.len() == 1 && remove_spans[0] == unused.item_span;
453            let num_to_remove = ms.primary_spans().len();
454
455            // If we are in the `--test` mode, suppress a help that adds the `#[cfg(test)]`
456            // attribute; however, if not, suggest adding the attribute. There is no way to
457            // retrieve attributes here because we do not have a `TyCtxt` yet.
458            let test_module_span = if tcx.sess.is_test_crate() {
459                None
460            } else {
461                let parent_module = visitor.r.get_nearest_non_block_module(
462                    visitor.r.local_def_id(unused.use_tree_id).to_def_id(),
463                );
464                match module_to_string(parent_module) {
465                    Some(module)
466                        if module == "test"
467                            || module == "tests"
468                            || module.starts_with("test_")
469                            || module.starts_with("tests_")
470                            || module.ends_with("_test")
471                            || module.ends_with("_tests") =>
472                    {
473                        Some(parent_module.span)
474                    }
475                    _ => None,
476                }
477            };
478
479            visitor.r.lint_buffer.buffer_lint(
480                UNUSED_IMPORTS,
481                unused.use_tree_id,
482                ms,
483                BuiltinLintDiag::UnusedImports {
484                    remove_whole_use,
485                    num_to_remove,
486                    remove_spans,
487                    test_module_span,
488                    span_snippets,
489                },
490            );
491        }
492
493        let unused_imports = visitor.unused_imports;
494        let mut check_redundant_imports = FxIndexSet::default();
495        for module in self.arenas.local_modules().iter() {
496            for (_key, resolution) in self.resolutions(*module).borrow().iter() {
497                let resolution = resolution.borrow();
498
499                if let Some(binding) = resolution.binding
500                    && let NameBindingKind::Import { import, .. } = binding.kind
501                    && let ImportKind::Single { id, .. } = import.kind
502                {
503                    if let Some(unused_import) = unused_imports.get(&import.root_id)
504                        && unused_import.unused.contains(&id)
505                    {
506                        continue;
507                    }
508
509                    check_redundant_imports.insert(import);
510                }
511            }
512        }
513
514        let mut redundant_imports = UnordSet::default();
515        for import in check_redundant_imports {
516            if self.check_for_redundant_imports(import)
517                && let Some(id) = import.id()
518            {
519                redundant_imports.insert(id);
520            }
521        }
522
523        // The lint fixes for unused_import and unnecessary_qualification may conflict.
524        // Deleting both unused imports and unnecessary segments of an item may result
525        // in the item not being found.
526        for unn_qua in &self.potentially_unnecessary_qualifications {
527            if let LexicalScopeBinding::Item(name_binding) = unn_qua.binding
528                && let NameBindingKind::Import { import, .. } = name_binding.kind
529                && (is_unused_import(import, &unused_imports)
530                    || is_redundant_import(import, &redundant_imports))
531            {
532                continue;
533            }
534
535            self.lint_buffer.buffer_lint(
536                UNUSED_QUALIFICATIONS,
537                unn_qua.node_id,
538                unn_qua.path_span,
539                BuiltinLintDiag::UnusedQualifications { removal_span: unn_qua.removal_span },
540            );
541        }
542
543        fn is_redundant_import(
544            import: Import<'_>,
545            redundant_imports: &UnordSet<ast::NodeId>,
546        ) -> bool {
547            if let Some(id) = import.id()
548                && redundant_imports.contains(&id)
549            {
550                return true;
551            }
552            false
553        }
554
555        fn is_unused_import(
556            import: Import<'_>,
557            unused_imports: &FxIndexMap<ast::NodeId, UnusedImport>,
558        ) -> bool {
559            if let Some(unused_import) = unused_imports.get(&import.root_id)
560                && let Some(id) = import.id()
561                && unused_import.unused.contains(&id)
562            {
563                return true;
564            }
565            false
566        }
567    }
568}