Crate synstructure [] [src]

This crate provides helper methods for matching against enum variants, and extracting bindings to each of the fields in the deriving Struct or Enum in a generic way.

If you are writing a #[derive] which needs to perform some operation on every field, then you have come to the right place!

Example

extern crate syn;
extern crate synstructure;
#[macro_use]
extern crate quote;
use synstructure::{each_field, BindStyle};

type TokenStream = String; // XXX: Dummy to not depend on rustc_macro

fn sum_fields_derive(input: TokenStream) -> TokenStream {
    let source = input.to_string();
    let mut ast = syn::parse_macro_input(&source).unwrap();

    let match_body = each_field(&mut ast, &BindStyle::Ref.into(), |bi| quote! {
        sum += #bi as i64;
    });

    let name = &ast.ident;
    let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
    let result = quote! {
        // Original struct unmodified
        #ast

        impl #impl_generics ::sum_fields::SumFields for #name #ty_generics #where_clause {
            fn sum_fields(&self) -> i64 {
                let mut sum = 0i64;
                match *self { #match_body }
                sum
            }
        }
    };

    result.to_string().parse().unwrap()
}

fn main() {}

For more example usage, consider investigating the abomonation_derive crate, which makes use of this crate, and is fairly simple.

Structs

BindOpts

Binding options to use when generating a pattern. Configuration options used for generating binding patterns.

BindingInfo

Information about a specific binding. This contains both an Ident reference to the given field, and the syn &'a Field descriptor for that field.

Enums

BindStyle

The type of binding to use when generating a pattern.

Functions

each_field

This method calls func once per field in the struct or enum, and generates a series of match branches which will destructure match argument, and run the result of func once on each of the bindings.

match_pattern

Generate a match pattern for binding to the given VariantData This function returns a tuple of the tokens which make up that match pattern, and a BindingInfo object for each of the bindings which were made. The bind parameter controls the type of binding which is made.

match_substructs

This method generates a match branch for each of the substructures of the given MacroInput. It will call func for each of these substructures, passing in the bindings which were made for each of the fields in the substructure. The return value of func is then used as the value of each branch