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 and quote
  • 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.

3.1 Basic setup of a procedural macro project

3.2 Analyzing the procedural macro setup

3.3 Generating output

3.4 Experimenting with our code

3.5 cargo expand

3.6 The same macro—without syn and quote

3.7 From the real world

Exercises

Summary