Rollup merge of #151283 - chenyukang:yukang-fix-macro-unused, r=petrochenkov

Suggest ignore returning value inside macro for unused_must_use lint

Fixes rust-lang/rust#151269

The first commit fix the original issue,
the second commit is a code refactoring in this lint.
This commit is contained in:
Jonathan Brouwer 2026-01-29 17:47:30 +01:00 committed by GitHub
commit adcdb6c2c3
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 50 additions and 5 deletions

View file

@ -539,10 +539,19 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults {
);
}
MustUsePath::Def(span, def_id, reason) => {
let span = span.find_ancestor_not_from_macro().unwrap_or(*span);
let ancenstor_span = span.find_ancestor_not_from_macro().unwrap_or(*span);
let is_redundant_let_ignore = cx
.sess()
.source_map()
.span_to_prev_source(ancenstor_span)
.ok()
.map(|prev| prev.trim_end().ends_with("let _ ="))
.unwrap_or(false);
let suggestion_span =
if is_redundant_let_ignore { *span } else { ancenstor_span };
cx.emit_span_lint(
UNUSED_MUST_USE,
span,
ancenstor_span,
UnusedDef {
pre: descr_pre,
post: descr_post,
@ -551,11 +560,13 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults {
note: *reason,
suggestion: (!is_inner).then_some(if expr_is_from_block {
UnusedDefSuggestion::BlockTailExpr {
before_span: span.shrink_to_lo(),
after_span: span.shrink_to_hi(),
before_span: suggestion_span.shrink_to_lo(),
after_span: suggestion_span.shrink_to_hi(),
}
} else {
UnusedDefSuggestion::NormalExpr { span: span.shrink_to_lo() }
UnusedDefSuggestion::NormalExpr {
span: suggestion_span.shrink_to_lo(),
}
}),
},
);

View file

@ -0,0 +1,15 @@
#![deny(unused_must_use)]
fn error() -> Result<(), ()> {
Err(())
}
macro_rules! foo {
() => {{
error();
}};
}
fn main() {
let _ = foo!(); //~ ERROR unused `Result` that must be used
}

View file

@ -0,0 +1,19 @@
error: unused `Result` that must be used
--> $DIR/lint-unsed-in-macro-issue-151269.rs:14:13
|
LL | let _ = foo!();
| ^^^^^^
|
= note: this `Result` may be an `Err` variant, which should be handled
note: the lint level is defined here
--> $DIR/lint-unsed-in-macro-issue-151269.rs:1:9
|
LL | #![deny(unused_must_use)]
| ^^^^^^^^^^^^^^^
help: use `let _ = ...` to ignore the resulting value
|
LL | let _ = error();
| +++++++
error: aborting due to 1 previous error