use macro_rules_attribute::derive; use mini_macro_magic::export; // An example macro that gets the name of the variant an expression is. // It also needs to be given the enum definition to generate the match statement. // We will use the export macro to export the enum definition for use by this macro. // // In some sense this macro is generic over the enum *definition* itself. macro_rules! variant_name { {{ $(#[$($attr:tt)*])* $vis:vis enum $name:ident { $($variant:ident($($stuff:tt)*)),*$(,)? } } $e:expr} => { match $e { $($name::$variant {..} => stringify!($variant)),* } }; } // An example enum. // Here we use the derive macro to apply export to the enum definition. // A macro named my_enum will be generated along side the enum definition. // The my_enum macro can be used to call any other macro with the definition of the enum. #[derive(export!)] #[custom(export(my_enum$))] pub enum MyEnum { A(i32), B(String), C(bool), } #[test] fn check_variant() { // Check that the macro can get the correct variant name. let x = MyEnum::A(1); assert_eq!(my_enum!(variant_name!(x)), "A"); let x = MyEnum::B("a".into()); assert_eq!(my_enum!(variant_name!(x)), "B"); let x = MyEnum::C(true); assert_eq!(my_enum!(variant_name!(x)), "C"); }