Sub topic 2
Creating a proc-macro crate
This chapter assumes you are comfortable with Cargo packages and workspaces, and that you have used #[derive(Debug)] and similar attributes. You do not need to know macro_rules!. By the end you will have a working proc-macro crate, you will know which rules rustc enforces on it, and you will know how to structure it so its logic can be unit tested.
Why procedural macros need their own crate
A procedural macro is a Rust function that rustc loads and runs while it compiles another crate. Rustc therefore has to build the macro as a dynamic library for the machine doing the compiling (the host). It cannot be built as an ordinary library.
Cargo builds a crate that way only when you ask for it. You set proc-macro = true under [lib]. A crate with that setting is a proc-macro crate. It can export procedural macros and nothing else, so you cannot put a shared trait or helper struct in it. Those go in a second, ordinary crate.
The Cargo manifest
This manifest is the minimum for a proc-macro crate that parses Rust items.
[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 = trueturns the library into a proc-macro crate.- The
proc_macrocrate is supplied by the compiler. You never list it under[dependencies]. synparses tokens into a syntax tree. Its default features are enough forDeriveInput, which is what derive macros parse. Thefullfeature adds types such asItemFn, which attribute macros need.quoteturns code written in a template back into tokens.proc-macro2is a wrapper around the compiler's token types. The next sections explain why you want it.
Recommended workspace layout
Most derive macros ship as two crates. The runtime crate defines the trait and re-exports the derive. The macro crate implements it.
| Member | Kind | Contents |
|---|---|---|
| `hello_macro` | ordinary library | the `HelloMacro` trait and a re-export of the derive |
| `hello_macro_derive` | proc-macro crate | the `#[proc_macro_derive(HelloMacro)]` function |
| `app` | binary | code that uses `#[derive(HelloMacro)]` |
The workspace manifest lists all three.
[workspace]
resolver = "2"
members = ["hello_macro", "hello_macro_derive", "app"]The runtime crate depends on the macro crate and re-exports it.
[package]
name = "hello_macro"
version = "0.1.0"
edition = "2021"
[dependencies]
hello_macro_derive = { path = "../hello_macro_derive" }pub trait HelloMacro {
fn hello_macro();
}
pub use hello_macro_derive::HelloMacro;The trait and the derive both have the name HelloMacro. This is legal because traits and macros live in different namespaces. Users then write one import, use hello_macro::HelloMacro;, and get both.
The dependency runs in one direction only. hello_macro depends on hello_macro_derive, so the macro crate cannot depend back on the runtime crate. That is why generated code refers to the trait by an absolute path such as ::hello_macro::HelloMacro and does not import it.
By convention the macro crate is named after the runtime crate plus _derive or _macros. Publish it first, because the runtime crate's manifest needs a published version to depend on.
The three entry points
Each macro kind has its own attribute and function signature.
| Attribute | Signature | Invoked as |
|---|---|---|
| `#[proc_macro]` | `fn(TokenStream) -> TokenStream` | `name!(...)` |
| `#[proc_macro_attribute]` | `fn(TokenStream, TokenStream) -> TokenStream` | `#[name(args)] item` |
| `#[proc_macro_derive(Name, attributes(helper))]` | `fn(TokenStream) -> TokenStream` | `#[derive(Name)]` |
The attribute macro receives two streams: the arguments inside the parentheses, then the item it is attached to. A derive receives only the annotated type. Later chapters build each kind in full.
Rustc enforces three rules on these functions:
- They must be
pub. - They must be defined at the root of the crate, in
lib.rs, not in a submodule. - The crate may not export anything else. Private helper functions and modules are fine.
A first macro to check your setup
This is the smallest useful macro. It parses a string into tokens and returns them.
use proc_macro::TokenStream;
#[proc_macro]
pub fn make_answer(_item: TokenStream) -> TokenStream {
"fn answer() -> u32 { 42 }".parse().unwrap()
}In a consumer crate, add my_macros = { path = "../my_macros" } to the dependencies and call it.
use my_macros::make_answer;
make_answer!();
fn main() {
println!("{}", answer());
}Running this prints 42. The call make_answer!(); expanded into a function definition, and main could call it because items produced by a macro join the module like any other item. If this builds, your manifest and layout are correct.
proc_macro versus proc_macro2
The proc_macro::TokenStream type works only while rustc is running your macro. If you call code that uses it from a normal #[test], the test panics with "procedural macro API is used outside of a procedural macro".
proc_macro2::TokenStream has the same shape but works anywhere. syn and quote are built on it. The standard pattern keeps the proc_macro type at the edge. The entry point converts the incoming stream with .into(), calls an ordinary function that uses only proc_macro2 types, and converts the result back.
use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
#[proc_macro]
pub fn text_of(input: TokenStream) -> TokenStream {
expand_text_of(input.into()).into()
}
fn expand_text_of(input: TokenStream2) -> TokenStream2 {
let text = input.to_string();
quote! { #text }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn stringifies_tokens() {
let out = expand_text_of(quote! { a + b });
assert_eq!(out.to_string(), "\"a + b\"");
}
}text_of!(a + b) expands to the string literal "a + b". Because expand_text_of never touches proc_macro types, cargo test runs it directly. The same split keeps the larger macros in later chapters testable. The expand function in the FieldNames derive follows it too. You can also put tests in the crate's tests/ directory. Integration tests there import your macros like any other crate and run them through real expansion.
Host builds and dependencies
Cargo compiles a proc-macro crate and everything it depends on for the host, not for your --target. Two consequences follow:
- Cross-compiling an app does not break the macro crate, because it never runs on the target.
- Every dependency of the macro crate must build on the host. Avoid pulling in large crates you do not need, since
synwithfullis already a noticeable part of compile time.
Common errors
| What you see | Cause | Fix |
|---|---|---|
| `can't find crate for proc_macro` | `use proc_macro::...` in a crate without `proc-macro = true` | Add the `[lib]` setting |
| `proc-macro crate types currently cannot export any items other than functions tagged with #[proc_macro]...` | A `pub struct`, `pub fn`, or `pub trait` at the crate root | Make it private, or move it to the runtime crate |
| `functions tagged with #[proc_macro] must currently reside in the root of the crate` | Macro defined inside `mod` | Define it in `lib.rs` and call helpers from there |
| `unresolved import syn::ItemFn` | `full` feature not enabled | Add `features = ["full"]` |
| Test panics with "procedural macro API is used outside of a procedural macro" | A test called code that uses `proc_macro::TokenStream` | Move the logic into `proc_macro2` functions |
| Cargo reports a dependency cycle | The macro crate depends on the runtime crate | Remove that dependency and use absolute paths in generated code |
Exercise
You add pub struct Config { pub verbose: bool } to the lib.rs of a crate that has proc-macro = true. The crate stops compiling. Why does this fail, and where should Config live instead?
Show answer
A proc-macro crate may export only procedural macros, so a public struct is rejected. Put Config in an ordinary runtime crate that the application depends on. If the macro's generated code needs to refer to it, the macro can name it by absolute path, such as ::my_runtime::Config. The macro crate itself cannot depend on the runtime crate if the runtime crate depends on the macro crate.
Exercise
Why does the text_of example put its logic in expand_text_of instead of writing it inside the #[proc_macro] function?
Show answer
The #[proc_macro] function takes proc_macro::TokenStream, which works only during a real macro expansion. expand_text_of takes and returns proc_macro2::TokenStream, which works anywhere, so a normal #[test] can call it.