Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added enum_is #257

Merged
merged 4 commits into from
Jun 18, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions strum_macros/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ proc-macro2 = "1.0"
quote = "1.0"
rustversion = "1.0"
syn = { version = "1.0", features = ["parsing", "extra-traits"] }
convert_case = "0.6"
MendyBerger marked this conversation as resolved.
Show resolved Hide resolved

[dev-dependencies]
strum = "0.24"
25 changes: 25 additions & 0 deletions strum_macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,31 @@ pub fn enum_iter(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
toks.into()
}

/// Generated `is_*()` methods for each variant.
/// E.g. `Color.is_red()`.
///
/// ```
///
/// use strum_macros::EnumIs;
///
/// #[derive(EnumIs, Debug)]
/// enum Color {
/// Red,
/// Green { range: usize },
/// }
///
/// assert!(Color::Red.is_red());
/// assert!(Color::Green{range: 0}.is_green());
/// ```
#[proc_macro_derive(EnumIs)]
pub fn enum_is(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let ast = syn::parse_macro_input!(input as DeriveInput);

let toks = macros::enum_is::enum_is_inner(&ast).unwrap_or_else(|err| err.to_compile_error());
debug_print_generated(&ast, &toks);
toks.into()
}

/// Add a function to enum that allows accessing variants by its discriminant
///
/// This macro adds a standalone function to obtain an enum variant by its discriminant. The macro adds
Expand Down
60 changes: 60 additions & 0 deletions strum_macros/src/macros/enum_is.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
use crate::helpers::non_enum_error;
use convert_case::{Case, Casing};
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use syn::{Data, DeriveInput};

pub fn enum_is_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
let variants = match &ast.data {
Data::Enum(v) => &v.variants,
_ => return Err(non_enum_error()),
};

let enum_name = &ast.ident;

let variants: Vec<_> = variants
MendyBerger marked this conversation as resolved.
Show resolved Hide resolved
.iter()
.map(|variant| {
let variant_name = &variant.ident;
let fn_name = format_ident!("is_{}", variant_name.to_string().to_case(Case::Snake));

match &variant.fields {
syn::Fields::Named(_) => {
quote! {
#[must_use]
#[inline]
pub const fn #fn_name(&self) -> bool {
matches!(self, &#enum_name::#variant_name { .. })
MendyBerger marked this conversation as resolved.
Show resolved Hide resolved
}
}
}
syn::Fields::Unnamed(values) => {
let underscores = values.unnamed.iter().map(|_| quote! {_});
quote! {
#[must_use]
#[inline]
pub const fn #fn_name(&self) -> bool {
matches!(self, &#enum_name::#variant_name (#(#underscores),*))
MendyBerger marked this conversation as resolved.
Show resolved Hide resolved
}
}
}
syn::Fields::Unit => {
quote! {
#[must_use]
#[inline]
pub const fn #fn_name(&self) -> bool {
matches!(self, &#enum_name::#variant_name)
}
}
}
}
})
.collect();

Ok(quote! {
impl #enum_name {
#(#variants)*
}
}
.into())
}
1 change: 1 addition & 0 deletions strum_macros/src/macros/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
pub mod enum_count;
pub mod enum_discriminants;
pub mod enum_is;
pub mod enum_iter;
pub mod enum_messages;
pub mod enum_properties;
Expand Down
67 changes: 67 additions & 0 deletions strum_tests/tests/enum_is.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
use strum::EnumIs;

#[derive(EnumIs)]
enum Foo {
Unit,
Named0 {},
Named1 { _a: char },
Named2 { _a: u32, _b: String },
Unnamed0(),
Unnamed1(Option<u128>),
Unnamed2(bool, u8),
MultiWordName,
}

#[test]
fn simple_test() {
assert!(Foo::Unit.is_unit());
}

#[test]
fn named_0() {
assert!(Foo::Named0 {}.is_named_0());
}

#[test]
fn named_1() {
let foo = Foo::Named1 {
_a: Default::default(),
};
assert!(foo.is_named_1());
}

#[test]
fn named_2() {
let foo = Foo::Named2 {
_a: Default::default(),
_b: Default::default(),
};
assert!(foo.is_named_2());
}

#[test]
fn unnamed_0() {
assert!(Foo::Unnamed0().is_unnamed_0());
}

#[test]
fn unnamed_1() {
let foo = Foo::Unnamed1(Default::default());
assert!(foo.is_unnamed_1());
}

#[test]
fn unnamed_2() {
let foo = Foo::Unnamed2(Default::default(), Default::default());
assert!(foo.is_unnamed_2());
}

#[test]
fn multi_word() {
assert!(Foo::MultiWordName.is_multi_word_name());
}

#[test]
fn doesnt_match_other_variations() {
assert!(!Foo::Unit.is_multi_word_name());
}