liveBook · Manning

Quote

As explained in Idiomatic Rust

quote is a Rust library that generates Rust source code from syntax-like interpolation constructs.

quote generates Rust code inside procedural macros using syntax-like interpolation. It offers a higher-level alternative to building generated code directly from raw token streams. section 8.3

Listing 8.9 Implementing the PrintName derive macro
#[proc_macro_derive(PrintName)]
pub fn print_name(input: TokenStream) -> TokenStream {   #1
    let input = parse_macro_input!(input as DeriveInput);    #1

    let generics = add_trait_bounds(input.generics);         #2
    let (impl_generics, type_generics, where_clause) =   #3
        generics.split_for_impl();          #3            

    let name = input.ident;

    let expanded = quote! {                 #4
        impl #impl_generics print_name::PrintName for #name #type_generics
                #where_clause {
            fn name() -> &'static str {
                stringify!(#name)       #5
            }
        }
    };

    TokenStream::from(expanded)     #6
}

fn add_trait_bounds(mut generics: Generics) -> Generics {
    for param in &mut generics.params {
        if let GenericParam::Type(ref mut type_param) = *param {
          type_param.bounds.push(                   #7
            parse_quote!(print_name::PrintName)    #7
          );   #7                                     
        }
    }
    generics
}

The PrintName derive macro interpolates generics and a type name into an implementation, then converts the generated code into a token stream. section 8.3

How Idiomatic Rust covers it

How deep it goes
Demonstrates interpolation and token stream conversion in a derive macro, but does not explore more elaborate macro features.
Examples
Generates a PrintName trait implementation that returns a struct’s name.
What it assumes
Builds on procedural macros and token streams, while introducing syn parsing and quote code generation.
What you can do after
Apply quote! interpolation to generate code for a Rust derive macro.
How it connects
Connects procedural macros with syn parsing and derive macros.

Also explained in

Compare how 2 books explain quote →

Related concepts

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