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

Use dedicated error types for Add and Not derives (#221) #233

Merged
merged 6 commits into from
Jan 26, 2023
Merged
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: 3 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
- The `From` derive doesn't derive `From<()>` for enum variants without any
fields anymore. This feature was removed because it was considered useless in
practice.
- The `TryFrom` derive now returns a dedicated error type instead of a
`&'static str` on error.
- The `TryFrom`, `Add`, `Sub`, `BitAnd`, `BitOr`, `BitXor`, `Not` and `Neg`
derives now return a dedicated error type instead of a `&'static str` on
error.
- The `Display` derive (and other `fmt`-like ones) now uses
`#[display("...", (<expr>),*)]` syntax instead of
`#[display(fmt = "...", ("<expr>"),*)]`, and `#[display(bound(<bound>))]`
Expand Down
12 changes: 8 additions & 4 deletions impl/doc/add.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,8 @@ Code like this will be generated:
# Unit,
# }
impl ::core::ops::Add for MixedInts {
type Output = Result<MixedInts, &'static str>;
fn add(self, rhs: MixedInts) -> Result<MixedInts, &'static str> {
type Output = Result<MixedInts, ::derive_more::ops::BinaryError>;
fn add(self, rhs: MixedInts) -> Result<MixedInts, ::derive_more::ops::BinaryError> {
match (self, rhs) {
(MixedInts::SmallInt(__l_0), MixedInts::SmallInt(__r_0)) => {
Ok(MixedInts::SmallInt(__l_0.add(__r_0)))
Expand All @@ -138,8 +138,12 @@ impl ::core::ops::Add for MixedInts {
(MixedInts::UnsignedTwo(__l_0), MixedInts::UnsignedTwo(__r_0)) => {
Ok(MixedInts::UnsignedTwo(__l_0.add(__r_0)))
}
(MixedInts::Unit, MixedInts::Unit) => Err("Cannot add() unit variants"),
_ => Err("Trying to add mismatched enum variants"),
(MixedInts::Unit, MixedInts::Unit) => Err(::derive_more::ops::BinaryError::Unit(
::derive_more::ops::UnitError::new("add"),
)),
_ => Err(::derive_more::ops::BinaryError::Mismatch(
::derive_more::ops::WrongVariantError::new("add"),
)),
}
}
}
Expand Down
8 changes: 4 additions & 4 deletions impl/doc/not.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# What `#[derive(Not)]` generates

The derived `Not` implementation simply negates all of the fields of a
The derived `Not` implementation simply negates all the fields of a
struct and returns that as a new instance of the struct.
For enums all fields of the active variant of the enum are negated and a new
instance of the same variant with these negated fields is returned.
Expand Down Expand Up @@ -148,11 +148,11 @@ Code like this will be generated:
# Unit,
# }
impl ::core::ops::Not for EnumWithUnit {
type Output = Result<EnumWithUnit, &'static str>;
fn not(self) -> Result<EnumWithUnit, &'static str> {
type Output = Result<EnumWithUnit, ::derive_more::ops::UnitError>;
fn not(self) -> Result<EnumWithUnit, ::derive_more::ops::UnitError> {
match self {
EnumWithUnit::SmallInt(__0) => Ok(EnumWithUnit::SmallInt(__0.not())),
EnumWithUnit::Unit => Err("Cannot not() unit variants"),
EnumWithUnit::Unit => Err(::derive_more::ops::UnitError::new("not")),
}
}
}
Expand Down
20 changes: 15 additions & 5 deletions impl/src/add_like.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@ pub fn expand(input: &DeriveInput, trait_name: &str) -> TokenStream {
_ => panic!("Unit structs cannot use derive({trait_name})"),
},
Data::Enum(ref data_enum) => (
quote! { ::core::result::Result<#input_type #ty_generics, &'static str> },
quote! {
::core::result::Result<#input_type #ty_generics, ::derive_more::ops::BinaryError>
},
enum_content(input_type, data_enum, &method_ident),
),

Expand Down Expand Up @@ -121,9 +123,13 @@ fn enum_content(
matches.push(matcher);
}
Fields::Unit => {
let message = format!("Cannot {method_ident}() unit variants");
let operation_name = method_ident.to_string();
matches.push(quote! {
(#subtype, #subtype) => ::core::result::Result::Err(#message)
(#subtype, #subtype) => ::core::result::Result::Err(
::derive_more::ops::BinaryError::Unit(
::derive_more::ops::UnitError::new(#operation_name)
)
)
});
}
}
Expand All @@ -132,8 +138,12 @@ fn enum_content(
if data_enum.variants.len() > 1 {
// In the strange case where there's only one enum variant this is would be an unreachable
// match.
let message = format!("Trying to {method_ident} mismatched enum variants");
matches.push(quote! { _ => ::core::result::Result::Err(#message) });
let operation_name = method_ident.to_string();
matches.push(quote! {
_ => ::core::result::Result::Err(::derive_more::ops::BinaryError::Mismatch(
::derive_more::ops::WrongVariantError::new(#operation_name)
))
});
}
quote! {
match (self, rhs) {
Expand Down
11 changes: 7 additions & 4 deletions impl/src/not_like.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,9 +145,12 @@ fn enum_output_type_and_content(
matches.push(matcher);
}
Fields::Unit => {
let message = format!("Cannot {method_ident}() unit variants");
matches
.push(quote! { #subtype => ::core::result::Result::Err(#message) });
let operation_name = method_ident.to_string();
matches.push(quote! {
#subtype => ::core::result::Result::Err(
::derive_more::ops::UnitError::new(#operation_name)
)
});
}
}
}
Expand All @@ -159,7 +162,7 @@ fn enum_output_type_and_content(
};

let output_type = if has_unit_type {
quote! { ::core::result::Result<#input_type #ty_generics, &'static str> }
quote! { ::core::result::Result<#input_type #ty_generics, ::derive_more::ops::UnitError> }
} else {
quote! { #input_type #ty_generics }
};
Expand Down
4 changes: 3 additions & 1 deletion src/errors.rs → src/convert.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
//! Definitions used in derived implementations of [`core::convert`] traits.

use core::fmt;

/// Error returned by the derived [`TryInto`] implementation.
Expand All @@ -15,7 +17,7 @@ pub struct TryIntoError<T> {
}

impl<T> TryIntoError<T> {
/// Creates a new [`TryIntoError`].
#[doc(hidden)]
#[must_use]
#[inline]
pub const fn new(
Expand Down
7 changes: 5 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@
pub use derive_more_impl::*;

#[cfg(feature = "try_into")]
mod errors;
mod convert;
#[cfg(feature = "try_into")]
pub use crate::errors::TryIntoError;
pub use self::convert::TryIntoError;

#[cfg(any(feature = "add", feature = "not"))]
pub mod ops;
92 changes: 92 additions & 0 deletions src/ops.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
//! Definitions used in derived implementations of [`core::ops`] traits.

use core::fmt;

/// Error returned by the derived implementations when an arithmetic or logic
/// operation is invoked on a unit-like variant of an enum.
#[derive(Clone, Copy, Debug)]
pub struct UnitError {
operation_name: &'static str,
}

impl UnitError {
#[doc(hidden)]
#[must_use]
#[inline]
pub const fn new(operation_name: &'static str) -> Self {
Self { operation_name }
}
}

impl fmt::Display for UnitError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Cannot {}() unit variants", self.operation_name)
}
}

#[cfg(feature = "std")]
impl std::error::Error for UnitError {}

#[cfg(feature = "add")]
/// Error returned by the derived implementations when an arithmetic or logic
/// operation is invoked on mismatched enum variants.
#[derive(Clone, Copy, Debug)]
pub struct WrongVariantError {
operation_name: &'static str,
}

#[cfg(feature = "add")]
impl WrongVariantError {
#[doc(hidden)]
#[must_use]
#[inline]
pub const fn new(operation_name: &'static str) -> Self {
Self { operation_name }
}
}

#[cfg(feature = "add")]
impl fmt::Display for WrongVariantError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"Trying to {}() mismatched enum variants",
self.operation_name
)
}
}

#[cfg(all(feature = "add", feature = "std"))]
impl std::error::Error for WrongVariantError {}

#[cfg(feature = "add")]
/// Possible errors returned by the derived implementations of binary
/// arithmetic or logic operations.
#[derive(Clone, Copy, Debug)]
pub enum BinaryError {
/// Operation is attempted between mismatched enum variants.
Mismatch(WrongVariantError),

/// Operation is attempted on unit-like enum variants.
Unit(UnitError),
}

#[cfg(feature = "add")]
impl fmt::Display for BinaryError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Mismatch(e) => write!(f, "{e}"),
Self::Unit(e) => write!(f, "{e}"),
}
}
}

#[cfg(all(feature = "add", feature = "std"))]
impl std::error::Error for BinaryError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Mismatch(e) => e.source(),
Self::Unit(e) => e.source(),
}
}
}