Reputation: 2190
I'm trying to get started with TDD in Rust and I need to write a macro, which returns the number of variants in an enum. My implementation is similar to this one:
extern crate proc_macro;
extern crate syn;
#[macro_use]
extern crate quote;
use proc_macro::TokenStream;
#[proc_macro_derive(EnumVariantCount)]
pub fn derive_enum_variant_count(input: TokenStream) -> TokenStream {
let syn_item: syn::DeriveInput = syn::parse(input).unwrap();
let len = match syn_item.data {
syn::Data::Enum(enum_item) => enum_item.variants.len(),
_ => panic!("EnumVariantCount only works on Enums"),
};
let expanded = quote! {
const LENGTH: usize = #len;
};
expanded.into()
}
So first I want to write a test to check if this macro only works on an enum. How would this even work? Can I somehow check if a file compiles in a unit test? Is there some documentation on testing rust macros that I overlooked?
Upvotes: 6
Views: 4240