Sub topic 11
Reading helper attributes
This chapter assumes you can write a basic derive macro with syn and quote, and that you know how syn::Error reports problems. Here you will let users configure a derive with their own attributes, such as #[describe(name = "...")].
Why helper attributes exist
A derive macro only sees the type it is attached to. To let users tune the output, such as renaming a type or skipping a field, you declare helper attributes. Without the declaration, the compiler rejects #[describe(...)] as an unknown attribute.
You declare helpers in the attributes(...) list of the derive:
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, DeriveInput};
#[proc_macro_derive(Describe, attributes(describe))]
pub fn describe_derive(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let ident = &input.ident;
let fallback = ident.to_string();
let label = match describe_name(&input) {
Ok(name) => name.unwrap_or(fallback),
Err(err) => return err.into_compile_error().into(),
};
let (ig, tg, wc) = input.generics.split_for_impl();
quote! {
impl #ig #ident #tg #wc {
pub fn describe() -> &'static str {
#label
}
}
}
.into()
}The helper only exists while the derive runs. The compiler strips it afterwards, so it never reaches your expanded code.
Finding your attribute
DeriveInput exposes the attributes on the type as input.attrs, a list of syn::Attribute. Other attributes such as #[derive(...)] and #[doc] appear in the same list, so you must filter by name. attr.path().is_ident("describe") does that.
Parsing the arguments with syn 2
In syn 2, Attribute::parse_nested_meta walks the comma-separated items inside the parentheses. It calls your closure once for each item. Inside the closure, meta.path is the key, and meta.value()?.parse()? reads the value after the =.
use syn::{DeriveInput, LitStr};
fn describe_name(input: &DeriveInput) -> syn::Result<Option<String>> {
let mut name = None;
for attr in &input.attrs {
if attr.path().is_ident("describe") {
attr.parse_nested_meta(|meta| {
if meta.path.is_ident("name") {
let value: LitStr = meta.value()?.parse()?;
name = Some(value.value());
Ok(())
} else {
Err(meta.error("unsupported describe property"))
}
})?;
}
}
Ok(name)
}A user can then write:
#[derive(Describe)]
#[describe(name = "Person record")]
struct Person {
age: u8,
}Calling Person::describe() returns "Person record". Without the attribute it returns "Person".
flowchart TD
A[DeriveInput.attrs] --> B{path is describe?}
B -- no --> C[skip attribute]
B -- yes --> D[parse_nested_meta]
D --> E{key is name?}
E -- yes --> F[parse LitStr value]
E -- no --> G[meta.error]Rejecting bad input
The else branch returns meta.error(...). That error carries the span of the offending key, so #[describe(title = "x")] produces a compiler message underlining title. Silently ignoring unknown keys hides typos from users, so return an error instead.
The ? after parse_nested_meta passes failures up to the caller. The derive then turns them into compile_error! output, as in the earlier error reporting chapter.
Common mistakes
- Forgetting
attributes(describe). The compiler reportscannot find attribute describe in this scope. The fix is in the derive declaration, not in the user's code. - Not filtering by name. Parsing every attribute fails on
#[derive(...)]or doc comments. - Reading only the first match. A user can write
#[describe(...)]twice. The loop above handles each one, and the lastnamewins. Decide whether that or an error is the right behavior for your macro. - Using the syn 1 API.
parse_metaandNestedMetaare gone in syn 2. Useparse_nested_meta. - Not consuming the value. If you accept a key without calling
meta.value(), flag-style items like#[describe(skip)]work. If you callmeta.value()on a key with no=, parsing fails.
Field-level helpers
The same helper can sit on fields. You loop over fields.iter() and call the same parsing on field.attrs. Only the source of the attribute list changes, from input.attrs to field.attrs.
Exercise
A user writes #[describe(name = "A", name = "B")] on a type. With the describe_name function above, what does it return, and how would you reject the duplicate?
Show answer
It returns Some("B"), because each name overwrites the previous value. To reject duplicates, check name.is_some() inside the name branch before assigning, and return Err(meta.error("duplicate name")) if it is already set.