Skip to content

Add auto-fixable suggestion to remove unused imports #47888

Closed
@killercup

Description

@killercup

Warnings like the following should contain information in their diagnostics output that allows rustfix to remove the unused import.

warning: unused import: `std::io::prelude::*`
  --> src/tiso/tiso_msg.rs:10:5
   |
10 | use std::io::prelude::*;
   |     ^^^^^^^^^^^^^^^^^^^

warning: unused import: `std::fmt`
  --> src/tiso/tiso_msg.rs:13:5
   |
13 | use std::fmt;
   |     ^^^^^^^^

The strategy is to suggest replacing the unused import with an empty string. There are two cases:

  • Are all items in the use statement unused (e.g., std::fs in use std::fs; is unused)? Then remove the whole use statement.
  • Are only some of the items imported by the use statement unused (e.g., File in use std::fs::{File, copy}; is unused)? Remove only these items but keep the use statement.

A quick search found this relevant file in typeck:

impl<'a, 'tcx> CheckVisitor<'a, 'tcx> {
fn check_import(&self, id: ast::NodeId, span: Span) {
let def_id = self.tcx.hir.local_def_id(id);
if !self.tcx.maybe_unused_trait_import(def_id) {
return;
}
let import_def_id = self.tcx.hir.local_def_id(id);
if self.used_trait_imports.contains(&import_def_id) {
return;
}
let msg = if let Ok(snippet) = self.tcx.sess.codemap().span_to_snippet(span) {
format!("unused import: `{}`", snippet)
} else {
"unused import".to_string()
};
self.tcx.lint_node(lint::builtin::UNUSED_IMPORTS, id, span, &msg);
}
}

Originally opened as https://github.com/killercup/rustfix/issues/56.

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsC-enhancementCategory: An issue proposing an enhancement or a PR with one.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions