Skip to content

try $body:block in a macro is not recognized as a try block #112952

Closed

Description

@PatchMixolydic

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:

None

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:?}");
}
"Hello world"

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

Activity

  1. added
    A-macrosArea: All kinds of macros (custom derive, macro_rules!, proc macros, ..)
    F-try_blocks`#![feature(try_blocks)]`
    on Jun 23, 2023
  2. compiler-errors commented on Jun 23, 2023

    @compiler-errors
    Contributor

    We don't support, for example, unsafe $block, so this probably needs to go by T-lang.

  3. added a commit that references this issue on Jul 22, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-macrosArea: All kinds of macros (custom derive, macro_rules!, proc macros, ..)C-bugCategory: This is a bug.F-try_blocks`#![feature(try_blocks)]`

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions