Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Macros

Procedural macros

Reference for Rust procedural macros: the three kinds (derive, attribute, function-like), proc-macro crates, TokenStream, and how they differ from macro_rules!.

A procedural macro is a Rust function that runs at compile time. It receives a stream of tokens, does any computation it likes, and returns a new stream of tokens that the compiler splices into your program. Unlike macro_rules!, which matches patterns, a procedural macro is ordinary Rust code, so it can parse input, inspect a struct's fields, build strings and report custom errors.

There are three kinds: derive macros (#[derive(MyTrait)]), attribute macros (#[my_attr(args)] on an item) and function-like macros (my_macro!(...)). All of them must live in their own crate marked proc-macro = true, which is why they cannot be defined and used in the same file.

Rust
// In a crate with `[lib] proc-macro = true` (read-only sketch):
use proc_macro::TokenStream;

#[proc_macro_derive(Describe)]
pub fn derive_describe(input: TokenStream) -> TokenStream {
    // parse `input`, return an `impl Describe for ...` block
    TokenStream::new()
}

Try it

The runner compiles a single file with no crates, so a real procedural macro cannot run here. The first example shows by hand what a derive macro produces: the impl block that #[derive(Debug)] and a custom derive would write for you. The second uses macro_rules! as a stand-in that generates the same kind of impl.

Rust What a derive generates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust A macro_rules stand-in

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

A proc-macro crate sets proc-macro = true under [lib] in Cargo.toml and exports functions with one of three attributes:

Rust
#[proc_macro]
pub fn name(input: TokenStream) -> TokenStream { /* name!(...) */ input }

#[proc_macro_derive(Name, attributes(helper))]
pub fn derive(input: TokenStream) -> TokenStream { /* #[derive(Name)] */ TokenStream::new() }

#[proc_macro_attribute]
pub fn name(args: TokenStream, item: TokenStream) -> TokenStream { /* #[name(args)] */ item }
Kind Invoked as Input Output
Function-like name!(tokens) The tokens inside the delimiters Replaces the whole call
Derive #[derive(Name)] The struct, enum or union definition Items added after the definition; the original stays
Attribute #[name(args)] The arguments, then the annotated item Replaces the annotated item

Errors and edge cases:

  • A derive can declare helper attributes, such as #[serde(rename = "x")], with attributes(helper). They are only legal on items that use the derive.
  • A panic inside the macro becomes a compile error, but a good macro reports errors with spans (for example compile_error! in the output) so the message points at the user's code.
  • Macros are hygienic only partially: procedural macros choose the span of each token, so identifiers can be made call-site or definition-site.

Usage notes

  • Separate crate. The macro crate is built for the host machine, and the crate that uses it depends on it like any library. Re-export it from the main crate so users add one dependency.
  • Common helpers. Most macros use the syn crate to parse tokens into a syntax tree, quote to build output with a template syntax, and proc-macro2 to test the code outside the compiler. These are crates, so they are not available on this site's runner.
  • Compile time. Procedural macros run on every build of the crate that uses them, and syn is large. Heavy use shows up in clean build times.
  • Choose the simplest tool. If a pattern-matching macro_rules! is enough, prefer it: it needs no extra crate, and it is easier to read and debug.
  • Debugging. cargo expand (a third-party subcommand) prints the code after expansion, which is the quickest way to see what a derive generated.
  • Stability. The three kinds are stable; the proc_macro crate API is available only inside proc-macro crates.