Sub topic 2
Creating a proc-macro crate
This chapter assumes you can read Cargo manifests and workspaces, and that you know the difference between macro_rules! and a #[derive(...)] attribute. You will set up the crate that holds procedural macros and check that it works from another crate.
Why a separate crate
The compiler loads a procedural macro as a compiled library and calls it while it compiles your code. That library has to be built for the machine running the compiler, not necessarily the target you are building for. Cargo handles this only for crates marked as proc-macro crates, so macros cannot live in an ordinary library or binary crate.
The manifest
Create the crate with cargo new my_macros --lib, then edit Cargo.toml:
[package]
name = "my_macros"
version = "0.1.0"
edition = "2021"
[lib]
proc-macro = true
[dependencies]
syn = { version = "2", features = ["full"] }
quote = "1"
proc-macro2 = "1"proc-macro = trueunder[lib]tells Cargo to build this library as a compiler plugin.synparses tokens into a syntax tree. Thefullfeature adds parsing for items such as functions. Without it you get only what derive macros need.quoteturns Rust-like templates back into tokens.proc-macro2is a wrapper around the compiler'sproc_macrotypes. It also works outside a macro call, so you can use it in unit tests and helper code.
The first macro
Put this in src/lib.rs:
use proc_macro::TokenStream;
#[proc_macro]
pub fn answer(_input: TokenStream) -> TokenStream {
"42".parse().unwrap()
}The proc_macro crate is built into the compiler, so it needs no entry in [dependencies]. A TokenStream can be parsed from a string, which makes this a quick way to test your setup. Later chapters replace this with syn and quote.
Using it from another crate
The easiest layout is a workspace with the macro crate and an app crate side by side:
[workspace]
members = ["my_macros", "app"]
resolver = "2"In app/Cargo.toml, add the dependency:
[dependencies]
my_macros = { path = "../my_macros" }Then call the macro from app/src/main.rs:
fn main() {
let n: i32 = my_macros::answer!();
println!("{n}");
}Running cargo run -p app prints 42.
Rules for proc-macro crates
- The crate may export only procedural macros. A
pub fn helper()orpub structat the top level is a compile error. Keep helpers private, or move them into a normal crate. - A macro cannot be used by the crate that defines it. Test it from another crate, such as an
appcrate or the crate'stests/directory. - The
proc_macrotypes panic when used outside a macro invocation. Useproc_macro2in code you want to unit test.
Common errors
| Symptom | Cause |
|---|---|
| `functions tagged with #[proc_macro] must be pub` | The macro function is not `pub`. |
| `proc-macro crate types currently cannot export any items other than functions tagged with #[proc_macro]...` | A non-macro item is `pub` in the crate root. |
| `can't find crate for proc_macro` | The crate lacks `proc-macro = true`. |
| `no method named ...` on a `syn` type | The `full` feature is missing or `syn` is the wrong major version. |
Exercise
You add pub fn parse_helper() {} to the root of a crate that has proc-macro = true. What happens, and what are two ways to fix it?
Show answer
The build fails because a proc-macro crate may export only procedural macros. Fix it by making the function private (remove pub), or by moving it into a separate normal library crate that the proc-macro crate depends on.