Sub topic 4
Parsing input with syn
This chapter assumes you can set up a proc-macro crate (the previous chapters covered that). It also assumes you know that a macro receives a TokenStream. Here you will turn that raw token stream into typed Rust values using the syn crate.
Why parse at all
A TokenStream is a flat sequence of tokens: identifiers, punctuation, literals, and groups in brackets. You can loop over it by hand, but you would have to check every comma and every delimiter yourself. syn does that work. It provides data types for Rust syntax, such as ItemFn, DeriveInput, LitInt, and Ident, and a parser that fills them in.
The Parse trait and parse_macro_input!
Every syn type implements the Parse trait. The parse_macro_input! macro runs it on the incoming TokenStream. The syntax is parse_macro_input!(input as Type). If parsing fails, the macro returns early with a compile_error!, so the user sees a normal compiler message.
For built-in syntax you only name the type. To parse a whole function, use ItemFn. To parse the type under a #[derive], use DeriveInput.
use proc_macro::TokenStream;
use syn::{parse_macro_input, DeriveInput};
#[proc_macro_derive(Inspect)]
pub fn inspect(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let _name = &input.ident; // the type's name
let _generics = &input.generics; // its generic parameters
let _data = &input.data; // struct, enum, or union body
TokenStream::new()
}DeriveInput has ident, generics, attrs, vis, and data. The data field is an enum Data with variants Struct, Enum, and Union, so you match on it to find fields.
Parsing your own syntax
Function-like macros often accept custom syntax. You describe it by implementing Parse for your own struct. Inside parse, you consume tokens from a ParseStream in order.
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()
}Reading the parse method line by line:
input.parse()?reads oneLitInt. Rust infers the type from the field it is assigned to.input.parse::<Token![,]>()?requires a comma and discards it. TheToken!macro names punctuation and keywords as types.- The second
input.parse()?reads the right-hand integer.
Calling add!(1, 2) expands to (1 + 2). Calling add!(1 2) fails at the comma step, and the compiler reports "expected ," at that location. You wrote no error handling, because ? passes the syn::Error upward.
Checking ahead
Sometimes the next token decides what to parse. input.peek(Token![,]) returns a bool without consuming anything, and input.is_empty() tells you whether tokens remain. Use them for optional parts and for lists of unknown length.
Common errors
- Missing
fullfeature.ItemFn,Item, andExprvariants for statements needsyn = { version = "2", features = ["full"] }. Without it, those types do not exist and you get an unresolved import.DeriveInputworks with the defaultderivefeature. - Mixing
proc_macroandproc_macro2.parse_macro_input!takes the compiler'sproc_macro::TokenStream. Functions you write and unit-test separately should useproc_macro2::TokenStream. - Unwrapping instead of
?. Calling.unwrap()insideparsemakes the compiler show a panic message instead of a pointed error.
Exercise
In the Pair parser, what happens if a user writes add!(1, 2, 3), and which part of your code detects it?
Show answer
Compilation fails with an "unexpected token" error pointing at the extra comma. The check is done by parse_macro_input!, which verifies that the whole input was consumed after Pair::parse returns. Your parse function does not need extra code for it.