use core::fmt;
use neco_algnum::AlgnumError;
use neco_bigint::BigintError;
use neco_formsum::FormSumErrorKind;
use neco_monomial::MonomialErrorKind;
use crate::{AtomId, ConsumerId, ExprId, StorageResource};
#[derive(Debug, Eq, PartialEq)]
pub enum StorageError {
CapacityOverflow {
resource: StorageResource,
},
AllocationFailure {
resource: StorageResource,
requested_elements: usize,
},
}
#[derive(Debug, Eq, PartialEq)]
pub enum GraphError {
IdExhausted,
InvalidChildId { child: ExprId, next: ExprId },
Node(EvalError),
Storage(StorageError),
}
#[derive(Debug, Eq, PartialEq)]
pub enum InsertError {
DuplicateId { resource: StorageResource, id: u32 },
Value(EvalError),
Storage(StorageError),
}
#[derive(Debug, Eq, PartialEq)]
pub enum EvalError {
DivisionByZero,
UndefinedZeroPower,
ZeroToNegativePower,
EvenRootOfNegative,
Bigint(BigintError),
Monomial(MonomialErrorKind),
FormSum(FormSumErrorKind),
Algnum(AlgnumError),
}
#[derive(Debug, Eq, PartialEq)]
pub enum ResolveError {
MissingAssignment { consumer: ConsumerId },
UnknownExprId { consumer: ConsumerId, expr: ExprId },
UnknownAtomId { expr: ExprId, atom: AtomId },
FloatOutOfRange { consumer: ConsumerId, expr: ExprId },
Evaluation(EvalError),
Bigint(BigintError),
Algnum(AlgnumError),
Storage(StorageError),
}
impl fmt::Display for StorageError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::CapacityOverflow { resource } => {
write!(formatter, "capacity overflow for {resource:?}")
}
Self::AllocationFailure {
resource,
requested_elements,
} => write!(
formatter,
"allocation failed for {resource:?}: requested {requested_elements} elements"
),
}
}
}
impl fmt::Display for GraphError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::IdExhausted => formatter.write_str("expression graph ID space is exhausted"),
Self::InvalidChildId { child, next } => write!(
formatter,
"expression child {} is not earlier than next expression {}",
child.get(),
next.get()
),
Self::Node(error) => write!(formatter, "expression node clone failed: {error}"),
Self::Storage(error) => error.fmt(formatter),
}
}
}
impl fmt::Display for InsertError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::DuplicateId { resource, id } => {
write!(formatter, "duplicate ID {id} for {resource:?}")
}
Self::Value(error) => write!(formatter, "stored value clone failed: {error}"),
Self::Storage(error) => error.fmt(formatter),
}
}
}
impl fmt::Display for EvalError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::DivisionByZero => formatter.write_str("division by zero"),
Self::UndefinedZeroPower => formatter.write_str("zero raised to the zero power"),
Self::ZeroToNegativePower => formatter.write_str("zero raised to a negative power"),
Self::EvenRootOfNegative => formatter.write_str("even root of a negative value"),
Self::Bigint(error) => error.fmt(formatter),
Self::Monomial(error) => error.fmt(formatter),
Self::FormSum(error) => error.fmt(formatter),
Self::Algnum(error) => error.fmt(formatter),
}
}
}
impl fmt::Display for ResolveError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::MissingAssignment { consumer } => {
write!(formatter, "consumer {} has no assignment", consumer.get())
}
Self::UnknownExprId { consumer, expr } => write!(
formatter,
"consumer {} refers to unknown expression {}",
consumer.get(),
expr.get()
),
Self::UnknownAtomId { expr, atom } => write!(
formatter,
"expression {} refers to unknown atom {}",
expr.get(),
atom.get()
),
Self::FloatOutOfRange { consumer, expr } => write!(
formatter,
"expression {} for consumer {} is outside finite f64 range",
expr.get(),
consumer.get()
),
Self::Evaluation(error) => error.fmt(formatter),
Self::Bigint(error) => error.fmt(formatter),
Self::Algnum(error) => error.fmt(formatter),
Self::Storage(error) => error.fmt(formatter),
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for StorageError {}
#[cfg(feature = "std")]
impl std::error::Error for GraphError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Node(error) => Some(error),
Self::Storage(error) => Some(error),
_ => None,
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for InsertError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Value(error) => Some(error),
Self::Storage(error) => Some(error),
Self::DuplicateId { .. } => None,
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for EvalError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Bigint(error) => Some(error),
Self::Monomial(error) => Some(error),
Self::FormSum(error) => Some(error),
Self::Algnum(error) => Some(error),
_ => None,
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for ResolveError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Evaluation(error) => Some(error),
Self::Bigint(error) => Some(error),
Self::Algnum(error) => Some(error),
Self::Storage(error) => Some(error),
_ => None,
}
}
}
impl From<BigintError> for EvalError {
fn from(error: BigintError) -> Self {
Self::Bigint(error)
}
}
impl From<MonomialErrorKind> for EvalError {
fn from(error: MonomialErrorKind) -> Self {
Self::Monomial(error)
}
}
impl From<FormSumErrorKind> for EvalError {
fn from(error: FormSumErrorKind) -> Self {
Self::FormSum(error)
}
}
impl From<AlgnumError> for EvalError {
fn from(error: AlgnumError) -> Self {
Self::Algnum(error)
}
}
impl From<StorageError> for InsertError {
fn from(error: StorageError) -> Self {
Self::Storage(error)
}
}
pub(crate) fn try_clone_eval_error(error: &EvalError) -> Result<EvalError, EvalError> {
match error {
EvalError::DivisionByZero => Ok(EvalError::DivisionByZero),
EvalError::UndefinedZeroPower => Ok(EvalError::UndefinedZeroPower),
EvalError::ZeroToNegativePower => Ok(EvalError::ZeroToNegativePower),
EvalError::EvenRootOfNegative => Ok(EvalError::EvenRootOfNegative),
EvalError::Bigint(error) => Ok(EvalError::Bigint(try_clone_bigint_error(error)?)),
EvalError::Monomial(error) => error
.try_clone()
.map(EvalError::Monomial)
.map_err(EvalError::Monomial),
EvalError::FormSum(error) => Ok(EvalError::FormSum(try_clone_formsum_error(error)?)),
EvalError::Algnum(error) => Ok(EvalError::Algnum(try_clone_algnum_error(error)?)),
}
}
fn try_clone_bigint_error(error: &BigintError) -> Result<BigintError, EvalError> {
Ok(match error {
BigintError::CapacityOverflow => BigintError::CapacityOverflow,
BigintError::AllocationFailure { requested_limbs } => BigintError::AllocationFailure {
requested_limbs: *requested_limbs,
},
BigintError::UnsignedUnderflow => BigintError::UnsignedUnderflow,
BigintError::DivisionByZero => BigintError::DivisionByZero,
BigintError::NonExactDivision => BigintError::NonExactDivision,
BigintError::ZeroDenominator => BigintError::ZeroDenominator,
BigintError::NonFiniteFloat => BigintError::NonFiniteFloat,
BigintError::FloatOutOfRange => BigintError::FloatOutOfRange,
BigintError::InvalidInterval => BigintError::InvalidInterval,
BigintError::ExponentOverflow { required, maximum } => BigintError::ExponentOverflow {
required: required.try_clone().map_err(EvalError::Bigint)?,
maximum: *maximum,
},
})
}
fn try_clone_formsum_error(error: &FormSumErrorKind) -> Result<FormSumErrorKind, EvalError> {
Ok(match error {
FormSumErrorKind::DivisionByZero => FormSumErrorKind::DivisionByZero,
FormSumErrorKind::DimensionOverflow {
resource,
required,
maximum,
} => FormSumErrorKind::DimensionOverflow {
resource: *resource,
required: required.try_clone().map_err(EvalError::Bigint)?,
maximum: maximum.try_clone().map_err(EvalError::Bigint)?,
},
FormSumErrorKind::AllocationFailure {
resource,
requested,
} => FormSumErrorKind::AllocationFailure {
resource: *resource,
requested: *requested,
},
FormSumErrorKind::Bigint(error) => FormSumErrorKind::Bigint(try_clone_bigint_error(error)?),
FormSumErrorKind::Monomial(error) => {
FormSumErrorKind::Monomial(error.try_clone().map_err(EvalError::Monomial)?)
}
})
}
fn try_clone_algnum_error(error: &AlgnumError) -> Result<AlgnumError, EvalError> {
Ok(match error {
AlgnumError::ZeroPolynomial => AlgnumError::ZeroPolynomial,
AlgnumError::InvalidIsolation => AlgnumError::InvalidIsolation,
AlgnumError::NoTargetRoot => AlgnumError::NoTargetRoot,
AlgnumError::MultipleTargetRoots => AlgnumError::MultipleTargetRoots,
AlgnumError::DivisionByZero => AlgnumError::DivisionByZero,
AlgnumError::UndefinedZeroPower => AlgnumError::UndefinedZeroPower,
AlgnumError::ZeroToNegativePower => AlgnumError::ZeroToNegativePower,
AlgnumError::ZeroRootDegree => AlgnumError::ZeroRootDegree,
AlgnumError::EvenRootOfNegative => AlgnumError::EvenRootOfNegative,
AlgnumError::RepresentationLimit {
resource,
required,
maximum,
} => AlgnumError::RepresentationLimit {
resource: *resource,
required: required.try_clone().map_err(EvalError::Bigint)?,
maximum: maximum.try_clone().map_err(EvalError::Bigint)?,
},
AlgnumError::AllocationLimit {
resource,
required,
maximum,
} => AlgnumError::AllocationLimit {
resource: *resource,
required: required.try_clone().map_err(EvalError::Bigint)?,
maximum: maximum.try_clone().map_err(EvalError::Bigint)?,
},
AlgnumError::AllocationFailure {
resource,
requested,
} => AlgnumError::AllocationFailure {
resource: *resource,
requested: *requested,
},
AlgnumError::Bigint(error) => AlgnumError::Bigint(try_clone_bigint_error(error)?),
AlgnumError::FormSum(error) => AlgnumError::FormSum(try_clone_formsum_error(error)?),
})
}
#[cfg(all(test, feature = "std"))]
mod tests {
use std::error::Error;
use neco_bigint::BigintError;
use neco_formsum::FormSumErrorKind;
use neco_monomial::MonomialErrorKind;
use crate::{EvalError, GraphError, InsertError, ResolveError, StorageError, StorageResource};
#[test]
fn error_sources_are_exactly_the_owned_lower_failures() {
let bigint = EvalError::Bigint(BigintError::DivisionByZero);
assert!(core::ptr::eq(
bigint
.source()
.unwrap()
.downcast_ref::<BigintError>()
.unwrap(),
match &bigint {
EvalError::Bigint(error) => error,
_ => unreachable!(),
}
));
let monomial = EvalError::Monomial(MonomialErrorKind::DivisionByZero);
assert!(monomial.source().unwrap().is::<MonomialErrorKind>());
let form_sum = EvalError::FormSum(FormSumErrorKind::DivisionByZero);
assert!(form_sum.source().unwrap().is::<FormSumErrorKind>());
let graph = GraphError::Node(EvalError::DivisionByZero);
assert!(graph.source().unwrap().is::<EvalError>());
let insert = InsertError::Value(EvalError::DivisionByZero);
assert!(insert.source().unwrap().is::<EvalError>());
let resolve = ResolveError::Evaluation(EvalError::DivisionByZero);
assert!(resolve.source().unwrap().is::<EvalError>());
let storage = StorageError::CapacityOverflow {
resource: StorageResource::GraphNodes,
};
let graph_storage = GraphError::Storage(storage);
assert!(graph_storage.source().unwrap().is::<StorageError>());
assert!(EvalError::DivisionByZero.source().is_none());
assert!(GraphError::IdExhausted.source().is_none());
assert!(InsertError::DuplicateId {
resource: StorageResource::AtomEntries,
id: 1,
}
.source()
.is_none());
}
#[test]
fn lower_error_conversions_preserve_variants_and_payloads() {
assert_eq!(
EvalError::from(MonomialErrorKind::AllocationFailure {
requested_elements: 23,
}),
EvalError::Monomial(MonomialErrorKind::AllocationFailure {
requested_elements: 23,
})
);
assert_eq!(
EvalError::from(FormSumErrorKind::DivisionByZero),
EvalError::FormSum(FormSumErrorKind::DivisionByZero)
);
assert_eq!(
EvalError::from(BigintError::AllocationFailure { requested_limbs: 5 }),
EvalError::Bigint(BigintError::AllocationFailure { requested_limbs: 5 })
);
}
}