The syn and quote Crates
Working directly with TokenStreams is low-level and tedious. To write
procedural macros effectively, authors often rely on syn (a parser for
Rust syntax) and quote (which constructs syn values from literal code
fragments) to do the heavy lifting of parsing and code generation.
The workflow of a typical procedural macro is:
- Input: Accept a raw
proc_macro::TokenStreamfrom the compiler. - Parsing (
syn): Convert the token stream into a structured, type-safe Abstract Syntax Tree (AST) representing Rust language items (e.g., structs, fields, functions). - Processing: Inspect the AST struct and perform your custom logic to decide what code needs to be generated.
- Generation (
quote): Use a templated macro to generate a newproc_macro2::TokenStream. - Output: Convert it back to
proc_macro::TokenStreamand return it to the compiler.
We will look at how syn parses code and how quote generates code.