Sub topic 4
Parsing input with syn
This chapter shows how syn turns the raw tokens a procedural macro receives into typed Rust values you can inspect. It assumes you can read Rust traits and generics, know how a proc-macro crate is set up (proc-macro = true in [lib]), and know that a macro function takes a TokenStream and returns one.
Why parse at all
A procedural macro receives a proc_macro::TokenStream. It is a flat sequence of tokens: identifiers, punctuation, literals, and delimited groups. It has no structure you can query. You could walk it by hand and match on TokenTree values, but that code is long and fragile, and its error messages are poor.
The syn crate parses tokens into a syntax tree. A struct definition becomes a DeriveInput with an ident, generics, and data. A function becomes an ItemFn with a sig and a block. For custom syntax, you write your own type and implement the Parse trait.
Which syn types to parse into
Pick the type that matches what the macro is attached to.
| Macro kind | Input | Typical syn type |
|---|---|---|
| Derive | A struct, enum, or union | `DeriveInput` |
| Attribute | Any item, such as a function | `ItemFn`, `ItemStruct`, or `Item` |
| Function-like | Whatever syntax you define | Your own type implementing `Parse` |
Cargo features matter here. The default features of syn include derive, which gives you DeriveInput. Parsing functions, impl blocks, and other items needs the full feature. If ItemFn is missing from syn, the cause is almost always that features = ["full"] is absent from Cargo.toml.
The parse_macro_input! macro
parse_macro_input! converts the incoming TokenStream into a syn type. If parsing fails, it returns early from your macro function with a compile_error! expansion, so you never write error handling for the failed parse.
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, DeriveInput};
#[proc_macro_derive(TypeName)]
pub fn type_name(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let name = &input.ident;
let text = name.to_string();
let (ig, tg, wc) = input.generics.split_for_impl();
quote! {
impl #ig #name #tg #wc {
pub fn type_name() -> &'static str {
#text
}
}
}
.into()
}The macro form parse_macro_input!(input as DeriveInput) requires the target type to implement Parse. Every syn syntax node does. Your own types can too.
Inspecting a DeriveInput
DeriveInput has four parts you will use constantly.
identis the type's name, anIdent.genericsholds type parameters, lifetimes, and the where clause.attrsis the list of attributes such as#[doc]or custom helpers.datais an enum with the variantsData::Struct,Data::Enum, andData::Union.
A struct's Fields can be Named, Unnamed (a tuple struct), or Unit. You almost always need to match on both levels:
use syn::{Data, DeriveInput, Fields};
fn describe(input: &DeriveInput) -> String {
match &input.data {
Data::Struct(s) => match &s.fields {
Fields::Named(f) => format!("struct with {} named fields", f.named.len()),
Fields::Unnamed(f) => format!("tuple struct with {} fields", f.unnamed.len()),
Fields::Unit => "unit struct".to_string(),
},
Data::Enum(e) => format!("enum with {} variants", e.variants.len()),
Data::Union(_) => "union".to_string(),
}
}Handle every case, or return an error for the ones you do not support. Calling unwrap() on a field's ident panics for tuple structs, and a panic produces a confusing compiler message.
Implementing Parse for custom syntax
A function-like macro defines its own input grammar. You describe the grammar by implementing Parse on a struct. The method receives a ParseStream, a cursor over the tokens that advances as you parse.
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()
}Three details are worth knowing:
input.parse()?infers the type to parse from the variable it is assigned to. Hereleftis used as a field of typeLitInt, so Rust infersLitInt.Token![,]is a macro that names the comma token type. Other examples areToken![=],Token![fn], andToken![->].- After your
parsemethod returns,parse_macro_input!checks that no tokens remain. Foradd!(1, 2, 3)the user sees an "unexpected token" error pointing at the extra comma. You do not need to check this yourself.
Lists with Punctuated
Comma-separated lists are common. Punctuated<T, P> stores values of type T separated by tokens of type P. The parse_terminated method on ParseStream fills one. It takes a parser function and a separator token:
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 {
items: Punctuated<LitInt, Token![,]>,
}
impl Parse for Numbers {
fn parse(input: ParseStream) -> syn::Result<Self> {
let items = input.parse_terminated(LitInt::parse, Token![,])?;
Ok(Numbers { items })
}
}
#[proc_macro]
pub fn sum(input: TokenStream) -> TokenStream {
let Numbers { items } = parse_macro_input!(input as Numbers);
let items = items.iter();
quote! { (0 #(+ #items)*) }.into()
}sum!(1, 2, 3) expands to (0 + 1 + 2 + 3). parse_terminated accepts an optional trailing comma and an empty list, so sum!() expands to (0). A Punctuated value iterates over its values only. Use pairs() if you need the separators as well.
Choosing between alternatives
When the input can take several shapes, look ahead without consuming tokens. The lookahead1 helper tries several peek checks, and when none match it builds an error that lists every expected alternative:
use syn::parse::{Parse, ParseStream};
use syn::{LitInt, LitStr};
enum Value {
Int(LitInt),
Str(LitStr),
}
impl Parse for Value {
fn parse(input: ParseStream) -> syn::Result<Self> {
let lookahead = input.lookahead1();
if lookahead.peek(LitInt) {
Ok(Value::Int(input.parse()?))
} else if lookahead.peek(LitStr) {
Ok(Value::Str(input.parse()?))
} else {
Err(lookahead.error())
}
}
}Given true as input, the error reads "expected integer literal or string literal". You get a good message without writing any text. For a plain one-token decision, input.peek(Token![,]) returns a bool and also does not consume anything.
Errors during parsing
Every parse step returns syn::Result<T>. Use ? to pass failures up. The error carries a span, which is the source location of the offending token, so the compiler underlines the right place in the user's code. Panics and unwrap() lose that location. Reporting your own errors is covered in a later chapter. For now, keep one rule: never panic on bad user input.
Testing a parser without the compiler
A proc_macro::TokenStream can only be created while the compiler is running a macro. The proc_macro2 crate wraps it so that syn code also works in ordinary tests. syn::parse_str parses a string through proc_macro2, so you can unit test your Parse implementations directly:
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_pair() {
let pair: Pair = syn::parse_str("1, 2").unwrap();
assert_eq!(pair.left.base10_parse::<u32>().unwrap(), 1);
assert_eq!(pair.right.base10_parse::<u32>().unwrap(), 2);
}
#[test]
fn rejects_missing_comma() {
assert!(syn::parse_str::<Pair>("1 2").is_err());
}
}Note that a function marked #[proc_macro] cannot be called from these tests. Keep the real logic in functions that take and return proc_macro2 types, and keep the exported macro function thin.
Common errors
ItemFnnot found. Enable thefullfeature ofsyn.- "expected one of ..." errors on valid-looking input. You probably consumed a token too early or too late. Parse in the same order the tokens appear.
- Panics on tuple or unit structs.
Fields::UnnamedandFields::Unithave no field names. Match on all variants. - Using
proc_macro::TokenStreaminside helper functions. Preferproc_macro2::TokenStreamthere. It works in tests and inquote!. - Parsing too narrowly. Parsing into
LitIntrejects a constant likeN. If you need any expression, parse intosyn::Expr.
Exercise
You write impl Parse for Settings that parses name = "x" using input.parse::<Ident>()?, input.parse::<Token![=]>()?, and input.parse::<LitStr>()?. A user writes settings!(name = "x", extra). What happens, and why?
Show answer
The macro fails with a compile error pointing at the comma after "x". Your parse method returns after the string literal and leaves , extra unread. parse_macro_input! then finds leftover tokens and reports "unexpected token". To accept a list of settings, parse a Punctuated<Setting, Token![,]> with parse_terminated instead.