try $body:block in a macro is not recognized as a try block · Issue #112952 · rust-lang/rust (original) (raw)

I tried this code:

#![feature(try_blocks)]

macro_rules! create_try { ($body:block) => { try $body }; }

fn main() { let x: Option<&str> = create_try! {{ None?; "Hello world" }};

println!("{x:?}");

}

I expected to see this happen:

Instead, this happened:

error: expected expression, found reserved keyword `try`
  --> src/main.rs:6:9
   |
6  |           try $body
   |           ^^^ expected expression
...
11 |       let x: Option<&str> = create_try! {{
   |  ___________________________-
12 | |         None?;
13 | |         "Hello world"
14 | |     }};
   | |______- in this macro invocation
   |
   = note: this error originates in the macro `create_try` (in Nightly builds, run with -Z macro-backtrace for more info)

Note that this works fine for similar expressions, such as if expressions:

macro_rules! create_if { ($body:block) => { if true $body else { unreachable!(); } }; }

fn main() { let x: &str = create_if! {{ "Hello world" }};

println!("{x:?}");

}

Meta

rustc --version --verbose:

rustc 1.71.0-nightly (9d871b061 2023-05-21)
binary: rustc
commit-hash: 9d871b0617a4b3d6610b7cee0ab5310dcb542c62
commit-date: 2023-05-21
host: x86_64-unknown-linux-gnu
release: 1.71.0-nightly
LLVM version: 16.0.4

Also reproduces on nightly 1.72.0-nightly (2023-06-21 065a1f5df9c2f1d93269) (tested on the playground)

@rustbot modify labels +A-macros +F-try_blocks