Macros & Metaprogramming · 19 min · free lesson

Procedural Macros

A procedural macro is a compiler plugin written in Rust.

Core idea

Proc macros execute at compile time, so they need a host-native build.

Diagram for Procedural Macros: a Rust code example flows to the lesson rule and the key observation.
A separate crate, marked as a proc-macro, built for the host.

Understand it

It receives a TokenStream and returns one, running as a real program during compilation — which is why it lives in its own crate compiled for the host machine. That host requirement is why a constrained device-local toolchain may not support arbitrary procedural macro crates; cross-compilation normally runs the macro on the build host.

A procedural macro is a Rust program that runs while another crate is being compiled. The compiler gives it tokens; it parses them, generates new tokens, and returns them to the caller's compilation. Derive, attribute, and function-like procedural macros differ in invocation shape, but all need a host-executable macro crate. The expansion is then checked as ordinary Rust code. This makes proc macros powerful for repetitive APIs and also makes their diagnostics, build time, and dependency chain part of the developer experience.

The host/target distinction matters for cross-compilation. A laptop may run the macro while producing code for a phone or WASM target. On-device compilation can support proc macros only if it can build or run compatible host artifacts and satisfy the required loading model; do not assume every constrained compiler can. Keep generated code independent of hidden target runtime state. In the example, the Hello derive should parse the input type, reject unsupported forms with a useful span, and emit an impl using stable paths. Try a trivial derive on a struct and then on an enum; make the unsupported form produce a clear compile error. Prefer a normal trait implementation when the implementation is short and explicit. Use generation when it removes repeated, mechanical code without hiding important behavior.

Generated code can fail to compile even when the macro itself runs successfully. Test the emitted implementation in a consumer crate and inspect the compiler errors there. A macro panic is poor feedback; report a structured compile error at the input span when possible. Avoid depending on the caller having a particular use statement unless the API explicitly documents it.

Read the code

# my-derive/Cargo.toml
[lib]
proc-macro = true

// my-derive/src/lib.rs
use proc_macro::TokenStream;

#[proc_macro_derive(Hello)]
pub fn derive_hello(
    input: TokenStream,
) -> TokenStream {
    // parse input, generate an impl, return it
    TokenStream::new()
}

A separate crate, marked as a proc-macro, built for the host.

Practice starter

use serde::Serialize;

#[derive(Serialize)]
struct Config { port: u16 }

Try it

Explain why a proc macro cannot run inside Crabrix.

What success looks like: You can name the host-compilation requirement as the reason.

Check your understanding

What does that derive need at build time?

Reveal the answer
  1. Only the serde crate as a normal dependency
  2. A proc-macro crate compiled for and run on the host
  3. Nothing special — derives are built into rustc

serde_derive is a program the compiler runs, not just a library it links.

Go deeper

Common misconception: “A derive is just a library item, so it needs nothing beyond a normal dependency.”

Proc macros execute at compile time, so they need a host-native build. #[derive(Serialize)] runs serde_derive as a program while your crate compiles.

  1. Mark the crate: proc-macro = true under [lib] tells Cargo to build this crate as a compiler plugin for the host, not the target.
  2. Receive the tokens: derive_hello takes the TokenStream of the item marked #[derive(Hello)], and whatever it returns is added after that item.
  3. Read the output: This sample returns an empty TokenStream, so the derive compiles and adds no impl. A real macro parses the input and generates one.

Transfer challenge: Make derive_hello return "impl Hello for Config {}".parse().unwrap(), then put the derive on a second struct. Predict the compiler error and say what the macro must read from its input.

Connections

  • macro_rules!: Pattern-based code generation
  • cfg & Features: Compiling different code per target
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: Procedural Macros (courseId "systems", lessonId "proc-macros")
Link: https://crabrix.com/learn/systems/proc-macros/
Goal: Proc macros execute at compile time, so they need a host-native build.
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.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.