1use core::fmt;
2
3use neco_algnum::AlgnumError;
4use neco_bigint::BigintError;
5use neco_formsum::FormSumErrorKind;
6use neco_monomial::MonomialErrorKind;
7
8use crate::{AtomId, ConsumerId, ExprId, StorageResource};
9
10#[derive(Debug, Eq, PartialEq)]
11pub enum StorageError {
12 CapacityOverflow {
13 resource: StorageResource,
14 },
15 AllocationFailure {
16 resource: StorageResource,
17 requested_elements: usize,
18 },
19}
20
21#[derive(Debug, Eq, PartialEq)]
22pub enum GraphError {
23 IdExhausted,
24 InvalidChildId { child: ExprId, next: ExprId },
25 Node(EvalError),
26 Storage(StorageError),
27}
28
29#[derive(Debug, Eq, PartialEq)]
30pub enum InsertError {
31 DuplicateId { resource: StorageResource, id: u32 },
32 Value(EvalError),
33 Storage(StorageError),
34}
35
36#[derive(Debug, Eq, PartialEq)]
37pub enum EvalError {
38 DivisionByZero,
39 UndefinedZeroPower,
40 ZeroToNegativePower,
41 EvenRootOfNegative,
42 Bigint(BigintError),
43 Monomial(MonomialErrorKind),
44 FormSum(FormSumErrorKind),
45 Algnum(AlgnumError),
46}
47
48#[derive(Debug, Eq, PartialEq)]
49pub enum ResolveError {
50 MissingAssignment { consumer: ConsumerId },
51 UnknownExprId { consumer: ConsumerId, expr: ExprId },
52 UnknownAtomId { expr: ExprId, atom: AtomId },
53 FloatOutOfRange { consumer: ConsumerId, expr: ExprId },
54 Evaluation(EvalError),
55 Bigint(BigintError),
56 Algnum(AlgnumError),
57 Storage(StorageError),
58}
59
60impl fmt::Display for StorageError {
61 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
62 match self {
63 Self::CapacityOverflow { resource } => {
64 write!(formatter, "capacity overflow for {resource:?}")
65 }
66 Self::AllocationFailure {
67 resource,
68 requested_elements,
69 } => write!(
70 formatter,
71 "allocation failed for {resource:?}: requested {requested_elements} elements"
72 ),
73 }
74 }
75}
76
77impl fmt::Display for GraphError {
78 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
79 match self {
80 Self::IdExhausted => formatter.write_str("expression graph ID space is exhausted"),
81 Self::InvalidChildId { child, next } => write!(
82 formatter,
83 "expression child {} is not earlier than next expression {}",
84 child.get(),
85 next.get()
86 ),
87 Self::Node(error) => write!(formatter, "expression node clone failed: {error}"),
88 Self::Storage(error) => error.fmt(formatter),
89 }
90 }
91}
92
93impl fmt::Display for InsertError {
94 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
95 match self {
96 Self::DuplicateId { resource, id } => {
97 write!(formatter, "duplicate ID {id} for {resource:?}")
98 }
99 Self::Value(error) => write!(formatter, "stored value clone failed: {error}"),
100 Self::Storage(error) => error.fmt(formatter),
101 }
102 }
103}
104
105impl fmt::Display for EvalError {
106 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
107 match self {
108 Self::DivisionByZero => formatter.write_str("division by zero"),
109 Self::UndefinedZeroPower => formatter.write_str("zero raised to the zero power"),
110 Self::ZeroToNegativePower => formatter.write_str("zero raised to a negative power"),
111 Self::EvenRootOfNegative => formatter.write_str("even root of a negative value"),
112 Self::Bigint(error) => error.fmt(formatter),
113 Self::Monomial(error) => error.fmt(formatter),
114 Self::FormSum(error) => error.fmt(formatter),
115 Self::Algnum(error) => error.fmt(formatter),
116 }
117 }
118}
119
120impl fmt::Display for ResolveError {
121 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
122 match self {
123 Self::MissingAssignment { consumer } => {
124 write!(formatter, "consumer {} has no assignment", consumer.get())
125 }
126 Self::UnknownExprId { consumer, expr } => write!(
127 formatter,
128 "consumer {} refers to unknown expression {}",
129 consumer.get(),
130 expr.get()
131 ),
132 Self::UnknownAtomId { expr, atom } => write!(
133 formatter,
134 "expression {} refers to unknown atom {}",
135 expr.get(),
136 atom.get()
137 ),
138 Self::FloatOutOfRange { consumer, expr } => write!(
139 formatter,
140 "expression {} for consumer {} is outside finite f64 range",
141 expr.get(),
142 consumer.get()
143 ),
144 Self::Evaluation(error) => error.fmt(formatter),
145 Self::Bigint(error) => error.fmt(formatter),
146 Self::Algnum(error) => error.fmt(formatter),
147 Self::Storage(error) => error.fmt(formatter),
148 }
149 }
150}
151
152#[cfg(feature = "std")]
153impl std::error::Error for StorageError {}
154
155#[cfg(feature = "std")]
156impl std::error::Error for GraphError {
157 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
158 match self {
159 Self::Node(error) => Some(error),
160 Self::Storage(error) => Some(error),
161 _ => None,
162 }
163 }
164}
165
166#[cfg(feature = "std")]
167impl std::error::Error for InsertError {
168 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
169 match self {
170 Self::Value(error) => Some(error),
171 Self::Storage(error) => Some(error),
172 Self::DuplicateId { .. } => None,
173 }
174 }
175}
176
177#[cfg(feature = "std")]
178impl std::error::Error for EvalError {
179 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
180 match self {
181 Self::Bigint(error) => Some(error),
182 Self::Monomial(error) => Some(error),
183 Self::FormSum(error) => Some(error),
184 Self::Algnum(error) => Some(error),
185 _ => None,
186 }
187 }
188}
189
190#[cfg(feature = "std")]
191impl std::error::Error for ResolveError {
192 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
193 match self {
194 Self::Evaluation(error) => Some(error),
195 Self::Bigint(error) => Some(error),
196 Self::Algnum(error) => Some(error),
197 Self::Storage(error) => Some(error),
198 _ => None,
199 }
200 }
201}
202
203impl From<BigintError> for EvalError {
204 fn from(error: BigintError) -> Self {
205 Self::Bigint(error)
206 }
207}
208
209impl From<MonomialErrorKind> for EvalError {
210 fn from(error: MonomialErrorKind) -> Self {
211 Self::Monomial(error)
212 }
213}
214
215impl From<FormSumErrorKind> for EvalError {
216 fn from(error: FormSumErrorKind) -> Self {
217 Self::FormSum(error)
218 }
219}
220
221impl From<AlgnumError> for EvalError {
222 fn from(error: AlgnumError) -> Self {
223 Self::Algnum(error)
224 }
225}
226
227impl From<StorageError> for InsertError {
228 fn from(error: StorageError) -> Self {
229 Self::Storage(error)
230 }
231}
232
233pub(crate) fn try_clone_eval_error(error: &EvalError) -> Result<EvalError, EvalError> {
234 match error {
235 EvalError::DivisionByZero => Ok(EvalError::DivisionByZero),
236 EvalError::UndefinedZeroPower => Ok(EvalError::UndefinedZeroPower),
237 EvalError::ZeroToNegativePower => Ok(EvalError::ZeroToNegativePower),
238 EvalError::EvenRootOfNegative => Ok(EvalError::EvenRootOfNegative),
239 EvalError::Bigint(error) => Ok(EvalError::Bigint(try_clone_bigint_error(error)?)),
240 EvalError::Monomial(error) => error
241 .try_clone()
242 .map(EvalError::Monomial)
243 .map_err(EvalError::Monomial),
244 EvalError::FormSum(error) => Ok(EvalError::FormSum(try_clone_formsum_error(error)?)),
245 EvalError::Algnum(error) => Ok(EvalError::Algnum(try_clone_algnum_error(error)?)),
246 }
247}
248
249fn try_clone_bigint_error(error: &BigintError) -> Result<BigintError, EvalError> {
250 Ok(match error {
251 BigintError::CapacityOverflow => BigintError::CapacityOverflow,
252 BigintError::AllocationFailure { requested_limbs } => BigintError::AllocationFailure {
253 requested_limbs: *requested_limbs,
254 },
255 BigintError::UnsignedUnderflow => BigintError::UnsignedUnderflow,
256 BigintError::DivisionByZero => BigintError::DivisionByZero,
257 BigintError::NonExactDivision => BigintError::NonExactDivision,
258 BigintError::ZeroDenominator => BigintError::ZeroDenominator,
259 BigintError::NonFiniteFloat => BigintError::NonFiniteFloat,
260 BigintError::FloatOutOfRange => BigintError::FloatOutOfRange,
261 BigintError::InvalidInterval => BigintError::InvalidInterval,
262 BigintError::ExponentOverflow { required, maximum } => BigintError::ExponentOverflow {
263 required: required.try_clone().map_err(EvalError::Bigint)?,
264 maximum: *maximum,
265 },
266 })
267}
268
269fn try_clone_formsum_error(error: &FormSumErrorKind) -> Result<FormSumErrorKind, EvalError> {
270 Ok(match error {
271 FormSumErrorKind::DivisionByZero => FormSumErrorKind::DivisionByZero,
272 FormSumErrorKind::DimensionOverflow {
273 resource,
274 required,
275 maximum,
276 } => FormSumErrorKind::DimensionOverflow {
277 resource: *resource,
278 required: required.try_clone().map_err(EvalError::Bigint)?,
279 maximum: maximum.try_clone().map_err(EvalError::Bigint)?,
280 },
281 FormSumErrorKind::AllocationFailure {
282 resource,
283 requested,
284 } => FormSumErrorKind::AllocationFailure {
285 resource: *resource,
286 requested: *requested,
287 },
288 FormSumErrorKind::Bigint(error) => FormSumErrorKind::Bigint(try_clone_bigint_error(error)?),
289 FormSumErrorKind::Monomial(error) => {
290 FormSumErrorKind::Monomial(error.try_clone().map_err(EvalError::Monomial)?)
291 }
292 })
293}
294
295fn try_clone_algnum_error(error: &AlgnumError) -> Result<AlgnumError, EvalError> {
296 Ok(match error {
297 AlgnumError::ZeroPolynomial => AlgnumError::ZeroPolynomial,
298 AlgnumError::InvalidIsolation => AlgnumError::InvalidIsolation,
299 AlgnumError::NoTargetRoot => AlgnumError::NoTargetRoot,
300 AlgnumError::MultipleTargetRoots => AlgnumError::MultipleTargetRoots,
301 AlgnumError::DivisionByZero => AlgnumError::DivisionByZero,
302 AlgnumError::UndefinedZeroPower => AlgnumError::UndefinedZeroPower,
303 AlgnumError::ZeroToNegativePower => AlgnumError::ZeroToNegativePower,
304 AlgnumError::ZeroRootDegree => AlgnumError::ZeroRootDegree,
305 AlgnumError::EvenRootOfNegative => AlgnumError::EvenRootOfNegative,
306 AlgnumError::RepresentationLimit {
307 resource,
308 required,
309 maximum,
310 } => AlgnumError::RepresentationLimit {
311 resource: *resource,
312 required: required.try_clone().map_err(EvalError::Bigint)?,
313 maximum: maximum.try_clone().map_err(EvalError::Bigint)?,
314 },
315 AlgnumError::AllocationLimit {
316 resource,
317 required,
318 maximum,
319 } => AlgnumError::AllocationLimit {
320 resource: *resource,
321 required: required.try_clone().map_err(EvalError::Bigint)?,
322 maximum: maximum.try_clone().map_err(EvalError::Bigint)?,
323 },
324 AlgnumError::AllocationFailure {
325 resource,
326 requested,
327 } => AlgnumError::AllocationFailure {
328 resource: *resource,
329 requested: *requested,
330 },
331 AlgnumError::Bigint(error) => AlgnumError::Bigint(try_clone_bigint_error(error)?),
332 AlgnumError::FormSum(error) => AlgnumError::FormSum(try_clone_formsum_error(error)?),
333 })
334}
335
336#[cfg(all(test, feature = "std"))]
337mod tests {
338 use std::error::Error;
339
340 use neco_bigint::BigintError;
341 use neco_formsum::FormSumErrorKind;
342 use neco_monomial::MonomialErrorKind;
343
344 use crate::{EvalError, GraphError, InsertError, ResolveError, StorageError, StorageResource};
345
346 #[test]
347 fn error_sources_are_exactly_the_owned_lower_failures() {
348 let bigint = EvalError::Bigint(BigintError::DivisionByZero);
349 assert!(core::ptr::eq(
350 bigint
351 .source()
352 .unwrap()
353 .downcast_ref::<BigintError>()
354 .unwrap(),
355 match &bigint {
356 EvalError::Bigint(error) => error,
357 _ => unreachable!(),
358 }
359 ));
360 let monomial = EvalError::Monomial(MonomialErrorKind::DivisionByZero);
361 assert!(monomial.source().unwrap().is::<MonomialErrorKind>());
362 let form_sum = EvalError::FormSum(FormSumErrorKind::DivisionByZero);
363 assert!(form_sum.source().unwrap().is::<FormSumErrorKind>());
364
365 let graph = GraphError::Node(EvalError::DivisionByZero);
366 assert!(graph.source().unwrap().is::<EvalError>());
367 let insert = InsertError::Value(EvalError::DivisionByZero);
368 assert!(insert.source().unwrap().is::<EvalError>());
369 let resolve = ResolveError::Evaluation(EvalError::DivisionByZero);
370 assert!(resolve.source().unwrap().is::<EvalError>());
371 let storage = StorageError::CapacityOverflow {
372 resource: StorageResource::GraphNodes,
373 };
374 let graph_storage = GraphError::Storage(storage);
375 assert!(graph_storage.source().unwrap().is::<StorageError>());
376
377 assert!(EvalError::DivisionByZero.source().is_none());
378 assert!(GraphError::IdExhausted.source().is_none());
379 assert!(InsertError::DuplicateId {
380 resource: StorageResource::AtomEntries,
381 id: 1,
382 }
383 .source()
384 .is_none());
385 }
386
387 #[test]
388 fn lower_error_conversions_preserve_variants_and_payloads() {
389 assert_eq!(
390 EvalError::from(MonomialErrorKind::AllocationFailure {
391 requested_elements: 23,
392 }),
393 EvalError::Monomial(MonomialErrorKind::AllocationFailure {
394 requested_elements: 23,
395 })
396 );
397 assert_eq!(
398 EvalError::from(FormSumErrorKind::DivisionByZero),
399 EvalError::FormSum(FormSumErrorKind::DivisionByZero)
400 );
401 assert_eq!(
402 EvalError::from(BigintError::AllocationFailure { requested_limbs: 5 }),
403 EvalError::Bigint(BigintError::AllocationFailure { requested_limbs: 5 })
404 );
405 }
406}