Sub topic 11
Reading helper attributes
This chapter assumes you can write a basic derive macro with syn and quote, as in the earlier chapters. You should also know how a DeriveInput represents a struct and its fields. The examples use syn 2 with the full feature, in a proc-macro crate named my_macros.
What a helper attribute is
A derive macro gets only the type it is attached to. Often you want the user to give it more information, such as "skip this field" or "use this name in the output". A helper attribute carries that information. It is an extra attribute that your derive macro declares and reads.
#[derive(Describe)]
struct User {
id: u64,
#[describe(skip)]
password_hash: String,
}Here describe is the helper attribute. The Describe derive reads it. The compiler does nothing else with it.
Declaring the attribute
You list helper attributes in the proc_macro_derive attribute:
#[proc_macro_derive(Describe, attributes(describe))]
pub fn describe_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
// ...
}The attributes(describe) part tells the compiler that describe is an inert attribute. Inert means the compiler accepts it and ignores it. Only your macro gives it meaning. You can list several names, for example attributes(describe, label).
Helper attributes can appear on the type, on each field, and on each enum variant. They show up in the attrs vector of DeriveInput, Field, and Variant. The compiler leaves them in place, because a derive macro cannot change the item it is attached to. An attribute macro is different: it replaces the item, so it must strip its own helper attributes from the output.
Put the #[derive(...)] line above any helper attribute on the same type. A helper attribute placed before the derive is reported as used before it is introduced.
How the attributes reach your code
The compiler collects every attribute into a Vec<syn::Attribute>. Your macro has to find the right ones and then parse their contents.
The attribute list also holds attributes that are not yours, such as #[doc] or #[allow]. Always filter by path first.
Parsing with parse_nested_meta
In syn 2, the standard tool is Attribute::parse_nested_meta. It calls your closure once for each item inside the parentheses. Inside the closure, meta.path is the key. You decide how to read what follows it.
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)
}The closure must consume exactly the tokens that belong to its key. For name = "x", calling meta.value()? consumes the =, and .parse() then consumes the literal. For a bare word such as skip, you consume nothing more and return Ok(()).
The common shapes are these:
| Written as | How to read it |
|---|---|
| `#[describe(skip)]` | Check `meta.path.is_ident("skip")` and set a flag. |
| `#[describe(name = "x")]` | Call `meta.value()?.parse::<LitStr>()?`. |
| `#[describe(tags(a, b))]` | Call `meta.parse_nested_meta(...)` again inside the closure. |
| `#[describe = "x"]` | Not handled by `parse_nested_meta`. Match `attr.meta` against `Meta::NameValue`. |
Several options can share one attribute, as in #[describe(skip, name = "x")]. They can also be split across several #[describe(...)] attributes. The loop above handles both, because it visits every matching attribute.
A complete example
This derive uses the helper attribute on both the type and its fields. name sets a label. skip removes a field from the list. It generates two associated functions.
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, Attribute, Data, DeriveInput, Error, Fields, LitStr};
#[proc_macro_derive(Describe, attributes(describe))]
pub fn describe_derive(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
expand(input)
.unwrap_or_else(syn::Error::into_compile_error)
.into()
}
#[derive(Default)]
struct Opts {
skip: bool,
name: Option<String>,
}
fn parse_opts(attrs: &[Attribute]) -> syn::Result<Opts> {
let mut opts = Opts::default();
for attr in attrs {
if !attr.path().is_ident("describe") {
continue;
}
attr.parse_nested_meta(|meta| {
if meta.path.is_ident("skip") {
opts.skip = true;
Ok(())
} else if meta.path.is_ident("name") {
let value: LitStr = meta.value()?.parse()?;
opts.name = Some(value.value());
Ok(())
} else {
Err(meta.error("unsupported describe property"))
}
})?;
}
Ok(opts)
}
fn expand(input: DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
let ident = &input.ident;
let type_opts = parse_opts(&input.attrs)?;
if type_opts.skip {
return Err(Error::new_spanned(ident, "`skip` is only valid on fields"));
}
let type_name = type_opts.name.unwrap_or_else(|| ident.to_string());
let fields = match &input.data {
Data::Struct(data) => match &data.fields {
Fields::Named(named) => &named.named,
_ => {
return Err(Error::new_spanned(
ident,
"Describe only supports structs with named fields",
))
}
},
_ => return Err(Error::new_spanned(ident, "Describe only supports structs")),
};
let mut labels = Vec::new();
for field in fields {
let opts = parse_opts(&field.attrs)?;
if opts.skip {
continue;
}
let label = opts
.name
.unwrap_or_else(|| field.ident.as_ref().unwrap().to_string());
labels.push(label);
}
let (ig, tg, wc) = input.generics.split_for_impl();
Ok(quote! {
impl #ig #ident #tg #wc {
pub fn describe_name() -> &'static str {
#type_name
}
pub fn describe_fields() -> &'static [&'static str] {
&[#(#labels),*]
}
}
})
}In a crate that depends on my_macros, you use it like this:
use my_macros::Describe;
#[derive(Describe)]
#[describe(name = "user account")]
#[allow(dead_code)]
struct User {
id: u64,
#[describe(name = "login")]
username: String,
#[describe(skip)]
password_hash: String,
}
fn main() {
println!("{}", User::describe_name());
println!("{:?}", User::describe_fields());
}The program prints user account and then ["id", "login"]. The skipped field is absent, and the renamed field uses its new label.
Design choices that matter
Reject what you do not understand
The else branch with meta.error(...) is deliberate. If you silently ignore unknown keys, a typo such as #[describe(nmae = "x")] compiles and does nothing, which is hard to notice. meta.error produces a compile error whose span points at the offending key.
Put all parsing in one place
Parse options once, in a function that returns syn::Result, and use the ? operator. The derive body then works with a plain struct and never touches raw attributes. This is also where you check combinations that make no sense, such as skip on the type.
Validate values, not only keys
LitStr accepts only a string literal. If the user writes name = 5, syn reports a parse error at the 5. This costs you no extra code. To accept several literal kinds, parse a syn::Lit or syn::Expr and match on it.
Report duplicates
The example lets a later name overwrite an earlier one. For options that must be unique, check opts.name.is_some() before assigning, and return meta.error("duplicate name").
Common errors
- Forgetting
attributes(...). The user sees "cannot find attribute". - Not filtering by path. Parsing every attribute fails on
#[doc = "..."]or#[derive(...)]. - Not consuming the value. If the closure returns
Ok(())forname = "x"without callingmeta.value(),synreports "expected,", because it sees= "x"still unread. - Using
parse_argsfor list syntax.attr.parse_args::<T>()expects you to supply a full parser for the contents. It suits attributes with a custom syntax, such as#[describe("a", "b")]. Useparse_nested_metafor the usualkey = valuestyle. - Expecting the attribute to disappear. In a derive, the helper attribute stays in the user's code. That is harmless because it is inert.
Exercises
Exercise
A user writes #[describe(nmae = "x")] on a field. With the parse_opts function above, what happens, and which line of the code causes it?
Show answer
Compilation fails with the message "unsupported describe property", pointing at nmae. The else branch of the closure calls meta.error(...), which creates a syn::Error spanned at the unknown key. parse_nested_meta returns it, ? passes it up, and into_compile_error turns it into a compiler error.
Exercise
Extend parse_opts so that #[describe(tags(a, b))] collects the identifiers a and b into a Vec<String> field named tags. Which method reads the inner list, and which method turns each item into a string?
Show answer
Add tags: Vec<String> to Opts and a new branch for meta.path.is_ident("tags"). Inside it, call meta.parse_nested_meta(|inner| { opts.tags.push(inner.path.require_ident()?.to_string()); Ok(()) })?; and then return Ok(()). parse_nested_meta reads the inner list, and require_ident returns the single identifier of each item or an error if it is a longer path.