rust-lang / rust-lang/rust

`$crate` is treated as a normal identifier in a `macro_rules` matcher

Open
#147,028 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-macros C-bug T-compiler T-lang
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

I've found that, in some cases, inside a macro_rules matcher (the thing on the left of the =>), $crate is treated as if it's a normal identifier, which seems very weird. I'm not sure if this is intended or a bug.

This weirdness manifests in two different ways:

  1. A $crate on its own in the matcher is treated as literally matching $crate, as opposed to being a metavariable or erroring:
macro_rules! foo {
    ($crate and $crate:tt) => {
        "wtf"
    }
}

macro_rules! bar {
    () => {
        foo!($crate and $crate:tt)
    }
}

fn main() {
    println!("{}", bar!());  // prints "wtf"
}
  1. I can create a metavariable (e.g., the metavariable $x:tt has the name x) such that the metavariable's name is $crate:
macro_rules! bar {
    ($dol:tt) => {
        macro_rules! foo {
            ($dol $crate : expr) => { $dol $crate }
        }
    }
}

bar!($);

fn main() {
    println!("{}", foo!(1 + 2));  // prints 3
}

See also https://github.com/rust-lang/rust/issues/146967 and https://github.com/rust-lang/rust/issues/146968 and https://github.com/rust-lang/rust/issues/146114 for weirdness with $crate.

Meta

Reproducible on the playground with version 1.92.0-nightly (2025-09-24 caccb4d0368bd918ef66)

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

No repository file or test is named. Start by running both macro_rules reproductions on the reported Rust 1.92.0-nightly toolchain, then locate the compiler entry point that handles matchers and $crate. Add regression coverage for the two behaviors and verify the resulting behavior against the intended language rule.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.