skip to content

In a Rust derive macro, how do you accept a #[builder(default)] field attribute, and why does rustc reject it as unknown without that?

level: middleimportance: should knowfreq 30%

answer

  1. declared by the derive
  2. attributes(...) in proc_macro_derive
  3. inert: rustc only lets it through
  4. filter Field::attrs by path
  5. parse_nested_meta and meta.error

basics

~20 s

Declare it in the derive as #[proc_macro_derive(Builder, attributes(builder))]. That registers builder as an inert helper attribute on the item and its fields; without it rustc treats #[builder] as an unknown attribute. The derive then finds and parses it in each Field's attrs.

solid answer

~30 s

rustc rejects an attribute it cannot resolve, so `#[builder(default)]` on a field fails with "cannot find attribute `builder` in this scope" unless something declares it. The derive declares it with `#[proc_macro_derive(Builder, attributes(builder))]`. That makes `builder` a **helper attribute**: inert, so rustc does nothing with it except accept it, and it stays in the tokens the derive receives. Inside the derive, loop over each `Field::attrs`, skip anything whose `attr.path().is_ident("builder")` is false (doc comments arrive as `#[doc]` attributes), and parse the arguments with `attr.parse_nested_meta`, returning `meta.error(...)` for an unknown key so the error underlines that key.

code

rust · 32 lines
rust
use proc_macro::TokenStream;
use syn::{parse_macro_input, Data, DeriveInput};

#[proc_macro_derive(Builder, attributes(builder))]
pub fn derive_builder(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let Data::Struct(data) = &input.data else { return TokenStream::new() };
    for field in &data.fields {
        if let Err(e) = wants_default(field) {
            return e.to_compile_error().into();
        }
    }
    TokenStream::new() // generation omitted: this snippet shows the attribute handling
}

fn wants_default(field: &syn::Field) -> syn::Result<bool> {
    let mut use_default = false;
    for attr in &field.attrs {
        if !attr.path().is_ident("builder") {
            continue; // a doc comment, #[allow(...)] or another derive's helper
        }
        attr.parse_nested_meta(|meta| {
            if meta.path.is_ident("default") {
                use_default = true;
                Ok(())
            } else {
                Err(meta.error("unknown builder option, expected `default`"))
            }
        })?;
    }
    Ok(use_default)
}

go deeper

for a junior

Recall that field options like #[builder(default)] have to be declared by the derive, using attributes(builder) in #[proc_macro_derive].

for a middle

Explain inert helpers, where they are valid, how the derive filters Field::attrs by path, and how parse_nested_meta reads the options.

for a senior

Show error discipline: unknown keys rejected with meta.error so the typo is underlined, doc comments and other derives' attributes skipped, and helpers placed after the derive.

for a principal

Treat a derive's helper vocabulary as public API: once users write #[builder(default)], renaming or reinterpreting an option breaks their code.

## The problem a helper attribute solves A derive often needs per-field configuration: this field has a default, that one is skipped, a third is renamed. The natural syntax is an attribute on the field, `#[builder(default)]`. But rustc resolves every attribute it sees. An attribute that is neither built in nor an attribute macro in scope is an error: `error: cannot find attribute `builder` in this scope` You get exactly that error with `#[builder(default)]` on a plain struct, and also on a struct that derives a macro which did not declare `builder`. ## Declaring a helper The fix is in the derive's own declaration: `#[proc_macro_derive(Builder, attributes(builder))]` The Reference calls these **derive macro helper attributes**. Declaring one has precise effects: - `builder` becomes valid on the item and on its **fields and variants**, wherever `#[derive(Builder)]` is applied; - the attribute is **inert**: rustc does not expand it or act on it, it only stops treating it as unknown; - it stays in the token stream passed to the derive, so the derive can read it; - any other macro can also see it, so it is a convention, not private data. The Reference also notes that rustc currently accepts a helper written *before* the `#[derive]` that introduces it, as deprecated behaviour slated to become an error; put helpers after the derive. | | Declared helper | Attribute macro | |---|---|---| | Declared by | `attributes(...)` in `#[proc_macro_derive]` | its own `#[proc_macro_attribute]` function | | Runs code | no, inert | yes, replaces the item | | Valid where | the derived item, its fields and variants | wherever the macro is in scope | ## Reading it in the derive The helper arrives in `syn::Field::attrs` (or `DeriveInput::attrs` for item-level options) as a `syn::Attribute`. The robust pattern: 1. Iterate the field's `attrs`. 2. Skip any attribute whose path is not `builder`: `if !attr.path().is_ident("builder") { continue; }`. A field may also carry doc comments, `#[allow(...)]` or another derive's helpers, and those belong to someone else. 3. Call `attr.parse_nested_meta(|meta| { ... })`. It walks the comma-separated entries inside the parentheses; `meta.path` is each key, and `meta.value()` reads an `= value` part when the option takes one. 4. Accept known keys and return `Err(meta.error("unknown builder option, expected `default`"))` for anything else. 5. Propagate the error with `?`, then emit it with `to_compile_error()`. Because `meta.error` is spanned at the key being parsed, a typo such as `#[builder(defualt)]` is underlined exactly, not at the derive. ## What the field option then changes With `use_default` known for each field, the generator chooses per field: required fields produce `self.host.ok_or("host")?`, defaulted ones `self.port.unwrap_or_default()`. A field marked `default` whose type has no `Default` impl is then a compile error in the generated code, and where rustc points it depends on the spans the derive gave those tokens. ## Pitfalls - **Not filtering by path**: calling `parse_nested_meta` on a doc comment returns the error "expected parentheses: #[doc(...)]", so documenting a field would break the derive. - **Silently ignoring unknown keys**: a misspelt option then does nothing, and the user finds out at run time. - **Writing the helper above the derive**: `#[builder]` placed before `#[derive(Builder)]` is accepted today only as deprecated behaviour, so keep helpers after the derive. - **Expecting the derive to strip it**: a derive cannot modify the item, and does not need to, because inert helpers are harmless.

  • How would the derive accept #[builder(rename = "hostname")] as well?
    Inside the same `parse_nested_meta` closure, add a branch for `meta.path.is_ident("rename")` and read the value with `let lit: syn::LitStr = meta.value()?.parse()?;`. `meta.value()` consumes the `=`, and parsing as `LitStr` gives a precise error if the user wrote a number or an identifier instead of a string.
  • Can a derive find out whether the struct also derives some other trait from its attributes?
    Only from what is written in the token stream it receives, and that is unreliable: a trait may be implemented by hand elsewhere, or by another macro. A derive should not depend on that. If generated code needs a trait, it states the bound or calls the trait, and rustc reports a missing implementation where the user can fix it.

  • Any attribute is allowed inside a struct that has a derive on it.
  • A helper attribute is a small attribute macro that runs its own code.
  • The derive must remove its helper attributes or rustc will reject them.
  • Every attribute in Field::attrs belongs to the derive reading it.
  • Unknown helper options can be ignored safely.