Skip to content

Attribute macro can replace item with expression. #144716

@theemathas

Description

@theemathas

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 

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-attributesArea: Attributes (`#[…]`, `#![…]`)A-macrosArea: All kinds of macros (custom derive, macro_rules!, proc macros, ..)A-proc-macrosArea: Procedural macrosC-bugCategory: This is a bug.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions