1use alloc::boxed::Box;
2use core::fmt;
3
4use neco_algnum::AlgnumError;
5use neco_bigint::{BigintError, Dyadic};
6use neco_formsum::FormSumErrorKind;
7use neco_monomial::MonomialErrorKind;
8
9use crate::product::ComputationProductId;
10use crate::{AbsoluteBits, AtomId, ConsumerId, ExprId, OwnerId, StorageResource};
11
12#[derive(Debug, Eq, PartialEq)]
13pub enum StorageError {
14 CapacityOverflow {
15 resource: StorageResource,
16 },
17 AllocationFailure {
18 resource: StorageResource,
19 requested_elements: usize,
20 },
21}
22
23#[derive(Debug, Eq, PartialEq)]
24pub enum GraphError {
25 IdExhausted,
26 InvalidChildId { child: ExprId, next: ExprId },
27 Node(EvalError),
28 Storage(StorageError),
29}
30
31#[derive(Debug, Eq, PartialEq)]
32pub enum InsertError {
33 DuplicateId { resource: StorageResource, id: u32 },
34 Value(EvalError),
35 Storage(StorageError),
36}
37
38#[derive(Debug, Eq, PartialEq)]
39pub enum EvalError {
40 DivisionByZero,
41 UndefinedZeroPower,
42 ZeroToNegativePower,
43 EvenRootOfNegative,
44 Bigint(BigintError),
45 Monomial(MonomialErrorKind),
46 FormSum(FormSumErrorKind),
47 Algnum(AlgnumError),
48}
49
50#[derive(Debug, Eq, PartialEq)]
51pub enum ResolveError {
52 MissingAssignment { consumer: ConsumerId },
53 UnknownExprId { consumer: ConsumerId, expr: ExprId },
54 UnknownAtomId { expr: ExprId, atom: AtomId },
55 FloatOutOfRange { consumer: ConsumerId, expr: ExprId },
56 Evaluation(EvalError),
57 Bigint(BigintError),
58 Algnum(AlgnumError),
59 Storage(StorageError),
60}
61
62impl fmt::Display for StorageError {
63 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
64 match self {
65 Self::CapacityOverflow { resource } => {
66 write!(formatter, "capacity overflow for {resource:?}")
67 }
68 Self::AllocationFailure {
69 resource,
70 requested_elements,
71 } => write!(
72 formatter,
73 "allocation failed for {resource:?}: requested {requested_elements} elements"
74 ),
75 }
76 }
77}
78
79impl fmt::Display for GraphError {
80 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
81 match self {
82 Self::IdExhausted => formatter.write_str("expression graph ID space is exhausted"),
83 Self::InvalidChildId { child, next } => write!(
84 formatter,
85 "expression child {} is not earlier than next expression {}",
86 child.get(),
87 next.get()
88 ),
89 Self::Node(error) => write!(formatter, "expression node clone failed: {error}"),
90 Self::Storage(error) => error.fmt(formatter),
91 }
92 }
93}
94
95impl fmt::Display for InsertError {
96 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
97 match self {
98 Self::DuplicateId { resource, id } => {
99 write!(formatter, "duplicate ID {id} for {resource:?}")
100 }
101 Self::Value(error) => write!(formatter, "stored value clone failed: {error}"),
102 Self::Storage(error) => error.fmt(formatter),
103 }
104 }
105}
106
107impl fmt::Display for EvalError {
108 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
109 match self {
110 Self::DivisionByZero => formatter.write_str("division by zero"),
111 Self::UndefinedZeroPower => formatter.write_str("zero raised to the zero power"),
112 Self::ZeroToNegativePower => formatter.write_str("zero raised to a negative power"),
113 Self::EvenRootOfNegative => formatter.write_str("even root of a negative value"),
114 Self::Bigint(error) => error.fmt(formatter),
115 Self::Monomial(error) => error.fmt(formatter),
116 Self::FormSum(error) => error.fmt(formatter),
117 Self::Algnum(error) => error.fmt(formatter),
118 }
119 }
120}
121
122impl fmt::Display for ResolveError {
123 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
124 match self {
125 Self::MissingAssignment { consumer } => {
126 write!(formatter, "consumer {} has no assignment", consumer.get())
127 }
128 Self::UnknownExprId { consumer, expr } => write!(
129 formatter,
130 "consumer {} refers to unknown expression {}",
131 consumer.get(),
132 expr.get()
133 ),
134 Self::UnknownAtomId { expr, atom } => write!(
135 formatter,
136 "expression {} refers to unknown atom {}",
137 expr.get(),
138 atom.get()
139 ),
140 Self::FloatOutOfRange { consumer, expr } => write!(
141 formatter,
142 "expression {} for consumer {} is outside finite f64 range",
143 expr.get(),
144 consumer.get()
145 ),
146 Self::Evaluation(error) => error.fmt(formatter),
147 Self::Bigint(error) => error.fmt(formatter),
148 Self::Algnum(error) => error.fmt(formatter),
149 Self::Storage(error) => error.fmt(formatter),
150 }
151 }
152}
153
154#[cfg(feature = "std")]
155impl std::error::Error for StorageError {}
156
157#[cfg(feature = "std")]
158impl std::error::Error for GraphError {
159 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
160 match self {
161 Self::Node(error) => Some(error),
162 Self::Storage(error) => Some(error),
163 _ => None,
164 }
165 }
166}
167
168#[cfg(feature = "std")]
169impl std::error::Error for InsertError {
170 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
171 match self {
172 Self::Value(error) => Some(error),
173 Self::Storage(error) => Some(error),
174 Self::DuplicateId { .. } => None,
175 }
176 }
177}
178
179#[cfg(feature = "std")]
180impl std::error::Error for EvalError {
181 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
182 match self {
183 Self::Bigint(error) => Some(error),
184 Self::Monomial(error) => Some(error),
185 Self::FormSum(error) => Some(error),
186 Self::Algnum(error) => Some(error),
187 _ => None,
188 }
189 }
190}
191
192#[cfg(feature = "std")]
193impl std::error::Error for ResolveError {
194 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
195 match self {
196 Self::Evaluation(error) => Some(error),
197 Self::Bigint(error) => Some(error),
198 Self::Algnum(error) => Some(error),
199 Self::Storage(error) => Some(error),
200 _ => None,
201 }
202 }
203}
204
205impl From<BigintError> for EvalError {
206 fn from(error: BigintError) -> Self {
207 Self::Bigint(error)
208 }
209}
210
211impl From<MonomialErrorKind> for EvalError {
212 fn from(error: MonomialErrorKind) -> Self {
213 Self::Monomial(error)
214 }
215}
216
217impl From<FormSumErrorKind> for EvalError {
218 fn from(error: FormSumErrorKind) -> Self {
219 Self::FormSum(error)
220 }
221}
222
223impl From<AlgnumError> for EvalError {
224 fn from(error: AlgnumError) -> Self {
225 Self::Algnum(error)
226 }
227}
228
229impl From<StorageError> for InsertError {
230 fn from(error: StorageError) -> Self {
231 Self::Storage(error)
232 }
233}
234
235pub(crate) fn try_clone_eval_error(error: &EvalError) -> Result<EvalError, EvalError> {
236 match error {
237 EvalError::DivisionByZero => Ok(EvalError::DivisionByZero),
238 EvalError::UndefinedZeroPower => Ok(EvalError::UndefinedZeroPower),
239 EvalError::ZeroToNegativePower => Ok(EvalError::ZeroToNegativePower),
240 EvalError::EvenRootOfNegative => Ok(EvalError::EvenRootOfNegative),
241 EvalError::Bigint(error) => Ok(EvalError::Bigint(try_clone_bigint_error(error)?)),
242 EvalError::Monomial(error) => error
243 .try_clone()
244 .map(EvalError::Monomial)
245 .map_err(EvalError::Monomial),
246 EvalError::FormSum(error) => Ok(EvalError::FormSum(try_clone_formsum_error(error)?)),
247 EvalError::Algnum(error) => Ok(EvalError::Algnum(try_clone_algnum_error(error)?)),
248 }
249}
250
251fn try_clone_bigint_error(error: &BigintError) -> Result<BigintError, EvalError> {
252 Ok(match error {
253 BigintError::CapacityOverflow => BigintError::CapacityOverflow,
254 BigintError::AllocationFailure { requested_limbs } => BigintError::AllocationFailure {
255 requested_limbs: *requested_limbs,
256 },
257 BigintError::UnsignedUnderflow => BigintError::UnsignedUnderflow,
258 BigintError::DivisionByZero => BigintError::DivisionByZero,
259 BigintError::NonExactDivision => BigintError::NonExactDivision,
260 BigintError::ZeroDenominator => BigintError::ZeroDenominator,
261 BigintError::NonFiniteFloat => BigintError::NonFiniteFloat,
262 BigintError::FloatOutOfRange => BigintError::FloatOutOfRange,
263 BigintError::InvalidInterval => BigintError::InvalidInterval,
264 BigintError::ExponentOverflow { required, maximum } => BigintError::ExponentOverflow {
265 required: required.try_clone().map_err(EvalError::Bigint)?,
266 maximum: *maximum,
267 },
268 })
269}
270
271fn try_clone_formsum_error(error: &FormSumErrorKind) -> Result<FormSumErrorKind, EvalError> {
272 Ok(match error {
273 FormSumErrorKind::DivisionByZero => FormSumErrorKind::DivisionByZero,
274 FormSumErrorKind::DimensionOverflow {
275 resource,
276 required,
277 maximum,
278 } => FormSumErrorKind::DimensionOverflow {
279 resource: *resource,
280 required: required.try_clone().map_err(EvalError::Bigint)?,
281 maximum: maximum.try_clone().map_err(EvalError::Bigint)?,
282 },
283 FormSumErrorKind::AllocationFailure {
284 resource,
285 requested,
286 } => FormSumErrorKind::AllocationFailure {
287 resource: *resource,
288 requested: *requested,
289 },
290 FormSumErrorKind::Bigint(error) => FormSumErrorKind::Bigint(try_clone_bigint_error(error)?),
291 FormSumErrorKind::Monomial(error) => {
292 FormSumErrorKind::Monomial(error.try_clone().map_err(EvalError::Monomial)?)
293 }
294 })
295}
296
297fn try_clone_algnum_error(error: &AlgnumError) -> Result<AlgnumError, EvalError> {
298 Ok(match error {
299 AlgnumError::ZeroPolynomial => AlgnumError::ZeroPolynomial,
300 AlgnumError::InvalidIsolation => AlgnumError::InvalidIsolation,
301 AlgnumError::NoTargetRoot => AlgnumError::NoTargetRoot,
302 AlgnumError::MultipleTargetRoots => AlgnumError::MultipleTargetRoots,
303 AlgnumError::DivisionByZero => AlgnumError::DivisionByZero,
304 AlgnumError::UndefinedZeroPower => AlgnumError::UndefinedZeroPower,
305 AlgnumError::ZeroToNegativePower => AlgnumError::ZeroToNegativePower,
306 AlgnumError::ZeroRootDegree => AlgnumError::ZeroRootDegree,
307 AlgnumError::EvenRootOfNegative => AlgnumError::EvenRootOfNegative,
308 AlgnumError::RepresentationLimit {
309 resource,
310 required,
311 maximum,
312 } => AlgnumError::RepresentationLimit {
313 resource: *resource,
314 required: required.try_clone().map_err(EvalError::Bigint)?,
315 maximum: maximum.try_clone().map_err(EvalError::Bigint)?,
316 },
317 AlgnumError::AllocationLimit {
318 resource,
319 required,
320 maximum,
321 } => AlgnumError::AllocationLimit {
322 resource: *resource,
323 required: required.try_clone().map_err(EvalError::Bigint)?,
324 maximum: maximum.try_clone().map_err(EvalError::Bigint)?,
325 },
326 AlgnumError::AllocationFailure {
327 resource,
328 requested,
329 } => AlgnumError::AllocationFailure {
330 resource: *resource,
331 requested: *requested,
332 },
333 AlgnumError::Bigint(error) => AlgnumError::Bigint(try_clone_bigint_error(error)?),
334 AlgnumError::FormSum(error) => AlgnumError::FormSum(try_clone_formsum_error(error)?),
335 })
336}
337
338#[cfg(all(test, feature = "std"))]
339mod tests {
340 use std::error::Error;
341
342 use neco_bigint::BigintError;
343 use neco_formsum::FormSumErrorKind;
344 use neco_monomial::MonomialErrorKind;
345
346 use crate::{EvalError, GraphError, InsertError, ResolveError, StorageError, StorageResource};
347
348 #[test]
349 fn error_sources_are_exactly_the_owned_lower_failures() {
350 let bigint = EvalError::Bigint(BigintError::DivisionByZero);
351 assert!(core::ptr::eq(
352 bigint
353 .source()
354 .unwrap()
355 .downcast_ref::<BigintError>()
356 .unwrap(),
357 match &bigint {
358 EvalError::Bigint(error) => error,
359 _ => unreachable!(),
360 }
361 ));
362 let monomial = EvalError::Monomial(MonomialErrorKind::DivisionByZero);
363 assert!(monomial.source().unwrap().is::<MonomialErrorKind>());
364 let form_sum = EvalError::FormSum(FormSumErrorKind::DivisionByZero);
365 assert!(form_sum.source().unwrap().is::<FormSumErrorKind>());
366
367 let graph = GraphError::Node(EvalError::DivisionByZero);
368 assert!(graph.source().unwrap().is::<EvalError>());
369 let insert = InsertError::Value(EvalError::DivisionByZero);
370 assert!(insert.source().unwrap().is::<EvalError>());
371 let resolve = ResolveError::Evaluation(EvalError::DivisionByZero);
372 assert!(resolve.source().unwrap().is::<EvalError>());
373 let storage = StorageError::CapacityOverflow {
374 resource: StorageResource::GraphNodes,
375 };
376 let graph_storage = GraphError::Storage(storage);
377 assert!(graph_storage.source().unwrap().is::<StorageError>());
378
379 assert!(EvalError::DivisionByZero.source().is_none());
380 assert!(GraphError::IdExhausted.source().is_none());
381 assert!(InsertError::DuplicateId {
382 resource: StorageResource::AtomEntries,
383 id: 1,
384 }
385 .source()
386 .is_none());
387 }
388
389 #[test]
390 fn lower_error_conversions_preserve_variants_and_payloads() {
391 assert_eq!(
392 EvalError::from(MonomialErrorKind::AllocationFailure {
393 requested_elements: 23,
394 }),
395 EvalError::Monomial(MonomialErrorKind::AllocationFailure {
396 requested_elements: 23,
397 })
398 );
399 assert_eq!(
400 EvalError::from(FormSumErrorKind::DivisionByZero),
401 EvalError::FormSum(FormSumErrorKind::DivisionByZero)
402 );
403 assert_eq!(
404 EvalError::from(BigintError::AllocationFailure { requested_limbs: 5 }),
405 EvalError::Bigint(BigintError::AllocationFailure { requested_limbs: 5 })
406 );
407 }
408}
409
410#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
411pub enum FailureOperation {
412 Read,
413 Allocate,
414 Normalize,
415 Decide,
416 Resolve,
417 Assemble,
418}
419
420#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
421pub enum MatrixInputRole {
422 Matrix,
423 Stiffness,
424 Mass,
425 MassNormalization,
426}
427
428#[derive(Clone, Copy, Debug, Eq, PartialEq)]
429pub struct FailureLocation {
430 operation: FailureOperation,
431 consumer: Option<ConsumerId>,
432 expr: Option<ExprId>,
433 atom: Option<AtomId>,
434 decision: Option<u32>,
435 matrix_role: Option<MatrixInputRole>,
436 row: Option<usize>,
437 column: Option<usize>,
438}
439
440impl FailureLocation {
441 pub const fn operation(operation: FailureOperation) -> Self {
442 Self {
443 operation,
444 consumer: None,
445 expr: None,
446 atom: None,
447 decision: None,
448 matrix_role: None,
449 row: None,
450 column: None,
451 }
452 }
453
454 pub const fn with_consumer(mut self, consumer: ConsumerId) -> Self {
455 self.consumer = Some(consumer);
456 self
457 }
458
459 pub const fn with_expr(mut self, expr: ExprId) -> Self {
460 self.expr = Some(expr);
461 self
462 }
463
464 pub const fn with_atom(mut self, atom: AtomId) -> Self {
465 self.atom = Some(atom);
466 self
467 }
468
469 pub const fn with_decision(mut self, decision: u32) -> Self {
470 self.decision = Some(decision);
471 self
472 }
473
474 pub const fn with_matrix_role(mut self, role: MatrixInputRole) -> Self {
475 self.matrix_role = Some(role);
476 self
477 }
478
479 pub const fn with_matrix_location(mut self, row: usize, column: usize) -> Self {
480 self.row = Some(row);
481 self.column = Some(column);
482 self
483 }
484
485 pub const fn operation_kind(&self) -> FailureOperation {
486 self.operation
487 }
488
489 pub const fn consumer(&self) -> Option<ConsumerId> {
490 self.consumer
491 }
492
493 pub const fn expr(&self) -> Option<ExprId> {
494 self.expr
495 }
496
497 pub const fn atom(&self) -> Option<AtomId> {
498 self.atom
499 }
500
501 pub const fn decision(&self) -> Option<u32> {
502 self.decision
503 }
504
505 pub const fn matrix_role(&self) -> Option<MatrixInputRole> {
506 self.matrix_role
507 }
508
509 pub const fn role(&self) -> Option<MatrixInputRole> {
510 self.matrix_role()
511 }
512
513 pub const fn row(&self) -> Option<usize> {
514 self.row
515 }
516
517 pub const fn column(&self) -> Option<usize> {
518 self.column
519 }
520}
521#[derive(Clone, Debug, Eq, PartialEq)]
522pub struct ProvenanceRecord {
523 owner: Option<OwnerId>,
524 consumer_id: Option<ConsumerId>,
525 expr_id: Option<ExprId>,
526 precision: Option<AbsoluteBits>,
527 revision_identity: Option<&'static str>,
528 public_api_identity: Option<&'static str>,
529 product_identity: Option<ComputationProductId>,
530}
531
532impl ProvenanceRecord {
533 pub const fn new(
534 owner: Option<OwnerId>,
535 consumer_id: Option<ConsumerId>,
536 expr_id: Option<ExprId>,
537 precision: Option<AbsoluteBits>,
538 revision_identity: Option<&'static str>,
539 public_api_identity: Option<&'static str>,
540 ) -> Self {
541 Self {
542 owner,
543 consumer_id,
544 expr_id,
545 precision,
546 revision_identity,
547 public_api_identity,
548 product_identity: None,
549 }
550 }
551
552 pub fn with_product_identity(mut self, product_identity: ComputationProductId) -> Self {
553 self.product_identity = Some(product_identity);
554 self
555 }
556
557 pub const fn owner(&self) -> Option<OwnerId> {
558 self.owner
559 }
560
561 pub const fn consumer_id(&self) -> Option<ConsumerId> {
562 self.consumer_id
563 }
564
565 pub const fn expr_id(&self) -> Option<ExprId> {
566 self.expr_id
567 }
568
569 pub const fn precision(&self) -> Option<AbsoluteBits> {
570 self.precision
571 }
572
573 pub const fn revision_identity(&self) -> Option<&'static str> {
574 self.revision_identity
575 }
576
577 pub const fn public_api_identity(&self) -> Option<&'static str> {
578 self.public_api_identity
579 }
580
581 pub fn product_identity(&self) -> Option<ComputationProductId> {
582 self.product_identity.clone()
583 }
584}
585
586#[derive(Clone, Copy, Debug, Eq, PartialEq)]
587pub enum ProvenanceMismatchField {
588 Consumer,
589 Owner,
590 Expression,
591 Precision,
592 Source,
593 Product,
594}
595
596#[derive(Clone, Debug, Eq, PartialEq)]
597pub struct ProvenanceMismatchPayload {
598 field: ProvenanceMismatchField,
599 expected: ProvenanceRecord,
600 actual: ProvenanceRecord,
601}
602
603impl ProvenanceMismatchPayload {
604 pub fn new(
605 field: ProvenanceMismatchField,
606 expected: ProvenanceRecord,
607 actual: ProvenanceRecord,
608 ) -> Self {
609 Self {
610 field,
611 expected,
612 actual,
613 }
614 }
615
616 pub const fn field(&self) -> ProvenanceMismatchField {
617 self.field
618 }
619
620 pub fn expected(&self) -> ProvenanceRecord {
621 self.expected.clone()
622 }
623
624 pub fn actual(&self) -> ProvenanceRecord {
625 self.actual.clone()
626 }
627}
628
629#[derive(Clone, Copy, Debug, Eq, PartialEq)]
630pub enum MatrixInputMismatchField {
631 Shape,
632 Expression,
633 MissingExpression,
634 DuplicateExpression,
635 ExtraExpression,
636 NumericValue,
637}
638
639#[derive(Clone, Debug, Eq, PartialEq)]
640pub struct MatrixInputMismatchPayload {
641 field: MatrixInputMismatchField,
642 row: Option<usize>,
643 column: Option<usize>,
644 expected: ProvenanceRecord,
645 actual: ProvenanceRecord,
646 expected_product: Option<ComputationProductId>,
647 actual_product: Option<ComputationProductId>,
648 expected_expr: Option<ExprId>,
649 actual_expr: Option<ExprId>,
650 expected_value_bits: Option<u64>,
651 actual_value_bits: Option<u64>,
652}
653
654impl MatrixInputMismatchPayload {
655 pub fn new(
656 field: MatrixInputMismatchField,
657 expected: ProvenanceRecord,
658 actual: ProvenanceRecord,
659 ) -> Self {
660 Self {
661 field,
662 row: None,
663 column: None,
664 expected,
665 actual,
666 expected_product: None,
667 actual_product: None,
668 expected_expr: None,
669 actual_expr: None,
670 expected_value_bits: None,
671 actual_value_bits: None,
672 }
673 }
674
675 pub const fn field(&self) -> MatrixInputMismatchField {
676 self.field
677 }
678
679 pub const fn row(&self) -> Option<usize> {
680 self.row
681 }
682
683 pub const fn column(&self) -> Option<usize> {
684 self.column
685 }
686
687 pub const fn expected_expr(&self) -> Option<ExprId> {
688 self.expected_expr
689 }
690
691 pub const fn actual_expr(&self) -> Option<ExprId> {
692 self.actual_expr
693 }
694
695 pub const fn expected_value_bits(&self) -> Option<u64> {
696 self.expected_value_bits
697 }
698
699 pub const fn actual_value_bits(&self) -> Option<u64> {
700 self.actual_value_bits
701 }
702
703 pub fn expected_product_identity(&self) -> Option<ComputationProductId> {
704 self.expected_product.clone()
705 }
706
707 pub fn actual_product_identity(&self) -> Option<ComputationProductId> {
708 self.actual_product.clone()
709 }
710
711 pub fn expected(&self) -> ProvenanceRecord {
712 self.expected.clone()
713 }
714
715 pub fn actual(&self) -> ProvenanceRecord {
716 self.actual.clone()
717 }
718
719 pub fn with_location(mut self, row: usize, column: usize) -> Self {
720 self.row = Some(row);
721 self.column = Some(column);
722 self
723 }
724
725 pub fn with_products(
726 mut self,
727 expected: Option<ComputationProductId>,
728 actual: Option<ComputationProductId>,
729 ) -> Self {
730 self.expected_product = expected;
731 self.actual_product = actual;
732 self
733 }
734
735 pub const fn with_expressions(
736 mut self,
737 expected: Option<ExprId>,
738 actual: Option<ExprId>,
739 ) -> Self {
740 self.expected_expr = expected;
741 self.actual_expr = actual;
742 self
743 }
744
745 pub const fn with_value_bits(mut self, expected: Option<u64>, actual: Option<u64>) -> Self {
746 self.expected_value_bits = expected;
747 self.actual_value_bits = actual;
748 self
749 }
750}
751
752#[derive(Debug, Eq, PartialEq)]
753pub enum PrecisionFailurePayload {
754 EnclosureWidth { actual_width: Dyadic },
755 Bigint(BigintError),
756 Algnum(AlgnumError),
757}
758
759#[derive(Debug, Eq, PartialEq)]
760pub enum StorageFailurePayload {
761 Storage(StorageError),
762 GraphIdExhausted,
763 DuplicateId { resource: StorageResource, id: u32 },
764 Bigint(BigintError),
765 Monomial(MonomialErrorKind),
766 FormSum(FormSumErrorKind),
767 Algnum(AlgnumError),
768}
769
770#[derive(Debug, Eq, PartialEq)]
771pub enum UnsupportedFailurePayload {
772 RequiredOperation(&'static str),
773 SourceIdentity,
774 Insert(InsertError),
775 Evaluation(EvalError),
776 Resolution(ResolveError),
777}
778
779#[derive(Debug, Eq, PartialEq)]
780pub enum NecoFailure {
781 MissingAssignment {
782 location: FailureLocation,
783 },
784 UnknownExpression {
785 location: FailureLocation,
786 },
787 UnknownAtom {
788 location: FailureLocation,
789 },
790 DivisionByZero {
791 location: FailureLocation,
792 },
793 UndefinedPower {
794 location: FailureLocation,
795 },
796 EvenRootOfNegative {
797 location: FailureLocation,
798 },
799 InvalidIsolation {
800 location: FailureLocation,
801 },
802 MultipleTargetRoots {
803 location: FailureLocation,
804 },
805 FloatOutOfRange {
806 location: FailureLocation,
807 },
808 ProvenanceMismatch {
809 location: FailureLocation,
810 payload: Box<ProvenanceMismatchPayload>,
811 },
812 MatrixInputMismatch {
813 location: FailureLocation,
814 payload: Box<MatrixInputMismatchPayload>,
815 },
816 MissingMatrixInput {
817 location: FailureLocation,
818 },
819 PrecisionExhaustion {
820 location: FailureLocation,
821 requested: AbsoluteBits,
822 payload: Box<PrecisionFailurePayload>,
823 },
824 StorageFailure {
825 location: FailureLocation,
826 payload: Box<StorageFailurePayload>,
827 },
828 UnsupportedRequiredOperation {
829 location: FailureLocation,
830 payload: Box<UnsupportedFailurePayload>,
831 },
832}
833
834impl NecoFailure {
835 pub fn location(&self) -> &FailureLocation {
836 match self {
837 Self::MissingAssignment { location }
838 | Self::UnknownExpression { location }
839 | Self::UnknownAtom { location }
840 | Self::DivisionByZero { location }
841 | Self::UndefinedPower { location }
842 | Self::EvenRootOfNegative { location }
843 | Self::InvalidIsolation { location }
844 | Self::MultipleTargetRoots { location }
845 | Self::FloatOutOfRange { location }
846 | Self::ProvenanceMismatch { location, .. }
847 | Self::MatrixInputMismatch { location, .. }
848 | Self::MissingMatrixInput { location }
849 | Self::PrecisionExhaustion { location, .. }
850 | Self::StorageFailure { location, .. }
851 | Self::UnsupportedRequiredOperation { location, .. } => location,
852 }
853 }
854
855 pub fn from_graph(location: FailureLocation, error: GraphError) -> Self {
856 map_graph_failure(location, error)
857 }
858
859 pub fn from_insert(location: FailureLocation, error: InsertError) -> Self {
860 map_insert_failure(location, error)
861 }
862
863 pub fn from_evaluation(location: FailureLocation, error: EvalError) -> Self {
864 map_eval_failure(location, error)
865 }
866
867 pub fn from_resolution(location: FailureLocation, error: ResolveError) -> Self {
868 map_resolve_failure(location, error)
869 }
870}
871
872pub(crate) fn map_storage_failure(location: FailureLocation, error: StorageError) -> NecoFailure {
873 NecoFailure::StorageFailure {
874 location,
875 payload: Box::new(StorageFailurePayload::Storage(error)),
876 }
877}
878
879pub(crate) fn map_graph_failure(location: FailureLocation, error: GraphError) -> NecoFailure {
880 match error {
881 GraphError::IdExhausted => NecoFailure::StorageFailure {
882 location,
883 payload: Box::new(StorageFailurePayload::GraphIdExhausted),
884 },
885 GraphError::InvalidChildId { child, .. } => NecoFailure::UnknownExpression {
886 location: location.with_expr(child),
887 },
888 GraphError::Node(error) => map_eval_failure(location, error),
889 GraphError::Storage(error) => map_storage_failure(location, error),
890 }
891}
892
893pub(crate) fn map_insert_failure(location: FailureLocation, error: InsertError) -> NecoFailure {
894 match error {
895 InsertError::DuplicateId { resource, id } => NecoFailure::StorageFailure {
896 location,
897 payload: Box::new(StorageFailurePayload::DuplicateId { resource, id }),
898 },
899 InsertError::Value(error) => map_eval_failure(location, error),
900 InsertError::Storage(error) => map_storage_failure(location, error),
901 }
902}
903
904pub(crate) fn map_eval_failure(location: FailureLocation, error: EvalError) -> NecoFailure {
905 match error {
906 EvalError::DivisionByZero => NecoFailure::DivisionByZero { location },
907 EvalError::UndefinedZeroPower | EvalError::ZeroToNegativePower => {
908 NecoFailure::UndefinedPower { location }
909 }
910 EvalError::EvenRootOfNegative => NecoFailure::EvenRootOfNegative { location },
911 EvalError::Bigint(error) => map_bigint_failure(location, error),
912 EvalError::Monomial(error) => map_monomial_failure(location, error),
913 EvalError::FormSum(error) => map_formsum_failure(location, error),
914 EvalError::Algnum(error) => map_algnum_failure(location, error),
915 }
916}
917
918pub(crate) fn map_resolve_failure(location: FailureLocation, error: ResolveError) -> NecoFailure {
919 match error {
920 ResolveError::MissingAssignment { consumer } => NecoFailure::MissingAssignment {
921 location: location.with_consumer(consumer),
922 },
923 ResolveError::UnknownExprId { consumer, expr } => NecoFailure::UnknownExpression {
924 location: location.with_consumer(consumer).with_expr(expr),
925 },
926 ResolveError::UnknownAtomId { expr, atom } => NecoFailure::UnknownAtom {
927 location: location.with_expr(expr).with_atom(atom),
928 },
929 ResolveError::FloatOutOfRange { consumer, expr } => NecoFailure::FloatOutOfRange {
930 location: location.with_consumer(consumer).with_expr(expr),
931 },
932 ResolveError::Evaluation(error) => map_eval_failure(location, error),
933 ResolveError::Bigint(error) => map_bigint_failure(location, error),
934 ResolveError::Algnum(error) => map_algnum_failure(location, error),
935 ResolveError::Storage(error) => map_storage_failure(location, error),
936 }
937}
938
939fn map_bigint_failure(location: FailureLocation, error: BigintError) -> NecoFailure {
940 match error {
941 BigintError::DivisionByZero | BigintError::ZeroDenominator => {
942 NecoFailure::DivisionByZero { location }
943 }
944 BigintError::FloatOutOfRange | BigintError::NonFiniteFloat => {
945 NecoFailure::FloatOutOfRange { location }
946 }
947 BigintError::CapacityOverflow
948 | BigintError::AllocationFailure { .. }
949 | BigintError::ExponentOverflow { .. } => NecoFailure::StorageFailure {
950 location,
951 payload: Box::new(StorageFailurePayload::Bigint(error)),
952 },
953 BigintError::UnsignedUnderflow
954 | BigintError::NonExactDivision
955 | BigintError::InvalidInterval => NecoFailure::UnsupportedRequiredOperation {
956 location,
957 payload: Box::new(UnsupportedFailurePayload::Evaluation(EvalError::Bigint(
958 error,
959 ))),
960 },
961 }
962}
963
964fn map_monomial_failure(location: FailureLocation, error: MonomialErrorKind) -> NecoFailure {
965 match error {
966 MonomialErrorKind::DivisionByZero => NecoFailure::DivisionByZero { location },
967 MonomialErrorKind::UndefinedZeroPower | MonomialErrorKind::ZeroToNegativePower => {
968 NecoFailure::UndefinedPower { location }
969 }
970 MonomialErrorKind::EvenRootOfNegative => NecoFailure::EvenRootOfNegative { location },
971 MonomialErrorKind::CapacityOverflow | MonomialErrorKind::AllocationFailure { .. } => {
972 NecoFailure::StorageFailure {
973 location,
974 payload: Box::new(StorageFailurePayload::Monomial(error)),
975 }
976 }
977 MonomialErrorKind::Bigint(error) => map_bigint_failure(location, error),
978 MonomialErrorKind::InvalidRadicalBasis => NecoFailure::UnsupportedRequiredOperation {
979 location,
980 payload: Box::new(UnsupportedFailurePayload::Evaluation(EvalError::Monomial(
981 error,
982 ))),
983 },
984 }
985}
986
987fn map_formsum_failure(location: FailureLocation, error: FormSumErrorKind) -> NecoFailure {
988 match error {
989 FormSumErrorKind::DivisionByZero => NecoFailure::DivisionByZero { location },
990 FormSumErrorKind::DimensionOverflow { .. } | FormSumErrorKind::AllocationFailure { .. } => {
991 NecoFailure::StorageFailure {
992 location,
993 payload: Box::new(StorageFailurePayload::FormSum(error)),
994 }
995 }
996 FormSumErrorKind::Bigint(error) => map_bigint_failure(location, error),
997 FormSumErrorKind::Monomial(error) => map_monomial_failure(location, error),
998 }
999}
1000
1001fn map_algnum_failure(location: FailureLocation, error: AlgnumError) -> NecoFailure {
1002 match error {
1003 AlgnumError::ZeroPolynomial | AlgnumError::InvalidIsolation | AlgnumError::NoTargetRoot => {
1004 NecoFailure::InvalidIsolation { location }
1005 }
1006 AlgnumError::MultipleTargetRoots => NecoFailure::MultipleTargetRoots { location },
1007 AlgnumError::DivisionByZero => NecoFailure::DivisionByZero { location },
1008 AlgnumError::UndefinedZeroPower | AlgnumError::ZeroToNegativePower => {
1009 NecoFailure::UndefinedPower { location }
1010 }
1011 AlgnumError::EvenRootOfNegative => NecoFailure::EvenRootOfNegative { location },
1012 AlgnumError::RepresentationLimit { .. }
1013 | AlgnumError::AllocationLimit { .. }
1014 | AlgnumError::AllocationFailure { .. } => NecoFailure::StorageFailure {
1015 location,
1016 payload: Box::new(StorageFailurePayload::Algnum(error)),
1017 },
1018 AlgnumError::Bigint(error) => map_bigint_failure(location, error),
1019 AlgnumError::FormSum(error) => map_formsum_failure(location, error),
1020 AlgnumError::ZeroRootDegree => NecoFailure::UnsupportedRequiredOperation {
1021 location,
1022 payload: Box::new(UnsupportedFailurePayload::Evaluation(EvalError::Algnum(
1023 error,
1024 ))),
1025 },
1026 }
1027}