The syn AST
The syn crate provides a complete, robust parser that parses a raw
TokenStream into structured, AST types that can represent any element of Rust
code. syn has a wide API surface, but it should feel relatively
straightforward as it mirrors the structure of Rust syntax itself. Here we
illustrate the use of syn for a Derive macro:
use proc_macro::TokenStream;
use syn::{DeriveInput, parse_macro_input};
#[proc_macro_derive(MyDerive)]
pub fn my_derive(input: TokenStream) -> TokenStream {
// Parse raw tokens into a structured `DeriveInput` AST:
let ast = parse_macro_input!(input as DeriveInput);
// Inspect struct metadata:
let struct_name = ast.ident;
let generics = ast.generics;
// ...
}
DeriveInput: The standard AST structure for a struct, enum, or union.parse_macro_input!: A specialized macro helper provided bysynto easily parse the input token stream. It automatically handles compile-time syntax errors if the input is malformed. This macro accepts the name of the type into which to parse the token stream after anasseparator, notation that resembles a Rust cast.
Explore DeriveInput, which three main components:
ident: The name of the struct/enum.generics: Generic parameters, lifetemes, and constraints.data: An enum containingsyn::DataStruct,syn::DataEnum, orsyn::DataUnion, which lets you iterate over variants and fields.