Avoid rustfix suggestions for macro-expanded unused imports

This commit is contained in:
cijiugechu
2026-05-15 17:43:09 +08:00
parent 29b7590130
commit ecf01910d5
4 changed files with 55 additions and 6 deletions
+10 -5
View File
@@ -486,6 +486,9 @@ pub(crate) fn check_unused(&mut self, krate: &ast::Crate) {
let remove_whole_use = remove_spans.len() == 1 && remove_spans[0] == unused.item_span;
let num_to_remove = ms.primary_spans().len();
// Only offer rustfix suggestions for spans that point at directly editable code.
let can_suggest_removal =
remove_spans.iter().all(|span| span.can_be_used_for_suggestions());
// If we are in the `--test` mode, suppress a help that adds the `#[cfg(test)]`
// attribute; however, if not, suggest adding the attribute. There is no way to
@@ -516,11 +519,13 @@ pub(crate) fn check_unused(&mut self, krate: &ast::Crate) {
unused.use_tree_id,
ms,
move |dcx, level, sess| {
let sugg = if remove_whole_use {
errors::UnusedImportsSugg::RemoveWholeUse { span: remove_spans[0] }
} else {
errors::UnusedImportsSugg::RemoveImports { remove_spans, num_to_remove }
};
let sugg = can_suggest_removal.then(|| {
if remove_whole_use {
errors::UnusedImportsSugg::RemoveWholeUse { span: remove_spans[0] }
} else {
errors::UnusedImportsSugg::RemoveImports { remove_spans, num_to_remove }
}
});
let test_module_span = test_module_span.map(|span| {
sess.downcast_ref::<rustc_session::Session>()
.expect("expected a `Session`")
+1 -1
View File
@@ -1742,7 +1742,7 @@ pub(crate) struct ElidedLifetimesInPaths {
)]
pub(crate) struct UnusedImports {
#[subdiagnostic]
pub sugg: UnusedImportsSugg,
pub sugg: Option<UnusedImportsSugg>,
#[help("if this is a test module, consider adding a `#[cfg(test)]` to the containing module")]
pub test_module_span: Option<Span>,
@@ -0,0 +1,22 @@
//@ edition:2024
//@ run-rustfix
//@ rustfix-only-machine-applicable
//@ check-pass
mod m {
macro_rules! define_new_macro {
($name:ident) => {
macro_rules! $name {
() => {};
}
pub(crate) use $name;
};
}
define_new_macro!(item_used);
define_new_macro!(item_unused);
}
fn main() {
m::item_used!();
}
@@ -0,0 +1,22 @@
//@ edition:2024
//@ run-rustfix
//@ rustfix-only-machine-applicable
//@ check-pass
mod m {
macro_rules! define_new_macro {
($name:ident) => {
macro_rules! $name {
() => {};
}
pub(crate) use $name;
};
}
define_new_macro!(item_used);
define_new_macro!(item_unused);
}
fn main() {
m::item_used!();
}