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