DeriveInput is syn’s parsed representation of an item supplied to a procedural macro. It provides the top-level identifier needed to generate an impl for the decorated type, rather than hardcoding that type’s name. section 3.3
Parse a TokenStream with parse_macro_input!(item as DeriveInput), then read ast.ident. Inside quote!, write #name to interpolate that identifier into generated Rust code. section 3.3
A DeriveInput exposes the item’s outer structure:
- attrs holds attributes; vis holds visibility; ident holds the item name; and generics describes generic parameters. section 4.4
- data is a Data enum containing Struct, Enum, or Union details. section 4.4
- For a struct, DataStruct leads to Fields; matching Fields::Named reaches named field definitions for transformation. section 4.4
Generate a method for the annotated type
A Hello derive macro parses its input, saves ast.ident as name, and emits impl #name { fn hello_world(&self) { println!("Hello, World") } }. Renaming the struct therefore changes the generated impl target automatically. section 3.3
DeriveInput can also parse annotated structs in attribute macros because both macro forms can target structs, enums, and unions. A macro limited to named structs can match ast.data and reject other shapes; syn::ItemStruct is an alternative when the syn “full” feature is enabled. section 4.4
When recreating input in generated output, avoid consuming parts you still need. DeriveInput implements ToTokens, so borrowing its identifier and interpolating the AST can preserve the original struct; taking ast.ident by value can cause a partial-move constraint. section 5.1.2
Figure 4.2 Finding the roots of the world tree: from DeriveInput to Fields for our Example struct
Follow the structural path from DeriveInput through Data and DataStruct to Fields before writing a match for named fields. section 4.4
