rust-lang / rust-lang/rust

Nested `decl_macro` has incorrect hygiene

Open
#151,569 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-decl-macros-2-0 A-hygiene A-macros C-bug F-decl_macro requires-nightly T-compiler T-lang
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

I tried this code:

#![feature(decl_macro)]

macro foo() {
    macro bar() {
        fn wut() {}
        wut();
    }
    bar!();
}

fn main() {
    foo!();
}
Another code snippet with the same behavior
#![feature(decl_macro)]

macro foo($name:ident) {
    macro $name() {
        fn wut() {}
        wut();
    }
}

fn main() {
    foo!(bar);
    bar!();
}

I expect the above code should compile, since the fn wut item and the wut() call are in the same "macro scope". Instead, I got the following compile error:

error[E0425]: cannot find function `wut` in this scope
  --> src/main.rs:6:9
   |
 6 |         wut();
   |         ^^^ not found in this scope
...
12 |     foo!();
   |     ------ in this macro invocation
   |
   = note: this error originates in the macro `bar` which comes from the expansion of the macro `foo` (in Nightly builds, run with -Z macro-backtrace for more info)

For more information about this error, try `rustc --explain E0425`.

However, if the fn wut item is defined in the foo macro instead, the wut() call finds that item and uses it. For example, the following code compiles and prints "outer":

#![feature(decl_macro)]

macro foo() {
    fn wut() {
        println!("outer");
    }
    macro bar() {
        fn wut() {
            println!("inner");
        }
        wut();
    }
    bar!();
}

fn main() {
    foo!();
}

This seems incorrect / undesirable.

My (uninformed) guess is that the fix would require each identifier to keep track of the entire "macro stack" that it went through.

Meta

Reproducible on the playground with version 1.95.0-nightly (2026-01-23 d222ddc4d90743dfc1e5)

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 compiling the reproducer in src/main.rs with a nightly Rust toolchain and confirm the nested decl_macro hygiene failure. Trace how the foo! and bar! expansions resolve wut, then verify the fix by compiling both snippets and confirming the inner function is found without changing the expected macro behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.