Skip to content

Commit 550e308

Browse files
committed
Suggest surrounding the macro with {} to interpret as a statement
1 parent 511364e commit 550e308

File tree

3 files changed

+43
-6
lines changed

3 files changed

+43
-6
lines changed

compiler/rustc_expand/src/mbe/diagnostics.rs

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -245,12 +245,24 @@ pub(super) fn emit_frag_parse_err(
245245
e.note(
246246
"the macro call doesn't expand to an expression, but it can expand to a statement",
247247
);
248-
e.span_suggestion_verbose(
249-
site_span.shrink_to_hi(),
250-
"add `;` to interpret the expansion as a statement",
251-
";",
252-
Applicability::MaybeIncorrect,
253-
);
248+
249+
if parser.token == token::Semi {
250+
if let Ok(snippet) = parser.sess.source_map().span_to_snippet(site_span) {
251+
e.span_suggestion_verbose(
252+
site_span,
253+
"surround the macro invocation with `{}` to interpret the expansion as a statement",
254+
format!("{{ {}; }}", snippet),
255+
Applicability::MaybeIncorrect,
256+
);
257+
}
258+
} else {
259+
e.span_suggestion_verbose(
260+
site_span.shrink_to_hi(),
261+
"add `;` to interpret the expansion as a statement",
262+
";",
263+
Applicability::MaybeIncorrect,
264+
);
265+
}
254266
}
255267
},
256268
_ => annotate_err_with_kind(&mut e, kind, site_span),

tests/ui/macros/issue-109237.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
macro_rules! statement {
2+
() => {;}; //~ ERROR expected expression
3+
}
4+
5+
fn main() {
6+
let _ = statement!();
7+
}

tests/ui/macros/issue-109237.stderr

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
error: expected expression, found `;`
2+
--> $DIR/issue-109237.rs:2:12
3+
|
4+
LL | () => {;};
5+
| ^ expected expression
6+
...
7+
LL | let _ = statement!();
8+
| ------------ in this macro invocation
9+
|
10+
= note: the macro call doesn't expand to an expression, but it can expand to a statement
11+
= note: this error originates in the macro `statement` (in Nightly builds, run with -Z macro-backtrace for more info)
12+
help: surround the macro invocation with `{}` to interpret the expansion as a statement
13+
|
14+
LL | let _ = { statement!(); };
15+
| ~~~~~~~~~~~~~~~~~
16+
17+
error: aborting due to previous error
18+

0 commit comments

Comments
 (0)