Rust Procedural Macros Explained: Serde, Clap, SQLx, and Writing Your Own with syn + quote
The speaker explains that Rust procedural macros are not just for auto-generating code but for providing expressive, accessible APIs, and previews a talk covering ecosystem “gems,” how procedural macros work, and building simple macros.
Using a Point example, they show how derive macros implement traits like Debug and how tools like cargo-expand reveal generated implementations and compiler notes.
They highlight three macro-driven crates: serde for serialization/deserialization with field renaming via attributes, clap for deriving command-line interfaces and generating help output from annotated structs/enums and doc comments, and sqlx for compile-time checked SQL queries that can error when columns don’t exist, with discussion about added build steps, safety/security concerns, and CI preparation.
The talk distinguishes declarative macros (pattern-matching like vec!) from procedural macros, introduces parsing to an AST and code generation, and explains the three procedural macro types: function-like, derive, and attribute macros that can replace items. They then build example procedural macros using syn (parsing to AST) and quote (generating tokens), including a macro that adds a greeting function and a constructor-generating macro using quote iterators and repetition, plus error handling via Result and syn::Error with spans converted to compile errors for unsupported struct forms (tuple/unit).
The speaker points to additional learning resources, mentions a personal learning project (EngCon) that uses constraints to generate validated types with try_from/try_into error messages, and concludes with a Q&A on nesting macros.
00:00 Procedural Macros as Powerful APIs (Intro & Roadmap)
02:01 Running Example: Derive Macros, Debug vs Display + cargo-expand
05:42 Gem #1: Serde — Zero-Boilerplate Serialization with Macro DSLs
08:26 Gem #2: Clap — Derive-Based CLI UX and Help Generation
12:26 Gem #3: SQLx — Compile-Time Checked SQL Queries (and the Tradeoffs)
15:06 Procedural vs Declarative Macros: How vec! Works
17:08 How Procedural Macros Work: Parsing to AST + 3 Macro Types
22:05 Tools of the Trade: syn & quote + First “Hello” Attribute Macro
26:15 Building a Constructor Macro: Iterators, Repetition, and Codegen Patterns
28:41 Error Handling in Proc Macros: syn::Error, Spans, and Compile Errors
32:30 Resources, Practice Mindset, and a Real Project Example (EngCon)
34:22 Q&A: Macro Nesting, Limits, and Attribute vs Derive Behavior
37:19 Wrap-Up & Thanks