Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
- Add `Hash` derive similar to `std`'s one, but considering generics correctly,
and supporting custom hash functions per field or skipping fields.
([#532](https://github.com/JelteF/derive_more/pull/532))
- Add `IsVariantAnd` derive, generating an `is_foo_and()` method for each enum
variant `foo` that also applies a closure to the variant's fields, similar to
`Option::is_some_and`.
([#561](https://github.com/JelteF/derive_more/pull/561),
[#365](https://github.com/JelteF/derive_more/issues/365))

### Fixed

Expand Down
7 changes: 7 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ index_mut = ["derive_more-impl/index_mut"]
into = ["derive_more-impl/into"]
into_iterator = ["derive_more-impl/into_iterator"]
is_variant = ["derive_more-impl/is_variant"]
is_variant_and = ["derive_more-impl/is_variant_and"]
mul = ["derive_more-impl/mul"]
mul_assign = ["derive_more-impl/mul_assign"]
not = ["derive_more-impl/not"]
Expand Down Expand Up @@ -100,6 +101,7 @@ full = [
"into",
"into_iterator",
"is_variant",
"is_variant_and",
"mul",
"mul_assign",
"not",
Expand Down Expand Up @@ -212,6 +214,11 @@ name = "is_variant"
path = "tests/is_variant.rs"
required-features = ["is_variant"]

[[test]]
name = "is_variant_and"
path = "tests/is_variant_and.rs"
required-features = ["is_variant_and"]

[[test]]
name = "mul"
path = "tests/mul.rs"
Expand Down
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,8 +139,9 @@ These don't derive traits, but derive static methods instead.
This is very basic if you need more customization for your constructor, check
out the [`derive-new`] crate.
2. [`IsVariant`], for each variant `foo` of an enum type, derives a `is_foo` method.
3. [`Unwrap`], for each variant `foo` of an enum type, derives an `unwrap_foo` method.
4. [`TryUnwrap`], for each variant `foo` of an enum type, derives an `try_unwrap_foo` method.
3. [`IsVariantAnd`], for each variant `foo` of an enum type, derives a `is_foo_and` method.
4. [`Unwrap`], for each variant `foo` of an enum type, derives an `unwrap_foo` method.
5. [`TryUnwrap`], for each variant `foo` of an enum type, derives an `try_unwrap_foo` method.


### Re-exports
Expand Down Expand Up @@ -273,6 +274,7 @@ Changing [MSRV] (minimum supported Rust version) of this crate is treated as a *

[`Constructor`]: https://docs.rs/derive_more/latest/derive_more/derive.Constructor.html
[`IsVariant`]: https://docs.rs/derive_more/latest/derive_more/derive.IsVariant.html
[`IsVariantAnd`]: https://docs.rs/derive_more/latest/derive_more/derive.IsVariantAnd.html
[`Unwrap`]: https://docs.rs/derive_more/latest/derive_more/derive.Unwrap.html
[`TryUnwrap`]: https://docs.rs/derive_more/latest/derive_more/derive.TryUnwrap.html

Expand Down
2 changes: 2 additions & 0 deletions impl/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ index_mut = []
into = ["syn/extra-traits", "syn/visit-mut"]
into_iterator = []
is_variant = ["dep:convert_case"]
is_variant_and = ["dep:convert_case"]
mul = ["syn/extra-traits", "syn/visit"]
mul_assign = ["syn/extra-traits", "syn/visit"]
not = ["syn/extra-traits"]
Expand Down Expand Up @@ -95,6 +96,7 @@ full = [
"into",
"into_iterator",
"is_variant",
"is_variant_and",
"mul",
"mul_assign",
"not",
Expand Down
69 changes: 69 additions & 0 deletions impl/doc/is_variant_and.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# What `#[derive(IsVariantAnd)]` generates

When an enum is decorated with `#[derive(IsVariantAnd)]`, for each variant `foo`
in the enum a public instance method `is_foo_and(&self, f) -> bool` is generated.
It returns `true` if the value is the `foo` variant *and* the closure `f`,
applied to the variant's fields (by reference), returns `true`. This mirrors
[`Option::is_some_and`], but for arbitrary enums.

The closure receives the variant's fields as a tuple of references, in
declaration order. As with a regular tuple, a variant with a single field
collapses to a plain reference (so `Just(T)` yields `is_just_and(|x: &T| ...)`,
exactly like [`Option::is_some_and`]), while a unit variant's method takes a
`FnOnce() -> bool` closure instead.

If you don't want the `is_foo_and` method generated for a variant you can put
the `#[is_variant_and(ignore)]` attribute on that variant.

[`Option::is_some_and`]: https://doc.rust-lang.org/core/option/enum.Option.html#method.is_some_and




## Example usage

```rust
# use derive_more::IsVariantAnd;
#
#[derive(IsVariantAnd)]
enum Maybe<T> {
Just(T),
Nothing,
}

let maybe = Maybe::Just(42);
assert!(maybe.is_just_and(|x| *x == 42));
assert!(!maybe.is_just_and(|x| *x == 0));
assert!(!maybe.is_nothing_and(|| true));

let nothing = Maybe::<i32>::Nothing;
assert!(nothing.is_nothing_and(|| true));
assert!(!nothing.is_just_and(|x| *x == 42));
```


### What is generated?

The derive in the above example generates code like this:
```rust
# enum Maybe<T> {
# Just(T),
# Nothing,
# }
impl<T> Maybe<T> {
#[must_use]
pub fn is_just_and(&self, f: impl FnOnce(&T) -> bool) -> bool {
match self {
Self::Just(field_0) => f(field_0),
_ => false,
}
}
#[must_use]
pub fn is_nothing_and(&self, f: impl FnOnce() -> bool) -> bool {
match self {
Self::Nothing => f(),
_ => false,
}
}
}
```
138 changes: 138 additions & 0 deletions impl/src/is_variant_and.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
use crate::utils::{AttrParams, DeriveType, State};
use convert_case::{Case, Casing};
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use syn::{DeriveInput, Fields, Result};

pub fn expand(input: &DeriveInput, trait_name: &'static str) -> Result<TokenStream> {
let state = State::with_attr_params(
input,
trait_name,
"is_variant_and".into(),
AttrParams {
enum_: vec!["ignore"],
variant: vec!["ignore"],
struct_: vec!["ignore"],
field: vec!["ignore"],
},
)?;
assert!(
state.derive_type == DeriveType::Enum,
"IsVariantAnd can only be derived for enums",
);

let enum_name = &input.ident;
let (imp_generics, type_generics, where_clause) = input.generics.split_for_impl();

let mut funcs = vec![];
for variant_state in state.enabled_variant_data().variant_states {
let variant = variant_state.variant.unwrap();
let variant_ident = &variant.ident;
let fn_name = format_ident!(
"is_{}_and",
variant_ident.to_string().to_case(Case::Snake),
span = variant_ident.span(),
);

let (pattern, bindings, arg_type) = field_info(&variant.fields);
let pattern = quote! { #enum_name ::#variant_ident #pattern };

let doc = format!(
"Returns `true` if this value is of type `{variant_ident}` and the \
given closure returns `true` for the contained value(s).\n\nReturns \
`false` otherwise.",
);

let func = if let Some(arg_type) = arg_type {
quote! {
#[doc = #doc]
#[inline]
#[must_use]
pub fn #fn_name(
&self,
f: impl derive_more::core::ops::FnOnce(#arg_type) -> bool,
) -> bool {
match self {
#pattern => f(#bindings),
_ => false,
}
}
}
} else {
quote! {
#[doc = #doc]
#[inline]
#[must_use]
pub fn #fn_name(
&self,
f: impl derive_more::core::ops::FnOnce() -> bool,
) -> bool {
match self {
#pattern => f(),
_ => false,
}
}
}
};
funcs.push(func);
}

let imp = quote! {
#[allow(deprecated)] // omit warnings on deprecated fields/variants
#[allow(unreachable_code)] // omit warnings for `!` and other unreachable types
#[allow(unreachable_patterns)] // omit warnings for single-variant enums
#[automatically_derived]
impl #imp_generics #enum_name #type_generics #where_clause {
#(#funcs)*
}
};

Ok(imp)
}

/// Returns the pattern binding the variant's fields, the tuple of bound field
/// references passed to the closure, and the closure's argument type.
///
/// The argument type is `None` for unit variants, whose generated method takes a
/// `FnOnce() -> bool` closure instead. For a variant with a single field the
/// resulting type collapses to a plain reference (e.g. `&T`), mirroring
/// [`Option::is_some_and`].
fn field_info(fields: &Fields) -> (TokenStream, TokenStream, Option<TokenStream>) {
match fields {
Fields::Named(fields) if !fields.named.is_empty() => {
let (patterns, (bindings, types)): (Vec<_>, (Vec<_>, Vec<_>)) = fields
.named
.iter()
.enumerate()
.map(|(n, field)| {
let name = field.ident.as_ref().unwrap();
let binding = format_ident!("__field_{n}");
(quote! { #name: #binding }, (binding, &field.ty))
})
.unzip();
(
quote! { { #(#patterns),* } },
quote! { (#(#bindings),*) },
Some(quote! { (#(&#types),*) }),
)
}
Fields::Unnamed(fields) if !fields.unnamed.is_empty() => {
let (bindings, types): (Vec<_>, Vec<_>) = fields
.unnamed
.iter()
.enumerate()
.map(|(n, field)| (format_ident!("__field_{n}"), &field.ty))
.unzip();
(
quote! { (#(#bindings),*) },
quote! { (#(#bindings),*) },
Some(quote! { (#(&#types),*) }),
)
}
// Variants with no fields (unit, empty tuple `()` or empty record `{}`)
// all take a `FnOnce() -> bool` closure.
Fields::Named(_) => (quote! { {} }, quote! {}, None),
Fields::Unnamed(_) => (quote! { () }, quote! {}, None),
Fields::Unit => (quote! {}, quote! {}, None),
}
}
10 changes: 10 additions & 0 deletions impl/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ mod into;
mod into_iterator;
#[cfg(feature = "is_variant")]
mod is_variant;
#[cfg(feature = "is_variant_and")]
mod is_variant_and;
#[cfg(feature = "not")]
mod not_like;
#[cfg(any(
Expand Down Expand Up @@ -238,6 +240,14 @@ create_derive!(
is_variant,
);

create_derive!(
"is_variant_and",
is_variant_and,
IsVariantAnd,
is_variant_and_derive,
is_variant_and,
);

create_derive!("mul", ops::mul, Mul, mul_derive, mul);
create_derive!("mul", ops::mul, Div, div_derive, div);
create_derive!("mul", ops::mul, Rem, rem_derive, rem);
Expand Down
9 changes: 9 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
//!
//! [`Constructor`]: macro@crate::Constructor
//! [`IsVariant`]: macro@crate::IsVariant
//! [`IsVariantAnd`]: macro@crate::IsVariantAnd
//! [`Unwrap`]: macro@crate::Unwrap
//! [`TryUnwrap`]: macro@crate::TryUnwrap

Expand Down Expand Up @@ -306,6 +307,9 @@ pub mod with_trait {
#[cfg(feature = "is_variant")]
pub use derive_more_impl::IsVariant;

#[cfg(feature = "is_variant_and")]
pub use derive_more_impl::IsVariantAnd;

#[cfg(feature = "mul")]
pub use derive_more_impl::{Div, Mul, Rem, Shl, Shr};

Expand Down Expand Up @@ -414,6 +418,10 @@ pub mod with_trait {
#[doc(hidden)]
pub use all_traits_and_derives::IsVariant;

#[cfg(feature = "is_variant_and")]
#[doc(hidden)]
pub use all_traits_and_derives::IsVariantAnd;

#[cfg(feature = "mul")]
#[doc(hidden)]
pub use all_traits_and_derives::{Div, Mul, Rem, Shl, Shr};
Expand Down Expand Up @@ -475,6 +483,7 @@ pub mod with_trait {
feature = "into",
feature = "into_iterator",
feature = "is_variant",
feature = "is_variant_and",
feature = "mul",
feature = "mul_assign",
feature = "not",
Expand Down
1 change: 0 additions & 1 deletion tests/compile_fail/eq/non_eq_field.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,4 @@ error[E0277]: the trait bound `f32: Eq` is not satisfied
u128
u16
and $N others
= help: see issue #48214
= note: this error originates in the derive macro `derive_more::Eq` (in Nightly builds, run with -Z macro-backtrace for more info)
Loading
Loading