Sub topic 12
Writing an attribute macro
This chapter assumes you can read a basic proc-macro crate. That means proc-macro = true in Cargo.toml, TokenStream in and out, and the syn and quote basics from the earlier chapters. You should also be comfortable with ItemFn, DeriveInput and syn::Error.
What an attribute macro does
An attribute macro is a function you attach to an item with #[name] or #[name(args)]. The item can be a function, struct, enum, impl block, module, and so on. The compiler passes the macro two token streams and replaces the item with whatever the macro returns.
#[proc_macro_attribute]
pub fn my_attr(attr: TokenStream, item: TokenStream) -> TokenStream {
// attr: the tokens inside the parentheses, empty for #[my_attr]
// item: the full item the attribute is attached to
item
}The attr stream does not include the macro name or the parentheses. For #[trace(label = "x")] it holds only label = "x".
The three kinds of procedural macro differ in what they receive and how they treat the original code:
| Kind | Receives | Original item | Typical output |
|---|---|---|---|
| Function-like | Anything inside `name!(...)` | None | An expression or items |
| Derive | The struct, enum or union | Kept automatically | Extra items, usually an `impl` |
| Attribute | Arguments and the item | Replaced by your output | Anything, including a rewritten item |
Because the item is replaced, your macro is responsible for emitting the original code again. Derive macros cannot delete or change the type, but attribute macros can. This power is why they are used for wrappers such as #[tokio::main] and #[test]-style harnesses.
A first example: `#[trace]`
The macro below prints a message before a function body runs.
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()
}ItemFn splits a function into parts you can reuse:
attrsholds the other attributes and doc comments.visis the visibility.sigis the signature, includingasync, generics and the return type.blockis the body, braces included.
The new body is { println!(...); { original body } }. The original block is the tail expression, so its value is still returned. return and ? inside it still work.
Re-emitting #(#attrs)* keeps #[inline], #[must_use] and doc comments. If you leave that line out, they disappear silently.
Using the macro from another crate that depends on my_macros:
use my_macros::trace;
#[trace]
fn add(a: i32, b: i32) -> i32 {
a + b
}
#[trace]
fn main() {
println!("{}", add(1, 2));
}This prints entering main, then entering add, then 3.
If someone writes #[trace] on a struct, parse_macro_input! fails with a message like expected fn. The error points at the struct, so you get a useful diagnostic without extra code.
Parsing the attribute arguments
In syn 2 the standard way to read key = value arguments is syn::meta::parser. It uses the same parse_nested_meta machinery as helper attributes on derives. Here #[trace(label = "adding")] replaces the function name in the message.
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, ItemFn, LitStr};
#[proc_macro_attribute]
pub fn trace(attr: TokenStream, item: TokenStream) -> TokenStream {
let mut label: Option<LitStr> = None;
let parser = syn::meta::parser(|meta| {
if meta.path.is_ident("label") {
label = Some(meta.value()?.parse()?);
Ok(())
} else {
Err(meta.error("unsupported trace property"))
}
});
parse_macro_input!(attr with parser);
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 message = match label {
Some(l) => l.value(),
None => sig.ident.to_string(),
};
quote! {
#(#attrs)*
#vis #sig {
println!("entering {}", #message);
#block
}
}
.into()
}The closure borrows label mutably until the parser is consumed by parse_macro_input!. After that statement you can read label normally. An unknown key such as #[trace(lable = "x")] produces an error that points at lable.
For a single, fixed argument you can skip the meta parser and parse the stream as one type, for example parse_macro_input!(attr as LitStr). Use the meta parser when you want several optional named arguments.
Attribute macros on structs
An attribute macro can also keep a type and add code beside it. DeriveInput parses structs, enums and unions, and it implements ToTokens, so you can interpolate it back with #input.
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, DeriveInput, LitStr};
#[proc_macro_attribute]
pub fn describe(attr: TokenStream, item: TokenStream) -> TokenStream {
let text = parse_macro_input!(attr as LitStr);
let input = parse_macro_input!(item as DeriveInput);
let name = &input.ident;
let (ig, tg, wc) = input.generics.split_for_impl();
quote! {
#input
impl #ig #name #tg #wc {
pub const DESCRIPTION: &'static str = #text;
}
}
.into()
}Applied as #[describe("A 2D point")] struct Point { x: i32, y: i32 }, this keeps Point and adds Point::DESCRIPTION. The split_for_impl call works the same way as in a derive macro, so generic types are supported.
If the attribute is written without an argument, parse_macro_input!(attr as LitStr) fails with an "expected string literal" error at the attribute.
Reporting errors without breaking the rest of the build
When a derive macro fails, the type still exists. When an attribute macro fails and returns only an error, the item vanishes. Every later use of that function or type then produces more errors that hide the real problem.
The fix is to return the original item together with the error. Put the logic in a function that uses proc_macro2 and returns syn::Result, then wrap it:
use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use syn::{Error, ItemFn};
#[proc_macro_attribute]
pub fn sync_only(attr: TokenStream, item: TokenStream) -> TokenStream {
let original = TokenStream2::from(item.clone());
match expand(attr.into(), item.into()) {
Ok(tokens) => tokens.into(),
Err(err) => {
let err = err.into_compile_error();
quote! { #original #err }.into()
}
}
}
fn expand(attr: TokenStream2, item: TokenStream2) -> syn::Result<TokenStream2> {
if !attr.is_empty() {
return Err(Error::new_spanned(attr, "sync_only takes no arguments"));
}
let func: ItemFn = syn::parse2(item)?;
if let Some(token) = &func.sig.asyncness {
return Err(Error::new_spanned(
token,
"async functions are not allowed here",
));
}
Ok(quote! { #func })
}This design has three benefits:
- The
expandfunction can be called from unit tests, because it does not use the compiler-onlyproc_macro::TokenStream. - The error points at the
asynckeyword, becausenew_spanneduses the span of the tokens you give it. - The original function stays in the output, so callers still resolve.
Common problems
- Dropped attributes. Forgetting
#(#attrs)*removes doc comments and other attributes from the output. - Ordering. Attributes written before your macro have already been handled by the compiler or are still present in
attrs. Do not assume a fixed order between two attribute macros on one item. Test the combination you care about. - Wrong item type. Parsing as
ItemFnrejects methods inside animplblock, because those areImplItemFn. UseItemImplif you want to wrap a wholeimpl. - Hygiene. Names you introduce, such as a local
startvariable, can clash with names in the user's body. Use unusual names or build them withquote::format_ident!. - Paths. Refer to items with absolute paths such as
::std::time::Instant, so the output works even when the user shadows a name.
Exercise
A #[log_calls] attribute macro parses an ItemFn and returns only quote! { fn wrapper() { /* logging */ } }, without the original function. What happens to code that calls the original function, and how do you fix it?
Show answer
The original function no longer exists, because the macro output replaces the item. Callers fail with "cannot find function" errors. Fix it by emitting the original item (or a rewritten version of it, with #(#attrs)* #vis #sig { ... #block }) in the output.
Exercise
Why is it better for sync_only to return the original item plus err.into_compile_error() than to return only the error?
Show answer
If only the error is returned, the annotated function is removed from the program. Every place that calls it then produces extra "not found" errors that bury the real message. Returning the original item keeps the program resolvable, so the user sees one clear error at the async keyword.