Official documentation for writing (procedural) macros

#1

Where is the official documentation (up-to-date version) on writing procedural macros?

So far I have found:

However, in the second edition of the book, the chapter about the macros is missing and the reference says it is very incomplete.

I would like to write macros using the ecosystem of proc-macro2, but I am not sure where to find an official up-to-date guide.

1 Like
#2

The book is there to cover the basics; the basics boil down to “use syn and quote.” Of course, doing more is more complex than that. We don’t have anyone with the experience and time to write such a thing, however, and so that’s what we’ve got.

#3

But in the second edition, the chapter has the section about advanced features removed (https://doc.rust-lang.org/book/second-edition/ch19-00-advanced-features.html). I know that the old version is still valid, but is probably outdated. What is supposed to replace Chap.19 of the book?

#4

Note that says that the second edition has been removed, not that specific chapter.

https://doc.rust-lang.org/stable/book/ch19-06-macros.html is the latest version of the book, and the section on the macro system.

#5

My bad :frowning:. Thank you for clarifications

1 Like
#6

No worries!

#7

While it’s not a documentation, if you want to get started with them, something like this worked for me:

  • First, try writing few ordinary macros, make sure they work well ‒ eg learn the tricks like using full paths to symbols, etc. There are docs for that out there.
  • Read the api docs of syn to get the feeling of the crate.
  • Find a procedural macro out there that does something similar to what you want to do and read through the real code.
  • Decide how your input and output should look like ‒ write the code that the macro should generate manually first.
  • Roll up your sleeves and dig in writing your own and don’t give up ‒ and check the resulting code with cargo expand.
4 Likes