
Understand it
A procedural macro is compiled for and runs on the build host, then emits tokens for the target crate. It cannot depend on target runtime state and should emit spans that point errors back to useful input.
Procedural macros run as host tools during compilation. They receive token input from the crate being built and return token output that the compiler later checks for the target. If you cross-compile from a Mac to a phone, the macro runs on the Mac; generated program code targets the phone. This is why host dependencies and target dependencies can have different requirements, and why a restricted on-device compiler may not support arbitrary proc-macro crates. Keep the generated program independent of accidental host-only paths or environment details.
Good diagnostics are part of the macro's public API. A derive that rejects an unsupported enum should point to the enum or offending field rather than failing with a cryptic token-stream panic. Parse input using an appropriate syntax library when available, preserve useful spans, and add compile-fail examples for invalid forms. Avoid doing network or filesystem work at expansion time unless the build contract explicitly depends on it; such hidden inputs make builds difficult to reproduce. Test the macro in a separate consumer crate, including renamed dependencies and generic types. If a small trait implementation is clearer without generation, prefer it. A proc macro should remove mechanical repetition while making the generated contract easier, not harder, to audit.
A procedural macro is code executed during the build, so dependency updates to that crate deserve the same review as other build tooling. Pin versions where reproducibility matters and avoid hidden environment-dependent output. If the macro emits code with an unexpected import, prefer absolute paths or documented helper crates. The generated API should still be understandable without reading the macro implementation.
Read the code
// Host process:
#[proc_macro_derive(Builder)]
pub fn derive(input: TokenStream)
-> TokenStream {
expand(input)
}The function runs in the compiler's host process, and the tokens it returns join the crate being built.
Practice starter
// my_macros/src/lib.rs
use proc_macro::TokenStream;
#[proc_macro]
pub fn host_os(_input: TokenStream) -> TokenStream {
format!("{:?}", std::env::consts::OS).parse().unwrap()
}
// app/src/main.rs
fn main() {
println!("{}", my_macros::host_os!());
}Try it
Predict what host_os! prints when app is cross-compiled on a Mac for another platform. Then change the macro so the generated code reads std::env::consts::OS at run time.
What success looks like: You can say which value belongs to the build host and which to the target.
Check your understanding
Where does a proc macro execute?
Reveal the answer
- On the build host
- Inside the target app
- In Cargo.toml
host_os! runs on the build host during compilation and pastes its answer into the target program as a string literal.
Go deeper
Common misconception: “A proc macro runs inside the app, so it can see the target's runtime state.”
A procedural macro is compiled for and runs on the build host, then emits tokens for the target crate. Only those emitted tokens reach the app.
- Find the attribute:
#[proc_macro_derive(Builder)]registersderiveas the function the compiler calls for#[derive(Builder)]. - Follow the tokens:
derivereceives the item's tokens as aTokenStreamand hands them toexpand, a helper in the same host crate. - Cross the boundary: The
TokenStreamit returns becomes code compiled for the target.deriveandexpandthemselves are not part of the target program.
Transfer challenge: Make expand reject unsupported input by returning compile_error! tokens with a message. Predict which crate reports the error and at which point in the build.
Connections
- Token Trees: Match Rust syntax as nested tokens, not raw text
- Raw Pointers: Represent an address without borrow guarantees
Learn this lesson with AI
Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.
I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools. Lesson: Proc-Macro Boundaries (courseId "systems", lessonId "proc-macro-boundaries") Link: https://crabrix.com/learn/systems/proc-macro-boundaries/ Goal: A procedural macro is compiled for and runs on the build host, then emits tokens for the target crate. Practice: give me the lesson's exercise (crabrix_academy_get_exercise); I will write and run the code in Crabrix. Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.