liveBook · Manning

Proc_macro_derive

As explained in Write Powerful Rust Macros

proc_macro_derive is the Rust attribute that marks a procedural macro function as a derive macro implementation and assigns its invocation name.

proc_macro_derive is a Rust attribute that marks a procedural macro function as a derive-macro entry point. Its parenthesized name, such as Hello, becomes the invocation name in #[derive(Hello)]; the function name is private to the implementation. section 3.2

A derive implementation follows a small interface:

  • Accept a TokenStream containing the annotated item, such as a struct. section 3.2
  • Return a TokenStream containing generated Rust code. section 3.2
  • Use quote! to construct output and convert it with into(). section 3.2

Minimal derive entry point

With #[proc_macro_derive(Hello)] on pub fn hello(_item: TokenStream) -> TokenStream, a consumer can write #[derive(Hello)] on struct Example;. The generated tokens become part of the consumer's program, so invalid output produces a compiler error attributed to the Hello derive macro. section 3.2

use quote::quote;
use proc_macro::TokenStream;

#[proc_macro_derive(Hello)]                 #1
pub fn hello(_item: TokenStream) -> TokenStream {
    let add_hello_world = quote! {};       #2
    add_hello_world.into()                #3
}

Inspect the compact implementation showing the attribute, TokenStream signature, quote! output, and conversion. section 3.2

How Write Powerful Rust Macros covers it

How deep it goes
Defines the attribute, naming rule, TokenStream interface, and token-processing context without developing full input parsing.
Examples
Uses a Hello derive, an Example struct, quote! output, and an intentionally invalid generated function.
What it assumes
Assumes familiarity with Rust functions, attributes, structs, and compiler-generated code while introducing the derive entry-point contract.
What you can do after
Build it from scratch by declaring a named derive entry point that accepts and returns TokenStream values.
How it connects
Connects derive macros with procedural macros, attributes, TokenStream, tokenization, parsing, and generated code.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Write Powerful Rust Macros. The section links point to the parts of the book it draws on.