### Example Search Queries Source: https://docs.rs/synstructure/0.13.2/synstructure/struct.Structure.html?search= Common search patterns for finding types and functions within the documentation. ```text std::vec ``` ```text u32 -> bool ``` ```text Option, (T -> U) -> Option ``` -------------------------------- ### decl_attribute Usage Example Source: https://docs.rs/synstructure/0.13.2/synstructure/macro.decl_attribute.html Example showing how to define an attribute function and register it using the decl_attribute macro. ```rust fn attribute_interesting( _attr: proc_macro2::TokenStream, _structure: synstructure::Structure, ) -> proc_macro2::TokenStream { quote::quote! { ... } } decl_attribute!([interesting] => attribute_interesting); ``` -------------------------------- ### Using test_derive for Macro Testing Source: https://docs.rs/synstructure/0.13.2/synstructure/macro.test_derive.html?search= An example demonstrating how to define a test function and invoke the test_derive macro to verify procedural macro output. ```rust fn test_derive_example(_s: synstructure::Structure) -> Result { Ok(quote::quote! { const YOUR_OUTPUT: &'static str = "here"; }) } fn main() { synstructure::test_derive!{ test_derive_example { struct A; } expands to { const YOUR_OUTPUT: &'static str = "here"; } } } ``` -------------------------------- ### Example Usage of unpretty_print Source: https://docs.rs/synstructure/0.13.2/synstructure/fn.unpretty_print.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to use unpretty_print to format a token stream generated by the quote macro. ```rust assert_eq!( synstructure::unpretty_print(quote! { const _: () = { extern crate krate; impl krate::Trait for A where Option: krate::Trait, U: krate::Trait { fn a() {} } }; }), "const _ : ( ) = { extern crate krate ; impl < T , U > krate :: Trait for A < T , U > where Option < U > : krate :: Trait , U : krate :: Trait { fn a ( ) { } } } ; " ) ``` -------------------------------- ### Implement WalkFields Trait Source: https://docs.rs/synstructure/0.13.2/synstructure/index.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Basic trait definition and implementation for the WalkFields example. ```rust pub trait WalkFields: std::any::Any { fn walk_fields(&self, walk: &mut FnMut(&WalkFields)); } impl WalkFields for i32 { fn walk_fields(&self, _walk: &mut FnMut(&WalkFields)) {} } ``` -------------------------------- ### Inner Function Signatures Source: https://docs.rs/synstructure/0.13.2/synstructure/macro.decl_derive.html Examples of valid function signatures that can be passed to decl_derive. ```rust fn derive_simple(input: synstructure::Structure) -> proc_macro2::TokenStream { unimplemented!() } fn derive_result(input: synstructure::Structure) -> syn::Result { unimplemented!() } ``` -------------------------------- ### Generate trait implementations with Structure Source: https://docs.rs/synstructure/0.13.2/synstructure/struct.Structure.html Demonstrates how to use Structure to filter variants and generate trait implementations for a given DeriveInput. The gen_impl macro supports automatic bounds inference and multiple trait generation. ```rust let di: syn::DeriveInput = syn::parse_quote! { enum A { B(T), C(Option), } }; let mut s = Structure::new(&di); s.filter_variants(|v| v.ast().ident != "B"); assert_eq!( s.gen_impl(quote! { extern crate krate; gen impl krate::Trait for @Self { fn a() {} } }).to_string(), quote!{ const _: () = { extern crate krate; impl krate::Trait for A where Option: krate::Trait, U: krate::Trait { fn a() {} } }; }.to_string() ); // NOTE: You can also add extra generics after the impl assert_eq!( s.gen_impl(quote! { extern crate krate; gen impl krate::Trait for @Self where X: Send + Sync, { fn a() {} } }).to_string(), quote!{ const _: () = { extern crate krate; impl krate::Trait for A where X: Send + Sync, Option: krate::Trait, U: krate::Trait { fn a() {} } }; }.to_string() ); // NOTE: you can generate multiple traits with a single call assert_eq!( s.gen_impl(quote! { extern crate krate; gen impl krate::Trait for @Self { fn a() {} } gen impl krate::OtherTrait for @Self { fn b() {} } }).to_string(), quote!{ const _: () = { extern crate krate; impl krate::Trait for A where Option: krate::Trait, U: krate::Trait { fn a() {} } impl krate::OtherTrait for A where Option: krate::OtherTrait, U: krate::OtherTrait { fn b() {} } }; }.to_string() ); ``` -------------------------------- ### Structure::new Source: https://docs.rs/synstructure/0.13.2/synstructure/struct.Structure.html?search= Creates a new Structure instance from a syn::DeriveInput. Panics if the input is an untagged union. ```APIDOC ## pub fn new(ast: &'a DeriveInput) -> Self ### Description Create a new `Structure` with the variants and fields from the passed-in `DeriveInput`. ### Parameters - **ast** (&'a DeriveInput) - Required - The AST node to wrap. ``` -------------------------------- ### pub fn bind_with(&mut self, f: F) -> &mut Self Source: https://docs.rs/synstructure/0.13.2/synstructure/struct.VariantInfo.html?search= Updates the BindStyle for each of the passed-in fields by calling the provided function. ```APIDOC ## pub fn bind_with(&mut self, f: F) -> &mut Self ### Description Updates the `BindStyle` for each of the passed-in fields by calling the passed-in function for each `BindingInfo`. ``` -------------------------------- ### BindStyle Variant Patterns Source: https://docs.rs/synstructure/0.13.2/synstructure/enum.BindStyle.html The pattern syntax associated with each BindStyle variant. ```text x ``` ```text mut x ``` ```text ref x ``` ```text ref mut x ``` -------------------------------- ### bind_with Source: https://docs.rs/synstructure/0.13.2/synstructure/struct.Structure.html?search=std%3A%3Avec Updates the BindStyle for fields using a closure. ```APIDOC ## pub fn bind_with(&mut self, f: F) -> &mut Self ### Description Updates the `BindStyle` for each of the passed-in fields by calling the provided function for each `BindingInfo`. ``` -------------------------------- ### Custom Derive for WalkFields Source: https://docs.rs/synstructure/0.13.2/synstructure/index.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Implementation of a custom derive macro using synstructure to generate field-walking logic, including a test case. ```rust fn walkfields_derive(s: synstructure::Structure) -> proc_macro2::TokenStream { let body = s.each(|bi| quote!{ walk(#bi) }); s.gen_impl(quote! { extern crate synstructure_test_traits; gen impl synstructure_test_traits::WalkFields for @Self { fn walk_fields(&self, walk: &mut FnMut(&synstructure_test_traits::WalkFields)) { match *self { #body } } } }) } synstructure::decl_derive!([WalkFields] => walkfields_derive); /* * Test Case */ fn main() { synstructure::test_derive! { walkfields_derive { enum A { B(i32, T), C(i32), } } expands to { const _: () = { extern crate synstructure_test_traits; impl synstructure_test_traits::WalkFields for A where T: synstructure_test_traits::WalkFields { fn walk_fields(&self, walk: &mut FnMut(&synstructure_test_traits::WalkFields)) { match *self { A::B(ref __binding_0, ref __binding_1,) => { { walk(__binding_0) } { walk(__binding_1) } } A::C(ref __binding_0,) => { { walk(__binding_0) } } } } } }; } } } ``` -------------------------------- ### pub fn bound_impl(&self, path: P, body: B) -> TokenStream Source: https://docs.rs/synstructure/0.13.2/synstructure/struct.Structure.html Creates an impl block for the specified trait path, automatically adding necessary where clauses for type parameters. ```APIDOC ## pub fn bound_impl(&self, path: P, body: B) -> TokenStream ### Description Creates an `impl` block with the required generic type fields filled in to implement the trait `path`. This method also adds where clauses to the impl requiring that all referenced type parameters implement the trait `path`. ### Note This methods’ features are superceded by `Structure::gen_impl`. ### Hygiene and Paths This method wraps the impl block inside of a `const`. In this scope, the first segment of the passed-in path is `extern crate`-ed in. ### Panics Panics if the path string parameter is not a valid `TraitBound`. ``` -------------------------------- ### pub fn add_bounds(&mut self, mode: AddBounds) -> &mut Self Source: https://docs.rs/synstructure/0.13.2/synstructure/struct.Structure.html Configures which bounds are generated by impl-generating functions. ```APIDOC ## pub fn add_bounds(&mut self, mode: AddBounds) -> &mut Self ### Description Specify which bounds should be generated by impl-generating functions. The default behavior is to generate both field and generic bounds. ### Parameters - **mode** (AddBounds) - Required - The configuration mode for bound generation. ``` -------------------------------- ### Usage With Attributes and Doc Comments Source: https://docs.rs/synstructure/0.13.2/synstructure/macro.decl_derive.html Usage of decl_derive including attributes and documentation comments. ```rust fn derive_interesting(_input: synstructure::Structure) -> proc_macro2::TokenStream { quote::quote! { ... } } decl_derive! { [Interesting] => #[allow(some_lint)] /// Documentation Comments derive_interesting } ``` -------------------------------- ### Custom Derive Implementation Source: https://docs.rs/synstructure/0.13.2/synstructure/index.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Implements a custom derive macro for the Interest trait and includes a test case using synstructure::test_derive. ```rust fn interest_derive(mut s: synstructure::Structure) -> proc_macro2::TokenStream { let body = s.fold(false, |acc, bi| quote!{ #acc || synstructure_test_traits::Interest::interesting(#bi) }); s.gen_impl(quote! { extern crate synstructure_test_traits; gen impl synstructure_test_traits::Interest for @Self { fn interesting(&self) -> bool { match *self { #body } } } }) } synstructure::decl_derive!([Interest] => interest_derive); /* * Test Case */ fn main() { synstructure::test_derive!{ interest_derive { enum A { B(i32, T), C(i32), } } expands to { const _: () = { extern crate synstructure_test_traits; impl synstructure_test_traits::Interest for A where T: synstructure_test_traits::Interest { fn interesting(&self) -> bool { match *self { A::B(ref __binding_0, ref __binding_1,) => { false || synstructure_test_traits::Interest::interesting(__binding_0) || synstructure_test_traits::Interest::interesting(__binding_1) } A::C(ref __binding_0,) => { false || synstructure_test_traits::Interest::interesting(__binding_0) } } } } }; } } } ``` -------------------------------- ### Structure::each Source: https://docs.rs/synstructure/0.13.2/synstructure/struct.Structure.html?search= Generates code by running a function for each bound field in the structure. ```APIDOC ## pub fn each(&self, f: F) -> TokenStream ### Description Runs the passed-in function once for each bound field, passing in a `BindingInfo`, and generating `match` arms which evaluate the returned tokens. This method ignores variants or fields filtered out by `filter` and `filter_variant` methods. ``` -------------------------------- ### fn unpretty_print Source: https://docs.rs/synstructure/0.13.2/synstructure/fn.unpretty_print.html?search=std%3A%3Avec Dumps an unpretty version of a tokenstream. Takes any type which implements Display. ```APIDOC ## fn unpretty_print(ts: T) -> String ### Description Dumps an unpretty version of a tokenstream. This is mostly useful for visualizing the output of a procedural macro, as it makes it marginally more readable. ### Signature `pub fn unpretty_print(ts: T) -> String` ### Parameters - **ts** (T: Display) - The tokenstream or object implementing Display to be printed. ### Returns - **String** - The unpretty printed representation of the input. ### Stability The stability of the output of this function is not guaranteed. Do not assert that the output of this function does not change between minor versions. ``` -------------------------------- ### unpretty_print Source: https://docs.rs/synstructure/0.13.2/synstructure/fn.unpretty_print.html?search=u32+-%3E+bool Dumps an unpretty version of a tokenstream for types implementing Display. ```APIDOC ## fn unpretty_print(ts: T) -> String ### Description Dumps an unpretty version of a tokenstream. Takes any type which implements Display. This is mostly useful for visualizing the output of a procedural macro. ### Signature `pub fn unpretty_print(ts: T) -> String` ### Parameters - **ts** (T: Display) - The tokenstream or object to be printed. ### Returns - **String** - The unpretty printed representation of the input. ### Stability The stability of the output of this function is not guaranteed. Do not assert that the output of this function does not change between minor versions. ``` -------------------------------- ### unpretty_print Source: https://docs.rs/synstructure/0.13.2/synstructure/fn.unpretty_print.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Dumps an unpretty version of a tokenstream. Takes any type which implements Display. ```APIDOC ## pub fn unpretty_print(ts: T) -> String ### Description Dumps an unpretty version of a tokenstream. Takes any type which implements `Display`. This is mostly useful for visualizing the output of a procedural macro. ### Parameters - **ts** (T: Display) - The tokenstream or type implementing Display to be printed. ### Returns - **String** - The unpretty printed representation of the input. ``` -------------------------------- ### unpretty_print Source: https://docs.rs/synstructure/0.13.2/synstructure/fn.unpretty_print.html?search= Dumps an unpretty version of a tokenstream. Takes any type which implements Display. ```APIDOC ## fn unpretty_print(ts: T) -> String ### Description Dumps an unpretty version of a tokenstream. This is mostly useful for visualizing the output of a procedural macro, as it makes it marginally more readable. ### Parameters - **ts** (T: Display) - Required - The tokenstream or type implementing Display to be printed. ### Returns - **String** - The unpretty printed representation of the input. ### Stability The stability of the output of this function is not guaranteed. Do not assert that the output of this function does not change between minor versions. ``` -------------------------------- ### unpretty_print Source: https://docs.rs/synstructure/0.13.2/synstructure/index.html Dumps an unpretty version of a tokenstream for debugging purposes. ```APIDOC ## unpretty_print ### Description Dumps an unpretty version of a tokenstream. This function is useful for inspecting the output of macros. ### Parameters - **input** (T: Display) - Required - The value to be printed, which must implement the Display trait. ``` -------------------------------- ### Generate match-arm pattern Source: https://docs.rs/synstructure/0.13.2/synstructure/struct.VariantInfo.html?search=u32+-%3E+bool Generates a TokenStream representing the match-arm pattern for a variant. ```rust let di: syn::DeriveInput = syn::parse_quote! { enum A { B(i32, i32), C(u32), } }; let s = Structure::new(&di); assert_eq!( s.variants()[0].pat().to_string(), quote!{ A::B(ref __binding_0, ref __binding_1,) }.to_string() ); ``` -------------------------------- ### Define a Structure Source: https://docs.rs/synstructure/0.13.2/synstructure/struct.Structure.html The primary struct definition for the synstructure crate. ```rust pub struct Structure<'a> { /* private fields */ } ``` -------------------------------- ### Generated output structure Source: https://docs.rs/synstructure/0.13.2/synstructure/struct.Structure.html The output of gen_impl is wrapped in a dummy const block to maintain scope hygiene. ```rust const _: () = { extern crate krate; use krate::Trait as MyTrait; impl MyTrait for Struct where T: MyTrait { fn f(&self) { ... } } }; ``` -------------------------------- ### Structure::try_new Source: https://docs.rs/synstructure/0.13.2/synstructure/struct.Structure.html?search= Creates a new Structure instance from a syn::DeriveInput, returning a Result instead of panicking on untagged unions. ```APIDOC ## pub fn try_new(ast: &'a DeriveInput) -> Result ### Description Create a new `Structure` with the variants and fields from the passed-in `DeriveInput`. Unlike `Structure::new`, this method does not panic if the provided AST node represents an untagged union. ``` -------------------------------- ### Generate Pattern Fragment Source: https://docs.rs/synstructure/0.13.2/synstructure/struct.BindingInfo.html Generates the pattern fragment for a field binding using the pat() method. ```rust let di: syn::DeriveInput = syn::parse_quote! { enum A { B{ a: i32, b: i32 }, C(u32), } }; let s = Structure::new(&di); assert_eq!( s.variants()[0].bindings()[0].pat().to_string(), quote! { ref __binding_0 }.to_string() ); ``` -------------------------------- ### test_derive! Source: https://docs.rs/synstructure/0.13.2/synstructure/macro.test_derive.html A macro used to test custom derive implementations by expanding a struct and verifying the output matches the expected token stream. ```APIDOC ## test_derive! ### Description Runs a test on a custom derive. This macro expands both the original struct and the expansion to ensure that they compile correctly, and confirms that feeding the original struct into the named derive will produce the written output. ### Syntax `test_derive!($name:path { $($i:tt)* } expands to { $($o:tt)* })` `test_derive!($name:path { $($i:tt)* } expands to { $($o:tt)* } no_build)` ### Parameters - **$name** (path) - The path to the function implementing the derive logic. - **$i** (tt) - The input struct definition. - **$o** (tt) - The expected output token stream. - **no_build** (flag) - Optional. If provided, disables the check that the written code compiles. ### Example ```rust fn test_derive_example(_s: synstructure::Structure) -> Result { Ok(quote::quote! { const YOUR_OUTPUT: &'static str = "here"; }) } synstructure::test_derive!{ test_derive_example { struct A; } expands to { const YOUR_OUTPUT: &'static str = "here"; } } ``` ``` -------------------------------- ### BindingInfo Struct Definition Source: https://docs.rs/synstructure/0.13.2/synstructure/struct.BindingInfo.html The structure definition for BindingInfo, containing the binding identifier and binding style. ```rust pub struct BindingInfo<'a> { pub binding: Ident, pub style: BindStyle, /* private fields */ } ``` -------------------------------- ### Iterate over bound fields Source: https://docs.rs/synstructure/0.13.2/synstructure/struct.VariantInfo.html?search=u32+-%3E+bool Generates a match arm that executes a function for each bound field. ```rust let di: syn::DeriveInput = syn::parse_quote! { enum A { B(i32, i32), C(u32), } }; let s = Structure::new(&di); assert_eq!( s.variants()[0].each(|bi| quote!(println!("{:?}", #bi))).to_string(), quote!{ A::B(ref __binding_0, ref __binding_1,) => { { println!("{:?}", __binding_0) } { println!("{:?}", __binding_1) } } }.to_string() ); ``` -------------------------------- ### Update binding style with bind_with Source: https://docs.rs/synstructure/0.13.2/synstructure/struct.Structure.html Modifies the BindStyle for fields by applying a closure to each BindingInfo. ```rust let di: syn::DeriveInput = syn::parse_quote! { enum A { B(i32, i32), C(u32), } }; let mut s = Structure::new(&di); s.bind_with(|bi| BindStyle::RefMut); assert_eq!( s.each(|bi| quote!(println!("{:?}", #bi))).to_string(), quote!{ A::B(ref mut __binding_0, ref mut __binding_1,) => { { println!("{:?}", __binding_0) } { println!("{:?}", __binding_1) } } A::C(ref mut __binding_0,) => { { println!("{:?}", __binding_0) } } }.to_string() ); ``` -------------------------------- ### pub fn referenced_ty_params(&self) -> Vec<&'a Ident> Source: https://docs.rs/synstructure/0.13.2/synstructure/struct.VariantInfo.html?search=std%3A%3Avec Returns a list of type parameters referenced in the field's type. ```APIDOC ## pub fn referenced_ty_params(&self) -> Vec<&'a Ident> ### Description Returns a list of the type parameters which are referenced in this field’s type. Note that if the field contains macros in type position, all parameters are considered bound. ``` -------------------------------- ### gen_impl(TokenStream) Source: https://docs.rs/synstructure/0.13.2/synstructure/struct.Structure.html?search=std%3A%3Avec Generates a trait implementation block for a structure. It accepts a TokenStream, typically generated by the quote! macro, and wraps the output in a const block to ensure scope hygiene. ```APIDOC ## gen_impl(TokenStream) ### Description Generates a trait implementation for a structure. The function accepts a TokenStream containing the implementation details and automatically handles scope isolation by wrapping the generated code in a dummy const block. ### Usage ```rust s.gen_impl(quote! { extern crate krate; use krate::Trait as MyTrait; gen impl MyTrait for @Self { fn f(&self) { ... } } }) ``` ### Parameters - **TokenStream** (TokenStream) - Required - A stream of tokens representing the implementation block, typically created using the `quote!` macro. ### Behavior - **Hygiene**: The output is wrapped in a `const _: () = { ... }` block to prevent scope leakage. - **Trait Bounds**: Automatically adds trait bounds for type parameters referenced in non-ignored fields. - **Errors**: Generates a `compile_error!` if generic type parameters conflict. - **Panics**: Panics if the provided `TokenStream` is not well-formed. ``` -------------------------------- ### Configure generated bounds Source: https://docs.rs/synstructure/0.13.2/synstructure/struct.Structure.html Limits the types of bounds generated by impl-generating functions. ```rust let di: syn::DeriveInput = syn::parse_quote! { enum A { B(T), C(Option), } }; let mut s = Structure::new(&di); // Limit bounds to only generics. s.add_bounds(AddBounds::Generics); assert_eq!( s.bound_impl(quote!(krate::Trait), quote!{ fn a() {} }).to_string(), quote!{ const _: () = { extern crate krate; impl krate::Trait for A where T: krate::Trait, U: krate::Trait { fn a() {} } }; }.to_string() ); ``` -------------------------------- ### pub fn gen_impl(&self, cfg: TokenStream) -> TokenStream Source: https://docs.rs/synstructure/0.13.2/synstructure/struct.Structure.html?search= Generates an impl block for the given struct with automatic hygiene and trait bounds. ```APIDOC ## pub fn gen_impl(&self, cfg: TokenStream) -> TokenStream ### Description Generate an impl block for the given struct. This impl block will automatically use hygiene tricks to avoid polluting the caller’s namespace, and will automatically add trait bounds for generic type parameters. ### Parameters - **cfg** (TokenStream) - Configuration for the implementation generation. ### Returns - **TokenStream** - The generated implementation code. ``` -------------------------------- ### Construct variant token stream Source: https://docs.rs/synstructure/0.13.2/synstructure/struct.VariantInfo.html?search=u32+-%3E+bool Generates the token stream required to construct the current variant using a provided function for fields. ```rust let di: syn::DeriveInput = syn::parse_quote! { enum A { B(usize, usize), C{ v: usize }, } }; let s = Structure::new(&di); assert_eq!( s.variants()[0].construct(|_, i| quote!(#i)).to_string(), quote!{ A::B(0usize, 1usize,) }.to_string() ); assert_eq!( s.variants()[1].construct(|_, i| quote!(#i)).to_string(), quote!{ A::C{ v: 0usize, } }.to_string() ); ``` -------------------------------- ### Generate a trait implementation with synstructure Source: https://docs.rs/synstructure/0.13.2/synstructure/struct.Structure.html Use the gen_impl macro within a quote block to define trait implementations. The @Self placeholder refers to the structure's type. ```rust s.gen_impl(quote! { // You can write any items which you want to import into scope here. // For example, you may want to include an `extern crate` for the // crate which implements your trait. These items will only be // visible to the code you generate, and won't be exposed to the // consuming crate extern crate krate; // You can also add `use` statements here to bring types or traits // into scope. // // WARNING: Try not to use common names here, because the stable // version of syn does not support hygiene and you could accidentally // shadow types from the caller crate. use krate::Trait as MyTrait; // The actual impl block is a `gen impl` or `gen unsafe impl` block. // You can use `@Self` to refer to the structure's type. gen impl MyTrait for @Self { fn f(&self) { ... } } }) ``` -------------------------------- ### binding_name Source: https://docs.rs/synstructure/0.13.2/synstructure/struct.Structure.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Customizes the binding names for fields. ```APIDOC ## pub fn binding_name(&mut self, f: F) -> &mut Self ### Description Updates the binding name for each of the passed-in fields by calling the passed-in function. The function receives the `BindingInfo` and its index in the variant. ``` -------------------------------- ### Generate trait implementation block Source: https://docs.rs/synstructure/0.13.2/synstructure/struct.Structure.html Use bound_impl to create an impl block for a trait, automatically adding necessary where clauses. Note that this method wraps the implementation in a const block for hygiene. ```rust let di: syn::DeriveInput = syn::parse_quote! { enum A { B(T), C(Option), } }; let mut s = Structure::new(&di); s.filter_variants(|v| v.ast().ident != "B"); assert_eq!( s.bound_impl(quote!(krate::Trait), quote!{ fn a() {} }).to_string(), quote!{ const _: () = { extern crate krate; impl krate::Trait for A where Option: krate::Trait, U: krate::Trait { fn a() {} } }; }.to_string() ); ``` -------------------------------- ### Define VariantInfo struct Source: https://docs.rs/synstructure/0.13.2/synstructure/struct.VariantInfo.html?search=u32+-%3E+bool The structure definition for VariantInfo. ```rust pub struct VariantInfo<'a> { pub prefix: Option<&'a Ident>, /* private fields */ } ``` -------------------------------- ### Structure::each_variant Source: https://docs.rs/synstructure/0.13.2/synstructure/struct.Structure.html?search= Generates code by running a function for each variant in the structure. ```APIDOC ## pub fn each_variant(&self, f: F) -> TokenStream ### Description Runs the passed-in function once for each variant, passing in a `VariantInfo` and generating `match` arms which evaluate the returned tokens. ``` -------------------------------- ### bound_impl Source: https://docs.rs/synstructure/0.13.2/synstructure/struct.Structure.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates an impl block for a trait, automatically adding necessary generic type fields and where clauses. ```APIDOC ## pub fn bound_impl(&self, path: P, body: B) -> TokenStream ### Description Creates an `impl` block with the required generic type fields filled in to implement the trait `path`. This method also adds where clauses to the impl requiring that all referenced type parameters implement the trait `path`. ### Note This method's features are superseded by `Structure::gen_impl`. ### Panics Panics if the path string parameter is not a valid `TraitBound`. ``` -------------------------------- ### pub fn referenced_ty_params(&self) -> Vec<&'a Ident> Source: https://docs.rs/synstructure/0.13.2/synstructure/struct.VariantInfo.html?search= Returns a list of the type parameters which are referenced in this field’s type. ```APIDOC ## pub fn referenced_ty_params(&self) -> Vec<&'a Ident> ### Description Returns a list of the type parameters which are referenced in this field’s type. ### Caveat If the field contains any macros in type position, all parameters will be considered bound. ``` -------------------------------- ### bound_impl Source: https://docs.rs/synstructure/0.13.2/synstructure/struct.Structure.html?search= Creates an impl block for a trait, automatically filling in generic type fields and adding necessary where clauses. ```APIDOC ## pub fn bound_impl(&self, path: P, body: B) -> TokenStream ### Description Creates an `impl` block with the required generic type fields filled in to implement the trait `path`. This method also adds where clauses to the impl requiring that all referenced type parameters implement the trait `path`. ### Note This methods’ features are superceded by `Structure::gen_impl`. ### Hygiene and Paths This method wraps the impl block inside of a `const`. In this scope, the first segment of the passed-in path is `extern crate`-ed in. ### Caveat If the method contains any macros in type position, all parameters will be considered bound. ### Panics Panics if the path string parameter is not a valid `TraitBound`. ``` -------------------------------- ### Usage With Attributes Source: https://docs.rs/synstructure/0.13.2/synstructure/macro.decl_derive.html Usage of decl_derive including custom attributes. ```rust fn derive_interesting(_input: synstructure::Structure) -> proc_macro2::TokenStream { quote::quote! { ... } } decl_derive!([Interesting, attributes(interesting_ignore)] => derive_interesting); ``` -------------------------------- ### pub fn binding_name(&mut self, f: F) -> &mut Self Source: https://docs.rs/synstructure/0.13.2/synstructure/struct.VariantInfo.html?search=std%3A%3Avec Updates the binding name for each field using the provided closure. ```APIDOC ## pub fn binding_name(&mut self, f: F) -> &mut Self ### Description Updates the binding name for each of the passed-in fields by calling the passed-in function for each `BindingInfo`. The function receives the `BindingInfo` and its index in the variant. ``` -------------------------------- ### pub fn add_where_predicate(&mut self, pred: WherePredicate) -> &mut Self Source: https://docs.rs/synstructure/0.13.2/synstructure/struct.Structure.html Adds additional where predicate bounds to be generated by impl-generating functions. ```APIDOC ## pub fn add_where_predicate(&mut self, pred: WherePredicate) -> &mut Self ### Description Specify additional where predicate bounds which should be generated by impl-generating functions such as `gen_impl`, `bound_impl`, and `unsafe_bound_impl`. ### Parameters - **pred** (WherePredicate) - Required - The where predicate to add. ``` -------------------------------- ### decl_derive! Source: https://docs.rs/synstructure/0.13.2/synstructure/macro.decl_derive.html?search= The decl_derive! macro declares a custom derive wrapper. It parses the incoming TokenStream into a synstructure::Structure object and passes it to the provided inner function. ```APIDOC ## decl_derive! ### Description Declares a custom derive wrapper that processes a `synstructure::Structure` object. The inner function must accept `synstructure::Structure` by value and return a type implementing `synstructure::MacroResult` (e.g., `proc_macro2::TokenStream` or `syn::Result`). ### Syntax `decl_derive!([$derives:ident $($derive_t:tt)*] => $(#[$($attrs:tt)*])* $inner:path);` ### Usage Examples #### Basic Usage ```rust fn derive_interesting(_input: synstructure::Structure) -> proc_macro2::TokenStream { quote::quote! { ... } } decl_derive!([Interesting] => derive_interesting); ``` #### With Attributes ```rust decl_derive!([Interesting, attributes(interesting_ignore)] => derive_interesting); ``` #### With Doc Comments ```rust decl_derive! { [Interesting] => #[allow(some_lint)] /// Documentation Comments derive_interesting } ``` ``` -------------------------------- ### decl_derive! Source: https://docs.rs/synstructure/0.13.2/synstructure/macro.decl_derive.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E The decl_derive! macro declares a custom derive wrapper. It parses the incoming TokenStream into a synstructure::Structure object and passes it to the provided inner function. ```APIDOC ## decl_derive! ### Description Declares a custom derive wrapper that processes a `synstructure::Structure` object. ### Syntax `decl_derive!([$derives:ident $($derive_t:tt)*] => $(#[$($attrs:tt)*])* $inner:path);` ### Usage #### Without Attributes ```rust fn derive_interesting(_input: synstructure::Structure) -> proc_macro2::TokenStream { quote::quote! { ... } } decl_derive!([Interesting] => derive_interesting); ``` #### With Attributes ```rust fn derive_interesting(_input: synstructure::Structure) -> proc_macro2::TokenStream { quote::quote! { ... } } decl_derive!([Interesting, attributes(interesting_ignore)] => derive_interesting); ``` ``` -------------------------------- ### decl_derive! Source: https://docs.rs/synstructure/0.13.2/synstructure/macro.decl_derive.html?search=std%3A%3Avec The decl_derive! macro declares a custom derive wrapper. It parses the incoming TokenStream into a synstructure::Structure object and passes it to the provided inner function. ```APIDOC ## decl_derive! ### Description Declares a custom derive wrapper. It parses the incoming TokenStream into a `synstructure::Structure` object and passes it into the inner function. ### Syntax `decl_derive!([$derives:ident $($derive_t:tt)*] => $(#[$($attrs:tt)*])* $inner:path);` ### Usage #### Without Attributes ```rust fn derive_interesting(_input: synstructure::Structure) -> proc_macro2::TokenStream { quote::quote! { ... } } decl_derive!([Interesting] => derive_interesting); ``` #### With Attributes ```rust fn derive_interesting(_input: synstructure::Structure) -> proc_macro2::TokenStream { quote::quote! { ... } } decl_derive!([Interesting, attributes(interesting_ignore)] => derive_interesting); ``` ### Requirements - The inner function must take a `synstructure::Structure` by value. - The inner function must return a type implementing `synstructure::MacroResult` (e.g., `proc_macro2::TokenStream` or `syn::Result`). - This macro is available if `synstructure` is built with the `proc-macro` feature. ``` -------------------------------- ### Usage Without Attributes Source: https://docs.rs/synstructure/0.13.2/synstructure/macro.decl_derive.html Basic usage of decl_derive without additional attributes. ```rust fn derive_interesting(_input: synstructure::Structure) -> proc_macro2::TokenStream { quote::quote! { ... } } decl_derive!([Interesting] => derive_interesting); ``` -------------------------------- ### pub fn unbound_impl(&self, path: P, body: B) -> TokenStream Source: https://docs.rs/synstructure/0.13.2/synstructure/struct.Structure.html?search= Creates an impl block for a trait without adding where clauses. Note: This method is superseded by Structure::gen_impl. ```APIDOC ## pub fn unbound_impl(&self, path: P, body: B) -> TokenStream ### Description Creates an `impl` block with the required generic type fields filled in to implement the trait `path`. This method will not add any where clauses to the impl. ### Parameters - **path** (P: ToTokens) - The path to the trait to implement. - **body** (B: ToTokens) - The body of the implementation block. ### Returns - **TokenStream** - The generated implementation code. ``` -------------------------------- ### pub fn binding_name(&mut self, f: F) -> &mut Self Source: https://docs.rs/synstructure/0.13.2/synstructure/struct.VariantInfo.html?search= Updates the binding name for each of the passed-in fields by calling the provided function. ```APIDOC ## pub fn binding_name(&mut self, f: F) -> &mut Self ### Description Updates the binding name for each of the passed-in fields by calling the passed-in function for each `BindingInfo`. The function will be called with the `BindingInfo` and its index in the enclosing variant. ``` -------------------------------- ### decl_derive! Source: https://docs.rs/synstructure/0.13.2/synstructure/macro.decl_derive.html The decl_derive! macro declares a custom derive wrapper. It parses the incoming TokenStream into a synstructure::Structure object and passes it to the specified inner function. ```APIDOC ## decl_derive! ### Description Declares a custom derive wrapper that processes a `synstructure::Structure` object. The inner function must accept a `synstructure::Structure` by value and return a type implementing `synstructure::MacroResult` (e.g., `proc_macro2::TokenStream` or `syn::Result`). ### Syntax `decl_derive!([$derives:ident $($derive_t:tt)*] => $(#[$($attrs:tt)*])* $inner:path)` ### Usage Examples #### Without Attributes ```rust fn derive_interesting(_input: synstructure::Structure) -> proc_macro2::TokenStream { quote::quote! { ... } } decl_derive!([Interesting] => derive_interesting); ``` #### With Attributes ```rust fn derive_interesting(_input: synstructure::Structure) -> proc_macro2::TokenStream { quote::quote! { ... } } decl_derive!([Interesting, attributes(interesting_ignore)] => derive_interesting); ``` #### With Attributes and Doc Comments ```rust fn derive_interesting(_input: synstructure::Structure) -> proc_macro2::TokenStream { quote::quote! { ... } } decl_derive! { [Interesting] => #[allow(some_lint)] /// Documentation Comments derive_interesting } ``` ``` -------------------------------- ### Iterate over variants with each_variant Source: https://docs.rs/synstructure/0.13.2/synstructure/struct.Structure.html Generates match arms that execute a function for each variant. ```rust let di: syn::DeriveInput = syn::parse_quote! { enum A { B(i32, i32), C(u32), } }; let s = Structure::new(&di); assert_eq!( s.each_variant(|v| { let name = &v.ast().ident; quote!(println!(stringify!(#name))) }).to_string(), quote!{ A::B(ref __binding_0, ref __binding_1,) => { println!(stringify!(B)) } A::C(ref __binding_0,) => { println!(stringify!(C)) } }.to_string() ); ``` -------------------------------- ### test_derive Macro Definition Source: https://docs.rs/synstructure/0.13.2/synstructure/macro.test_derive.html?search= The signature for the test_derive macro, supporting optional build verification. ```rust macro_rules! test_derive { ($name:path { $($i:tt)* } expands to { $($o:tt)* }) => { ... }; ($name:path { $($i:tt)* } expands to { $($o:tt)* } no_build) => { ... }; } ``` -------------------------------- ### pub fn binding_name(&mut self, f: F) -> &mut Self Source: https://docs.rs/synstructure/0.13.2/synstructure/struct.VariantInfo.html Updates the binding name for each of the passed-in fields using a provided function. ```APIDOC ## pub fn binding_name(&mut self, f: F) -> &mut Self ### Description Updates the binding name for each of the passed-in fields by calling the passed-in function for each `BindingInfo`. The function is called with the `BindingInfo` and its index in the enclosing variant. ``` -------------------------------- ### Fold over bound fields Source: https://docs.rs/synstructure/0.13.2/synstructure/struct.VariantInfo.html?search=u32+-%3E+bool Generates a match arm that folds over bound fields using an accumulator. ```rust let di: syn::DeriveInput = syn::parse_quote! { enum A { B(i32, i32), C(u32), } }; let s = Structure::new(&di); assert_eq!( s.variants()[0].fold(quote!(0), |acc, bi| quote!(#acc + #bi)).to_string(), quote!{ A::B(ref __binding_0, ref __binding_1,) => { 0 + __binding_0 + __binding_1 } }.to_string() ); ``` -------------------------------- ### Define Interest Trait Source: https://docs.rs/synstructure/0.13.2/synstructure/index.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Defines the Interest trait and provides a basic implementation for i32. ```rust pub trait Interest { fn interesting(&self) -> bool; } impl Interest for i32 { fn interesting(&self) -> bool { *self > 0 } } ``` -------------------------------- ### Structure::fold Source: https://docs.rs/synstructure/0.13.2/synstructure/struct.Structure.html?search= Generates code by folding over bound fields in the structure. ```APIDOC ## pub fn fold(&self, init: I, f: F) -> TokenStream ### Description Runs the passed-in function once for each bound field, passing in the result of the previous call and a `BindingInfo`, generating `match` arms which evaluate to the resulting tokens. ``` -------------------------------- ### unsafe_bound_impl Source: https://docs.rs/synstructure/0.13.2/synstructure/struct.Structure.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates an unsafe impl block with required generic type fields and where clauses for the specified trait. ```APIDOC ## pub fn unsafe_bound_impl(&self, path: P, body: B) -> TokenStream ### Description Creates an `impl` block with the required generic type fields filled in to implement the unsafe trait `path`. This method also adds where clauses to the impl requiring that all referenced type parameters implement the trait `path`. ### Parameters - **path** (P: ToTokens) - The trait path to implement. - **body** (B: ToTokens) - The body of the implementation block. ### Returns - **TokenStream** - The generated implementation block wrapped in a const scope. ``` -------------------------------- ### pub fn unsafe_bound_impl(&self, path: P, body: B) -> TokenStream Source: https://docs.rs/synstructure/0.13.2/synstructure/struct.Structure.html?search= Creates an unsafe impl block for a trait with required generic type fields and where clauses. Note: This method is superseded by Structure::gen_impl. ```APIDOC ## pub fn unsafe_bound_impl(&self, path: P, body: B) -> TokenStream ### Description Creates an `impl` block with the required generic type fields filled in to implement the unsafe trait `path`. This method also adds where clauses to the impl requiring that all referenced type parameters implement the trait `path`. ### Parameters - **path** (P: ToTokens) - The path to the trait to implement. - **body** (B: ToTokens) - The body of the implementation block. ### Returns - **TokenStream** - The generated implementation code. ``` -------------------------------- ### pub fn filter(&mut self, f: F) -> &mut Self Source: https://docs.rs/synstructure/0.13.2/synstructure/struct.Structure.html?search=u32+-%3E+bool Filters the bindings created by this Structure object. Bindings that do not satisfy the predicate will be excluded from generated match arms and impl blocks. ```APIDOC ## pub fn filter(&mut self, f: F) -> &mut Self ### Description Filters the bindings created by this `Structure` object. This affects match arms generated by the structure and type parameters referenced in impl blocks. ### Parameters - **f** (FnMut(&BindingInfo<'_>) -> bool) - Required - A closure that returns true to keep a binding or false to filter it out. ``` -------------------------------- ### pub fn referenced_ty_params(&self) -> Vec<&'a Ident> Source: https://docs.rs/synstructure/0.13.2/synstructure/struct.Structure.html Returns a list of type parameters referenced in non-filtered fields or variants. ```APIDOC ## pub fn referenced_ty_params(&self) -> Vec<&'a Ident> ### Description Returns a list of the type parameters which are referenced in the types of non-filtered fields or variants. Note that if the struct contains macros in type position, all parameters are considered bound. ``` -------------------------------- ### decl_derive Macro Definition Source: https://docs.rs/synstructure/0.13.2/synstructure/macro.decl_derive.html The signature for the decl_derive macro. ```rust macro_rules! decl_derive { ([$derives:ident $($derive_t:tt)*] => $(#[$($attrs:tt)*])* $inner:path) => { ... }; } ```