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.
Previous
How does Rust FFI (Foreign Function Interface) work with C?
Next
How do you implement a custom global allocator in Rust?
More Rust Questions
View all →- Advanced What are zero-cost abstractions and monomorphization in Rust?
- Advanced What are Pin<T> and Unpin in Rust async programming?
- Advanced How does the async runtime work internally in Rust (Waker, Poll, Executor)?
- Advanced What are the rules for writing correct unsafe Rust?
- Advanced How does Rust FFI (Foreign Function Interface) work with C?