rust-lang / rust-lang/rustfmt

rustfmt erroneously removes brackets around statement arg in macro

Open
#5,680 8 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-macros A-matches C-bug
Dominant language
Rust
Stars
7k
Forks
1.1k
Avg merge
2d 13h
Merged PRs (30d)
24

Description

Example code:

macro_rules! unwrap_or {
    ($v:expr, $s:stmt) => {
        match $v {
            Some(v) => v,
            None => { $s },
        }
    };
}

fn main() {
    let _asdf = unwrap_or!(Some(123), return);
}

Compiles fine. Running rustfmt 1.5.2-nightly (1e225413 2023-01-28) removes the braces around $s, as such:

macro_rules! unwrap_or {
    ($v:expr, $s:stmt) => {
        match $v {
            Some(v) => v,
            None => $s,
        }
    };
}

fn main() {
    let _asdf = unwrap_or!(Some(123), return);
}

The code no longer compiles:

   Compiling playground v0.0.1 (/playground)
error: expected expression, found `return;`
  --> src/main.rs:5:21
   |
5  |             None => $s,
   |                  -- ^^ expected expression
   |                  |
   |                  while parsing the `match` arm starting here
...
11 |     let _asdf = unwrap_or!(Some(123), return);
   |                 ----------------------------- in this macro invocation
   |
   = note: this error originates in the macro `unwrap_or` (in Nightly builds, run with -Z macro-backtrace for more info)

error: could not compile `playground` due to previous error

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the provided macro example with rustfmt 1.5.2-nightly and compare the formatted output with the compiler error. Trace the formatter's handling of statement arguments in macro_rules! bodies; done means the braces are preserved and the formatted example still compiles.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.