Sub topic 6
Writing a function-like macro
Prerequisites
This chapter assumes you have read the earlier chapters on setting up a proc-macro crate, on TokenStream, and on syn and quote. You should be comfortable with Rust traits, Result, and Cargo dependencies. If macro_rules! is familiar, that helps, but it is not required.
What a function-like macro is
A function-like procedural macro is invoked like a macro_rules! macro, as name!(...), name![...] or name!{...}. The difference is what runs behind it. Instead of pattern-matching rules, the compiler calls a Rust function in your proc-macro crate. That function receives the tokens between the delimiters and returns the tokens that replace the whole invocation.
The signature is always the same:
#[proc_macro]
pub fn name(input: TokenStream) -> TokenStreamThe attribute is #[proc_macro], with no arguments. The function name becomes the macro name. The input does not include the macro name or the outer delimiters, only what is inside them.
Function-like macros suit cases where you want custom syntax or logic that macro_rules! handles badly. Examples are parsing a DSL, validating a literal at compile time, or generating several items from a small description.
The crate setup
The Cargo manifest is the same one used in the setup chapter. The [lib] section must contain proc-macro = true, and syn needs the full feature only if you parse items such as functions. For the macros in this chapter, syn needs no extra features beyond the defaults, but keeping full is harmless.
[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 proc-macro crate can export only procedural macros. You cannot put ordinary public functions or types in it for other crates to use. If you need shared runtime code, put it in a separate library crate.
The working model
A function-like macro does three things, in order:
- Parse the incoming
TokenStreaminto a Rust data structure you define. - Check or transform that data.
- Build the output tokens with
quote!and convert them back to aTokenStream.
Parsing custom syntax with the Parse trait
Suppose we want add!(1, 2) to expand to (1 + 2). The input grammar is two integer literals separated by a comma. We describe that grammar by implementing syn::parse::Parse for a struct.
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()
}Points worth understanding:
ParseStreamis a cursor over the tokens. Eachinput.parse::<T>()consumes tokens as aTor returns an error.- The types of
leftandrightare inferred from the struct fields, soinput.parse()?needs no turbofish there. Token![,]is a macro that names the comma token type. The comma has no value you need, so the result is discarded.parse_macro_input!(input as Pair)converts the compiler'sTokenStreaminto aproc_macro2::TokenStream, runs yourParseimplementation, and requires that all input is consumed. If parsing fails, it returns early from your function with the error already turned into acompile_error!invocation.#leftand#rightinquote!interpolate the parsed values.LitIntimplementsToTokens, so it prints back as the original literal..into()convertsproc_macro2::TokenStreamtoproc_macro::TokenStream.
Using it from another crate (or from an integration test in tests/):
use my_macros::add;
fn main() {
let total = add!(1, 2);
println!("{total}");
}This prints 3. Because the macro wraps its output in parentheses, add!(1, 2) * 10 is 30, not 21. Wrapping expression output in parentheses is a good habit, since the replacement is spliced into the surrounding code token by token.
Accepting a variable number of arguments
Fixed-shape input is easy. Repetition uses syn::punctuated::Punctuated, a list of values with separators between them. The next macro, sum!, accepts any number of integer literals, including none.
use proc_macro::TokenStream;
use quote::quote;
use syn::parse::{Parse, ParseStream};
use syn::punctuated::Punctuated;
use syn::{parse_macro_input, LitInt, Token};
struct Numbers(Punctuated<LitInt, Token![,]>);
impl Parse for Numbers {
fn parse(input: ParseStream) -> syn::Result<Self> {
Ok(Numbers(Punctuated::parse_terminated(input)?))
}
}
#[proc_macro]
pub fn sum(input: TokenStream) -> TokenStream {
let Numbers(list) = parse_macro_input!(input as Numbers);
let items = list.iter();
quote! { (0 #(+ #items)*) }.into()
}If you keep both macros in one lib.rs, merge the duplicate use lines.
parse_terminated accepts an optional trailing comma, so sum!(1, 2, 3,) is valid. The repetition #(+ #items)* emits + item once per element. sum!(1, 2, 3) becomes (0 + 1 + 2 + 3), and sum!() becomes (0).
Reporting errors
The user sees parse failures as compiler errors, and syn already supplies sensible messages and locations:
| Invocation | Result |
|---|---|
| `add!(1 2)` | error: expected `,` |
| `add!(1, "x")` | error: expected integer literal |
| `add!(1, 2, 3)` | error: unexpected token |
Each error points at the exact token that caused it, because every token carries a span, a record of where it came from in the source. When you detect a problem that parsing cannot catch, create the error yourself and attach it to the most relevant tokens:
use syn::{Error, LitInt};
fn check_small(lit: &LitInt) -> syn::Result<u8> {
lit.base10_parse::<u8>()
.map_err(|_| Error::new(lit.span(), "value must fit in a u8"))
}Use Error::new_spanned(tokens, message) to underline a whole group of tokens. In the macro function, convert an error into output with err.into_compile_error().into(). Never call panic! or unwrap() on user input: a panic gives a vague "proc macro panicked" message with no useful location.
Edge cases and common errors
- Using the macro in its own crate. A proc-macro crate cannot call its own macros in its own non-test code. Put examples and tests in
tests/(an integration test), or in a separate crate. - Missing
pub. Every#[proc_macro]function must bepub. Otherwise the compiler rejects the crate. - Type suffixes.
add!(1u8, 2i32)expands to(1u8 + 2i32), and rustc then reports a type mismatch at the expansion site. If you care, compareleft.suffix()andright.suffix()in your parser and report your own error. - Negative numbers.
-1is two tokens, a minus sign and a literal.LitIntdoes not accept it. If you want signed input, parsesyn::Exprinstead, or check forToken![-]first withinput.peek. - Unused input. If your
Parseimplementation stops early,parse_macro_input!reports "unexpected token" for the rest. This is usually what you want. - Delimiter choice. The compiler allows
add!(..),add![..]andadd!{..}. Your macro cannot tell which was used. In statement position, a macro invoked with braces needs no trailing semicolon, but one invoked with parentheses does. - Hygiene. Identifiers created with
quote!use the call site's context by default, so a local variable you introduce in the output can clash with or capture names from the user's code. Prefer fully qualified paths such as::std::println!, and give generated locals unusual names. - Everything is tokens. The macro runs before type checking. It cannot know the type of an expression, only what the tokens look like.
Exercise
Why does parse_macro_input!(input as Pair) let you skip writing error-handling code in the add function, and what happens if the user writes add!(1, 2, 3)?
Show answer
The macro runs Pair::parse and, on Err, returns early from the function with the error converted into a compile_error! token stream, so the user sees a normal compiler error at the offending token. It also requires that all input is consumed. With add!(1, 2, 3), Pair::parse stops after the second literal, so the leftover , 3 produces an "unexpected token" error pointing at the extra comma.
Exercise
Change sum! so that it rejects any literal that does not fit in a u32, with an error pointing at that literal. Which syn method parses the value, and which constructor attaches the span?
Show answer
Call lit.base10_parse::<u32>() on each LitInt and turn failures into syn::Error::new(lit.span(), "value must fit in a u32") (or use the error base10_parse itself returns, which already carries the literal's span). Do this inside the Parse implementation or in a helper that returns syn::Result, then return err.into_compile_error().into() from the macro function when it fails.