1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
//! This crate provides a macro to implement equality of enum variants. //! //! Two enum variants are equal if they are the same variant from the same enum, regardless of the //! values of the fields each variant contains. //! //! ```no_run //! # #[macro_use] //! # extern crate varianteq; //! # //! #[derive(VariantEq)] //! enum Enum { //! Variant, //! } //! # //! # fn main() {} //! ``` //! //! # Examples //! //! ``` //! #[macro_use] //! extern crate varianteq; //! //! #[derive(Debug, VariantEq)] //! enum E { //! A(i32), //! B(i32), //! C(u32, bool), //! } //! //! fn main() { //! assert_eq!(E::A(1), E::A(2)); //! assert_ne!(E::A(1), E::B(1)); //! assert_ne!(E::A(1), E::C(1, false)); //! } //! ``` //! //! # Errors //! //! The `VariantEq` macro only applies to enums and will cauase a compilation error if used on //! structs. //! //! ```compile_fail //! # #[macro_use] //! # extern crate varianteq; //! # //! #[derive(VariantEq)] //! struct S; //! # //! # fn main() {} //! ``` //! //! ```text //! error: #[derive(VariantEq)] is only defined for enums //! ``` #![feature(proc_macro)] extern crate proc_macro; extern crate proc_macro2; extern crate syn; #[macro_use] extern crate quote; use proc_macro::{Diagnostic, TokenStream}; use quote::Tokens; use syn::{parse2, DeriveInput}; mod varianteq; type DeriveFn = fn(DeriveInput) -> Result<Tokens, Diagnostic>; #[proc_macro_derive(VariantEq)] pub fn varianteq_derive(tokens: TokenStream) -> TokenStream { expand_derive(tokens, varianteq::derive) } fn expand_derive(tokens: TokenStream, derive: DeriveFn) -> TokenStream { let item = parse2(tokens.into()).unwrap(); match derive(item) { Ok(tokens) => tokens.into(), Err(err) => handle_derive_err(err), } } fn handle_derive_err(err: Diagnostic) -> TokenStream { err.emit(); "".parse().unwrap() }