🦀 Rust Advanced

What is procedural macro metaprogramming with syn, quote, and proc_macro2?

Answer

Writing procedural macros involves three foundational crates. proc_macro2 is a wrapper around the compiler's proc_macro crate that allows creating token streams outside of procedural macro contexts (enabling testing). syn parses a Rust token stream into a strongly-typed Abstract Syntax Tree (AST) — e.g., syn::parse_macro_input!(input as syn::DeriveInput) gives you a structured representation of a struct or enum you can programmatically inspect (field names, types, attributes). quote generates Rust code from a quasi-quoted template where you interpolate values: quote! { impl MyTrait for #name { fn method(&self) -> #return_type { #body } } }. Together they form the standard toolchain for derive macros — syn to read code, quote to write code. The workflow: take a TokenStream, parse with syn, analyze the AST, generate code with quote, return as TokenStream.