An attribute macro is a type of procedural macro in Rust that defines custom, compiler-recognized attributes. It operates as a function that takes aDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
TokenStream (a flat sequence of lexical tokens) representing the annotated item, processes it at compile time, and emits a new TokenStream that entirely replaces the original item in the compilation unit.
Unlike declarative macros (macro_rules!), attribute macros are compiled as separate dynamic libraries and are invoked by the compiler during the macro expansion phase, which is a distinct step that occurs after the initial parsing of the source code.
Crate Configuration
Attribute macros must be defined in a dedicated crate with theproc-macro type enabled in the Cargo.toml manifest:
Function Signature
The macro is defined using the#[proc_macro_attribute] directive. The underlying Rust function must accept exactly two proc_macro::TokenStream arguments and return a single TokenStream.
Parameter Breakdown
attr: TokenStream: Represents the tokens passed inside the attribute’s parentheses. For#[custom_attribute(arg1, arg2)], this stream containsarg1, arg2. If no arguments are provided, this stream is empty.item: TokenStream: Represents the entire syntactic item (e.g., astruct,fn,enum, orimplblock) to which the attribute is applied.
AST Manipulation
Because rawTokenStream manipulation is complex, attribute macros typically rely on the syn crate to explicitly parse the token stream into a strongly-typed Abstract Syntax Tree (AST), and the quote crate to serialize the modified AST back into a TokenStream.
Application Syntax
Once defined and imported, the macro is applied to an item using the standard Rust attribute syntax. The compiler intercepts this, passes the item to the macro, and compiles the returnedTokenStream instead of the original code.
Replacement Semantics
A critical characteristic of attribute macros is that they are destructive by default. The originalitem passed into the macro is discarded unless explicitly reconstructed and included in the returned TokenStream. If the macro returns an empty TokenStream, the annotated item is effectively stripped from the compiled source code.
Master Rust with Deep Grasping Methodology!Learn More





