Sub topic 12
Writing an attribute macro
This chapter assumes you can set up a proc-macro crate (proc-macro = true, with syn, quote and proc-macro2). It also assumes you have written a derive macro and can use parse_macro_input! and quote!.
How attribute macros differ
An attribute macro is written as #[name] or #[name(args)] on an item. The item can be a function, struct, enum, impl block or module. Two things set it apart from a derive macro:
- It receives two token streams: the attribute's arguments and the annotated item.
- Its output replaces the item. A derive macro only adds code next to the item. An attribute macro must print the item back out, or the item disappears.
You declare it with #[proc_macro_attribute].
A trace macro
This macro wraps a function so that it prints a message each time it is called.
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, ItemFn};
#[proc_macro_attribute]
pub fn trace(_attr: TokenStream, item: TokenStream) -> TokenStream {
let func = parse_macro_input!(item as ItemFn);
let attrs = &func.attrs;
let vis = &func.vis;
let sig = &func.sig;
let block = &func.block;
let name = sig.ident.to_string();
quote! {
#(#attrs)*
#vis #sig {
println!("entering {}", #name);
#block
}
}
.into()
}The macro works in four steps:
parse_macro_input!(item as ItemFn)parses the item into a syntax tree. If the attribute sits on something that is not a function, the user gets a compiler error.- It splits the function into attributes, visibility, signature and body.
quote!rebuilds the function. The original body#blockis a block, so it is placed inside the new body. Its last expression becomes the return value, andreturnstatements still work..into()converts theproc_macro2::TokenStreamfromquote!into theproc_macro::TokenStreamthe compiler expects.
In another crate that depends on my_macros, you use it like this:
use my_macros::trace;
#[trace]
fn double(x: i32) -> i32 {
x * 2
}
fn main() {
println!("{}", double(21));
}Running it prints entering double, then 42.
The #(#attrs)* repetition keeps the function's other attributes, such as #[inline] or doc comments. If you leave it out, they are silently dropped.
Handling the arguments
For #[trace] the attr stream is empty. Ignoring it means #[trace(verbose)] is silently accepted and does nothing. It is better to reject input you do not support:
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, ItemFn};
#[proc_macro_attribute]
pub fn trace(attr: TokenStream, item: TokenStream) -> TokenStream {
if !attr.is_empty() {
let tokens = proc_macro2::TokenStream::from(attr);
return syn::Error::new_spanned(tokens, "#[trace] takes no arguments")
.into_compile_error()
.into();
}
let func = parse_macro_input!(item as ItemFn);
let attrs = &func.attrs;
let vis = &func.vis;
let sig = &func.sig;
let block = &func.block;
let name = sig.ident.to_string();
quote! {
#(#attrs)*
#vis #sig {
println!("entering {}", #name);
#block
}
}
.into()
}To accept real arguments, such as #[trace(prefix = "db")], define a type that implements Parse and use parse_macro_input!(attr as MyArgs). You can also use syn::meta::parser with parse_nested_meta, as in the helper attribute chapter.
Common mistakes
| Mistake | Result |
|---|---|
| Forgetting `#(#attrs)*` | Doc comments and other attributes on the item vanish |
| Parsing `item` as the wrong type | A parse error that points at the whole item |
| Ignoring `attr` | Misspelled or unsupported arguments are accepted silently |
| Using `#sig` without `#vis` | A `pub fn` becomes private |
Exercise
A #[trace] macro returns only quote! { println!("hi"); } and never emits the original function. What happens when the attribute is placed on fn double?
Show answer
The attribute's output replaces the item, so double no longer exists. Any call to it fails with "cannot find function double". The macro must re-emit the function, with its attributes, visibility, signature and body.