3 A “Hello, World” procedural macro
This chapter covers
- Setting up a procedural macro
- Getting the name of a struct by parsing a stream of tokens
- Generating hardcoded output
- Using variables in generated code
- Inspecting generated code with
cargo expand
- Writing a macro without help from
syn
andquote
- Understanding how Rust’s internal macros are special
We now come to the meat of our book: procedural macros. As we explained earlier, both procedural and declarative macros are forms of metaprogramming and allow you to manipulate and extend code. But they go about it differently. Declarative macros offer a domain-specific language (DSL) that allows you to generate code based on a combination of matchers and transcribers. Procedural macros, on the other hand, deal with lower-level information. They receive a stream of tokens containing every detail of the code you want to work with.