Function derive_utils::derive_trait
source · [−]pub fn derive_trait<I>(
data: &EnumData,
trait_path: Path,
supertraits_types: I,
trait_def: ItemTrait
) -> TokenStream where
I: IntoIterator<Item = Ident>,
I::IntoIter: ExactSizeIterator,
Expand description
A function for creating proc_macro_derive
like deriving trait to enum so
long as all variants are implemented that trait.
Examples
use derive_utils::derive_trait;
use proc_macro::TokenStream;
use quote::format_ident;
use syn::{parse_macro_input, parse_quote};
#[proc_macro_derive(Iterator)]
pub fn derive_iterator(input: TokenStream) -> TokenStream {
derive_trait(
&parse_macro_input!(input),
// trait path
parse_quote!(std::iter::Iterator),
// super trait's associated types
None,
// trait definition
parse_quote! {
trait Iterator {
type Item;
fn next(&mut self) -> Option<Self::Item>;
fn size_hint(&self) -> (usize, Option<usize>);
}
},
)
.into()
}
#[proc_macro_derive(ExactSizeIterator)]
pub fn derive_exact_size_iterator(input: TokenStream) -> TokenStream {
derive_trait(
&parse_macro_input!(input),
// trait path
parse_quote!(std::iter::ExactSizeIterator),
// super trait's associated types
Some(format_ident!("Item")),
// trait definition
parse_quote! {
trait ExactSizeIterator: Iterator {
fn len(&self) -> usize;
}
},
)
.into()
}