rust-lang / rust-lang/rust

Attribute macro can replace item with expression.

Open
#144,716 9 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

I tried this code:

bar/src/lib.rs:

use proc_macro::TokenStream;

#[proc_macro_attribute]
pub fn my_macro(_: TokenStream, _: TokenStream) -> TokenStream {
    "\"weird\"".parse().unwrap()
}

src/main.rs:

fn main() {
    // prints "weird"
    println!("{}", {
        #[bar::my_macro]
        struct Thing;
    });
}

I expected the code to give a compile error. Instead, it compiles and prints weird.

The proc macro is somehow replacing an item with an expression. The reference says this isn't allowed:

The returned TokenStream replaces the item with an arbitrary number of items.

Initially discovered in #144579.

@rustbot labels +A-macros +A-proc-macros +A-attributes

Meta

rustc --version --verbose:

rustc 1.88.0 (6b00bc388 2025-06-23)
binary: rustc
commit-hash: 6b00bc3880198600130e1cf62b8f8a93494488cc
commit-date: 2025-06-23
host: aarch64-apple-darwin
release: 1.88.0
LLVM version: 20.1.5

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

Reproduce the behavior using bar/src/lib.rs and src/main.rs with the reported rustc version, then trace how attribute macro output is validated in the compiler. Add regression coverage for the item-to-expression case and verify that the example now produces the expected compile error.

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
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.