Sub topic 2
Generating Code with `quote!`
Assume you know Rust structs, traits, generics, Cargo dependencies, and basic macro_rules!. This chapter focuses on turning parsed syntax into new Rust code.
Generating code with `quote!`
The quote! macro converts Rust-like syntax into a proc_macro2::TokenStream. A token stream is the sequence of tokens that the compiler parses. Place a variable inside quote! with # to insert its tokens.
let name = syn::Ident::new("answer", proc_macro2::Span::call_site());
let generated = quote::quote! {
fn #name() -> u32 {
42
}
};For repeated generated items, use #(...),*. The repetition inserts each value and separates values with commas.
Writing a function-like macro
A function-like procedural macro is invoked like add!(1, 2). Parse its input with syn, then interpolate the parsed values into generated code.
use proc_macro::TokenStream;
use quote::quote;
use syn::parse::{Parse, ParseStream};
use syn::{parse_macro_input, LitInt, Token};
struct Pair {
left: LitInt,
right: LitInt,
}
impl Parse for Pair {
fn parse(input: ParseStream) -> syn::Result<Self> {
Ok(Self {
left: input.parse()?,
right: {
input.parse::<Token![,]>()?;
input.parse()?
},
})
}
}
#[proc_macro]
pub fn add(input: TokenStream) -> TokenStream {
let Pair { left, right } = parse_macro_input!(input as Pair);
quote! { (#left + #right) }.into()
}If the caller omits the comma or supplies a non-integer, syn returns a compiler error.
Writing a derive macro
A derive macro receives the annotated item as a DeriveInput. Extract its identifier, then generate a trait implementation.
#[proc_macro_derive(HelloMacro)]
pub fn hello_macro(input: TokenStream) -> TokenStream {
let input = syn::parse_macro_input!(input as syn::DeriveInput);
let name = &input.ident;
let text = name.to_string();
quote::quote! {
impl ::hello_macro::HelloMacro for #name {
fn hello_macro() {
println!("Hello, {}!", #text);
}
}
}
.into()
}The absolute path ::hello_macro::HelloMacro avoids depending on the caller's imports.
Supporting generic types
For generic structs, call split_for_impl() and place its three results in the implementation:
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
quote! {
impl #impl_generics Trait for #name #ty_generics #where_clause {
// generated methods
}
}This preserves type parameters, lifetimes, and where clauses.
Exercise
Why should a derive macro use split_for_impl() instead of writing impl<T> ... manually?
Show answer
It preserves every generic parameter and the original where clause, so the generated implementation matches the input type.