From 550e3087d1b521f2b3b669ebaaf6d16e4c593fca Mon Sep 17 00:00:00 2001 From: Mu42 Date: Fri, 17 Mar 2023 14:36:22 +0800 Subject: [PATCH] Suggest surrounding the macro with `{}` to interpret as a statement --- compiler/rustc_expand/src/mbe/diagnostics.rs | 24 +++++++++++++++----- tests/ui/macros/issue-109237.rs | 7 ++++++ tests/ui/macros/issue-109237.stderr | 18 +++++++++++++++ 3 files changed, 43 insertions(+), 6 deletions(-) create mode 100644 tests/ui/macros/issue-109237.rs create mode 100644 tests/ui/macros/issue-109237.stderr diff --git a/compiler/rustc_expand/src/mbe/diagnostics.rs b/compiler/rustc_expand/src/mbe/diagnostics.rs index b1d9cea2773..6bc393c6534 100644 --- a/compiler/rustc_expand/src/mbe/diagnostics.rs +++ b/compiler/rustc_expand/src/mbe/diagnostics.rs @@ -245,12 +245,24 @@ pub(super) fn emit_frag_parse_err( e.note( "the macro call doesn't expand to an expression, but it can expand to a statement", ); - e.span_suggestion_verbose( - site_span.shrink_to_hi(), - "add `;` to interpret the expansion as a statement", - ";", - Applicability::MaybeIncorrect, - ); + + if parser.token == token::Semi { + if let Ok(snippet) = parser.sess.source_map().span_to_snippet(site_span) { + e.span_suggestion_verbose( + site_span, + "surround the macro invocation with `{}` to interpret the expansion as a statement", + format!("{{ {}; }}", snippet), + Applicability::MaybeIncorrect, + ); + } + } else { + e.span_suggestion_verbose( + site_span.shrink_to_hi(), + "add `;` to interpret the expansion as a statement", + ";", + Applicability::MaybeIncorrect, + ); + } } }, _ => annotate_err_with_kind(&mut e, kind, site_span), diff --git a/tests/ui/macros/issue-109237.rs b/tests/ui/macros/issue-109237.rs new file mode 100644 index 00000000000..86a193c9e44 --- /dev/null +++ b/tests/ui/macros/issue-109237.rs @@ -0,0 +1,7 @@ +macro_rules! statement { + () => {;}; //~ ERROR expected expression +} + +fn main() { + let _ = statement!(); +} diff --git a/tests/ui/macros/issue-109237.stderr b/tests/ui/macros/issue-109237.stderr new file mode 100644 index 00000000000..d125cff63ea --- /dev/null +++ b/tests/ui/macros/issue-109237.stderr @@ -0,0 +1,18 @@ +error: expected expression, found `;` + --> $DIR/issue-109237.rs:2:12 + | +LL | () => {;}; + | ^ expected expression +... +LL | let _ = statement!(); + | ------------ in this macro invocation + | + = note: the macro call doesn't expand to an expression, but it can expand to a statement + = note: this error originates in the macro `statement` (in Nightly builds, run with -Z macro-backtrace for more info) +help: surround the macro invocation with `{}` to interpret the expansion as a statement + | +LL | let _ = { statement!(); }; + | ~~~~~~~~~~~~~~~~~ + +error: aborting due to previous error +