Providing custom derives
You might have looked at #[derive(Debug)]
and assumed it's some weird compiler magic. It is not. It is a so-called procedural macro, that is, a macro that doesn't simply expand at compile time but instead runs at compile time. This way, you can inject code into the actual compilation process. The most useful application for this is creating custom derives, with which you can generate new code based on the analysis of existing code.
Getting started
This recipe will operate with an Abstract Syntax Tree, or AST. It is a tree-like representation of a language's elements in relation to each other. In this recipe, we (that is, a cool crate called syn
) will parse our entire program into a single deep struct
.
How to do it...
Create a new sub-crate for the custom derive with
cargo new chapter-five-derive
.- Open the newly generated
chapter-five-derive/Cargo.toml
. - Add this directly above the
[dependencies]
section of the file in order to mark the crate as a procedural macro crate:
...