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