Sub topic 6
Writing a function-like macro
This chapter assumes you can write Rust structs and traits, you know how Cargo packages and dependencies work, and you have already set up a proc-macro crate with syn, quote, and proc-macro2. If not, review the chapters on crate setup and on syn and quote first.
What a function-like macro is
A function-like procedural macro is called like name!(...). It receives the tokens between the delimiters and returns tokens that replace the call. Unlike macro_rules!, the body is ordinary Rust code that runs at compile time. This lets you parse custom syntax and report precise errors.
You declare one with #[proc_macro]. The function takes one TokenStream and returns one TokenStream.
Step 1: Define the input syntax
Say we want add!(1, 2). The input is two integer literals separated by a comma. Model that as a struct and implement syn's Parse trait for it.
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(Pair { left, right })
}
}
#[proc_macro]
pub fn add(input: TokenStream) -> TokenStream {
let Pair { left, right } = parse_macro_input!(input as Pair);
quote! { (#left + #right) }.into()
}Each input.parse()? consumes the next piece of input and fails if it does not match the expected type. The compiler infers the type from the struct field. input.parse::<Token![,]>()? consumes a comma. You write the type explicitly because the result is discarded.
Step 2: Generate output
quote! { (#left + #right) } builds a token stream. The #left and #right markers interpolate the parsed literals. quote! produces a proc_macro2::TokenStream, so .into() converts it to the proc_macro::TokenStream the compiler expects.
Step 3: Use the macro
Add the macro crate as a dependency of another crate, then call it:
use my_macros::add;
fn main() {
let total = add!(1, 2);
println!("{total}");
}This prints 3. The call expands to (1 + 2), and the parentheses keep the result safe inside larger expressions, such as add!(1, 2) * 10.
How errors work
parse_macro_input! does the error handling for you. If parse returns an Err, the macro expands to a compile_error! call and returns early. The error shows up in the user's build at the location of the bad tokens.
For example, add!(1 2) fails at the missing comma, and add!("a", 2) fails because "a" is not a LitInt. You wrote no error code for either case. The parser reports both.
Common mistakes
- Returning the wrong
TokenStreamtype.quote!yieldsproc_macro2::TokenStream. Call.into()before returning it from the macro function. - Forgetting
proc-macro = true. Without it under[lib],#[proc_macro]is rejected. - Exporting other items. A proc-macro crate can only export procedural macros. Put shared helper types in a separate crate.
- Skipping the surrounding parentheses. Emitting
#left + #rightwithout them can change operator precedence at the call site. - Parsing too loosely. Accepting
TokenStreamand pulling tokens out by hand gives poor error messages. Define a type that implementsParseinstead.
Exercise
In the add! macro, what happens if a user writes add!(1, 2, 3), and why? Assume Pair::parse is exactly as shown above.
Show answer
It compiles to an error. parse_macro_input! parses the whole input as a Pair, and it requires the parser to consume every token. After Pair::parse reads 1, 2, the leftover , 3 causes an "unexpected token" error pointing at the extra input. The macro expands to compile_error! instead of producing code.
Exercise
Change the macro so it also accepts a three-number form such as add!(1, 2, 3) and expands to (1 + 2 + 3). What type would you use for the input, and which syn helper parses a comma-separated list?
Show answer
Use syn::punctuated::Punctuated<LitInt, Token![,]> as the input type and parse it with Punctuated::parse_terminated. Implement Parse for a wrapper struct that calls it. In quote!, repeat with a separator: quote! { (#(#items)+*) }, where items is an iterator over the parsed literals.