liveBook · Manning

Syn

As explained in Idiomatic Rust

syn is a Rust library for parsing source code into syntax-tree representations.

syn parses Rust token streams into syntax structures that procedural macros can inspect. It offers a higher-level alternative to handling raw tokens directly. section 8.3

Listing 8.9 Implementing the PrintName derive macro
#[proc_macro_derive(PrintName)]
pub fn print_name(input: TokenStream) -> TokenStream {   #1
    let input = parse_macro_input!(input as DeriveInput);    #1

    let generics = add_trait_bounds(input.generics);         #2
    let (impl_generics, type_generics, where_clause) =   #3
        generics.split_for_impl();          #3            

    let name = input.ident;

    let expanded = quote! {                 #4
        impl #impl_generics print_name::PrintName for #name #type_generics
                #where_clause {
            fn name() -> &'static str {
                stringify!(#name)       #5
            }
        }
    };

    TokenStream::from(expanded)     #6
}

fn add_trait_bounds(mut generics: Generics) -> Generics {
    for param in &mut generics.params {
        if let GenericParam::Type(ref mut type_param) = *param {
          type_param.bounds.push(                   #7
            parse_quote!(print_name::PrintName)    #7
          );   #7                                     
        }
    }
    generics
}

A derive macro parses its input as DeriveInput, handles generics, and uses quote! to generate a trait implementation. section 8.3

How Idiomatic Rust covers it

How deep it goes
Demonstrates derive-input parsing, generic-bound handling, and generated implementations, while limiting procedural macros to a basic introduction.
Examples
Uses a PrintName derive macro on MyStruct and tests its generated name method.
What it assumes
Assumes Rust familiarity and introduces procedural-macro basics, including the separate proc-macro library requirement.
What you can do after
Build a derive macro that parses an input declaration and generates a trait implementation.
How it connects
Connects procedural macros and derive macros with TokenStream parsing, generic bounds, and quote-based code generation.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Idiomatic Rust. The section links point to the parts of the book it draws on.