Sub topic 1
Declarative Macros versus Procedural Macros
Prerequisites
This chapter assumes you can read Rust structs, traits, generics, and macro_rules! macros. You should also know how Cargo packages and dependencies work.
Two kinds of macros
A declarative macro uses pattern matching to transform tokens. You write its rules with macro_rules!, and Rust selects a matching rule:
macro_rules! make_pair {
($a:expr, $b:expr) => {
($a, $b)
};
}A procedural macro is a Rust function that runs during compilation. It receives a TokenStream, which is a sequence of Rust tokens, and returns another TokenStream. Procedural macros can inspect syntax and generate code programmatically.
Rust has three procedural macro forms:
- Function-like macros, invoked as
name!(...). - Derive macros, invoked as
#[derive(Name)]on a type. - Attribute macros, invoked as
#[name]on an item such as a function.
Choose a function-like macro for custom input syntax, a derive macro for generating implementations from a type, and an attribute macro for transforming an existing item.
Creating a proc-macro crate
A procedural macro must live in a crate marked with proc-macro = true. syn parses tokens into syntax trees, and quote generates tokens.
[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"A macro crate is normally separate from the application that uses it. This separation lets Cargo compile the macro before compiling the application.
Tokens in, tokens out
TokenStream preserves Rust syntax without requiring you to parse every token yourself. For nontrivial macros, parse it with syn. The parsed representation gives you typed values and useful compiler errors.
This function-like macro accepts two integer literals and generates an addition expression:
use proc_macro::TokenStream;
use quote::quote;
use syn::parse::{Parse, ParseStream};
use syn::{parse_macro_input, LitInt, Token};
struct Pair {
left: LitInt,
right: LitInt,
}
impl Parse for Pair {
fn parse(input: ParseStream) -> syn::Result<Self> {
let left = input.parse()?;
input.parse::<Token![,]>()?;
let right = input.parse()?;
Ok(Self { left, right })
}
}
#[proc_macro]
pub fn add(input: TokenStream) -> TokenStream {
let Pair { left, right } = parse_macro_input!(input as Pair);
quote! { (#left + #right) }.into()
}parse_macro_input! converts invalid input into a compiler error. quote! then turns the parsed values back into generated Rust tokens.
Exercise
Which procedural macro form is appropriate for generating a trait implementation from a struct definition?
Show answer
A derive macro, because it receives the annotated type and can generate an implementation for it.