Sub topic 5
Generating code with quote!
This chapter assumes you can write a proc-macro crate with syn, quote, and proc-macro2 in its dependencies, and that you can parse a DeriveInput. It covers the output half of a macro: turning values into Rust code.
What quote! does
quote! takes Rust-like source text and returns a proc_macro2::TokenStream. Inside it, #name inserts the value of the variable name. The value must implement the ToTokens trait. syn types such as Ident, Type, Expr, and LitStr all implement it, and so do String, integers, and bool. The last three become literals.
Your macro entry point must return proc_macro::TokenStream, so you end with .into(). Helper functions should keep using proc_macro2::TokenStream, because that type also works in unit tests.
Interpolation and repetition
Repetition uses the same syntax as macro_rules!. #(#items)* emits every item in order. #(#items),* puts a comma between items. The variable must be something iterable, such as a Vec, a slice, or an iterator. If you use several variables in one repetition, they must have the same length.
Creating new identifiers
A String interpolates as a string literal, not as a name. To build a name such as get_age, use format_ident!.
| You write | Result in generated code |
|---|---|
| `let n = "age"; quote!(#n)` | `"age"` (a string literal) |
| `let n = format_ident!("age"); quote!(#n)` | `age` (an identifier) |
| `format_ident!("get_{}", ident)` | `get_age` for an `ident` named `age` |
Worked example: a getter generator
This derive macro adds a get_<field> method for each named field. It uses split_for_impl so generic structs work, and it returns a compile error for unsupported input. Error reporting gets its own chapter.
use proc_macro::TokenStream;
use quote::{format_ident, quote};
use syn::{parse_macro_input, Data, DeriveInput, Fields};
#[proc_macro_derive(Getters)]
pub fn getters(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let name = &input.ident;
let fields = match &input.data {
Data::Struct(s) => match &s.fields {
Fields::Named(f) => &f.named,
_ => return unsupported(name),
},
_ => return unsupported(name),
};
let methods = fields.iter().map(|f| {
let field = f.ident.as_ref().unwrap();
let ty = &f.ty;
let getter = format_ident!("get_{}", field);
quote! {
pub fn #getter(&self) -> &#ty {
&self.#field
}
}
});
let (ig, tg, wc) = input.generics.split_for_impl();
quote! {
impl #ig #name #tg #wc {
#(#methods)*
}
}
.into()
}
fn unsupported(name: &syn::Ident) -> TokenStream {
syn::Error::new_spanned(name, "Getters needs a struct with named fields")
.into_compile_error()
.into()
}Using it from another crate that depends on my_macros:
use my_macros::Getters;
#[derive(Getters)]
struct User {
name: String,
age: u32,
}
fn main() {
let u = User { name: "Ada".into(), age: 36 };
println!("{} is {}", u.get_name(), u.get_age());
}This prints Ada is 36.
Common errors
- Reusing a consumed iterator. A repetition consumes an iterator. If you need the same list twice, collect it into a
Vecfirst. - Mismatched lengths. Two variables of different lengths in one
#(...)*cause a compile error in the macro crate. - Names as strings. If generated code reports "expected identifier, found string literal", you interpolated a
Stringwhere anIdentwas needed. - Relative paths. Write
::std::fmt::Debug, notDebug. The user's code may have shadowed the name.
Exercise
A macro contains let field = "id"; quote! { self.#field }. The generated code fails to compile. What is wrong, and how do you fix it?
Show answer
A String or &str interpolates as the string literal "id", so the output is self."id". Create an identifier instead, for example let field = format_ident!("id"); or syn::Ident::new("id", proc_macro2::Span::call_site()), so quote! emits self.id.