Skip to content

Commit 6f33a8f

Browse files
committed
Do not suggest compatible variants inside macro
Signed-off-by: xizheyin <[email protected]>
1 parent d61b8bd commit 6f33a8f

File tree

2 files changed

+13
-4
lines changed

2 files changed

+13
-4
lines changed

compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2409,16 +2409,21 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
24092409
let (open, close) = match ctor_kind {
24102410
Some(CtorKind::Fn) => ("(".to_owned(), ")"),
24112411
None => (format!(" {{ {field_name}: "), " }"),
2412-
24132412
Some(CtorKind::Const) => unreachable!("unit variants don't have fields"),
24142413
};
24152414

2416-
// Suggest constructor as deep into the block tree as possible.
2417-
// This fixes https://github.com/rust-lang/rust/issues/101065,
2418-
// and also just helps make the most minimal suggestions.
2415+
// Find the deepest expression in the block tree while staying within the same
2416+
// context. This ensures that suggestions point to user-visible code
2417+
// rather than macro-expanded internal code.
2418+
//
2419+
// For example, with `println!("A")`, we want to suggest wrapping the entire
2420+
// `println!("A")` call, not some internal macro-generated code.
2421+
// See #101065, #142359
24192422
let mut expr = expr;
24202423
while let hir::ExprKind::Block(block, _) = &expr.kind
24212424
&& let Some(expr_) = &block.expr
2425+
// Only traverse blocks in same context
2426+
&& expr_.span.eq_ctxt(expr.span)
24222427
{
24232428
expr = expr_
24242429
}

tests/ui/typeck/suggestions/suggest-compatible-variants-macro-issue-142359.stderr

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,10 @@ LL | | };
1313
= note: expected enum `ControlFlow<i32, _>`
1414
found unit type `()`
1515
= note: this error originates in the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
16+
help: try wrapping the expression in `std::ops::ControlFlow::Continue`
17+
|
18+
LL | Ok(r) => std::ops::ControlFlow::Continue({ println!("A")})
19+
| ++++++++++++++++++++++++++++++++ +
1620

1721
error: aborting due to 1 previous error
1822

0 commit comments

Comments
 (0)