Skip to content

Macro with format literal doesn't find captured identifier in scope #94674

@malaire

Description

@malaire

I tried this code:

macro_rules! foo {
    ($format:literal) => {{
        let bar = 42;
        format!($format)
    }};
}

fn main() {
    assert_eq!(foo!("{bar}"), "42");
}

I expected to see this happen:
Code should succeed because macro is given a literal format and so variable bar should be found in the scope of format!($format).

Instead, this happened:
Compiler gives following error:

error[E0425]: cannot find value `bar` in this scope
 --> src/main.rs:9:22
  |
9 |     assert_eq!(foo!("{bar}"), "42");
  |                      ^^^^^ not found in this scope

For more information about this error, try `rustc --explain E0425`.
error: could not compile `macrotest` due to previous error

Meta

rustc --version --verbose:

rustc 1.59.0 (9d1b2106e 2022-02-23)
binary: rustc
commit-hash: 9d1b2106e23b1abd32fce1f17267604a5102f57a
commit-date: 2022-02-23
host: x86_64-unknown-linux-gnu
release: 1.59.0
LLVM version: 13.0.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: This is a bug.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions