quote is a Rust library for generating TokenStream output in procedural macros. Its quote! macro lets generated Rust look like ordinary syntax, then converts the result from proc_macro2::TokenStream when a proc_macro::TokenStream is required. An empty quote! {} is valid: a procedural macro may generate no code at all. section 3.2
Use interpolation to splice parsed syntax back into generated code. Prefix a variable with # inside quote!: identifiers and types recovered from a field can become pub #name: #ty. quote! substitutes variables, not their properties, so extract f.ident and f.ty before quoting rather than writing #f.ident or #f.ty. section 4.4
Generate public fields
When transforming a named-field struct, iterate over its fields, obtain each field name and type, and map them to quote! { pub #name: #ty }. The resulting iterator of token streams can be placed directly into a larger quoted struct; collecting into Vec<TokenStream> is optional. section 4.4 section 4.4
quote! also makes token-stream tests readable. Create quoted input and expected output, run the helper, then compare their string forms because TokenStream does not implement PartialEq. Parsing generated output with syn::parse2 is another option when a structural assertion is more useful. section 6.3
Test generated builder code
A helper can quote a builder struct plus impl blocks, interpolating #builder and #name into generated definitions. A black-box test then derives the macro on an empty struct and verifies that ExampleStructNoFields::builder().build() compiles and returns the original type. When output fails, cargo expand can reveal the generated test code; interpolation mistakes commonly cause errors involving missing braces, return types, identifiers, or hashes. section 6.4.1 section 6.4.1
Listing 6.9 Adding enough implementation to turn our test green
// earlier imports
pub fn create_builder(item: TokenStream) -> TokenStream {
let ast: DeriveInput = syn::parse2(item).unwrap();
let name = ast.ident;
let builder = format_ident!("{}Builder", name);
quote! {
struct #builder {} #1
impl #builder { #2
pub fn build(&self) -> #name {
#name {}
}
}
impl #name {
pub fn builder() -> #builder { #3
#builder {}
}
}
}
}
Inspect a complete quote! expansion that generates a builder type, its build method, and an associated builder method on the original struct. section 6.4.1

