Skip to main content

excel_api/
error.rs

1use core::fmt;
2
3use crate::DecodeError;
4
5/// Safe representation of worksheet errors.
6#[derive(Clone, Copy, Debug, Eq, PartialEq)]
7pub enum ExcelError {
8    /// `#NULL!`: an invalid intersection.
9    Null,
10    /// `#DIV/0!`: division by zero.
11    Div0,
12    /// `#VALUE!`: an invalid value or argument type.
13    Value,
14    /// `#REF!`: an invalid worksheet reference.
15    Ref,
16    /// `#NAME?`: an unrecognized name.
17    Name,
18    /// `#NUM!`: an invalid numeric result.
19    Num,
20    /// `#N/A`: data is unavailable.
21    Na,
22    /// `#GETTING_DATA`: an asynchronous data source is still pending.
23    GettingData,
24}
25
26impl From<excel_api_sys::XlError> for ExcelError {
27    fn from(value: excel_api_sys::XlError) -> Self {
28        match value {
29            excel_api_sys::XlError::Null => Self::Null,
30            excel_api_sys::XlError::Div0 => Self::Div0,
31            excel_api_sys::XlError::Value => Self::Value,
32            excel_api_sys::XlError::Ref => Self::Ref,
33            excel_api_sys::XlError::Name => Self::Name,
34            excel_api_sys::XlError::Num => Self::Num,
35            excel_api_sys::XlError::Na => Self::Na,
36            excel_api_sys::XlError::GettingData => Self::GettingData,
37        }
38    }
39}
40
41/// Strict UTF-16 decoding failed because the payload contains an unpaired
42/// surrogate.
43#[derive(Clone, Copy, Debug, Eq, PartialEq)]
44pub struct Utf16ConversionError;
45
46impl fmt::Display for Utf16ConversionError {
47    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
48        formatter.write_str("UTF-16 payload contains an unpaired surrogate")
49    }
50}
51
52impl std::error::Error for Utf16ConversionError {}
53
54/// Failure to construct an owned semantic value directly.
55#[derive(Clone, Debug, Eq, PartialEq)]
56pub enum OwnedValueError {
57    /// Multiplying the requested dimensions overflowed `usize`.
58    ArrayShapeOverflow {
59        /// Requested row count.
60        rows: usize,
61        /// Requested column count.
62        columns: usize,
63    },
64    /// The supplied flat element count does not match the dimensions.
65    InvalidArrayShape {
66        /// Requested row count.
67        rows: usize,
68        /// Requested column count.
69        columns: usize,
70        /// Provided flat element count.
71        elements: usize,
72    },
73    /// An owned array attempted to contain another array.
74    NestedArrayUnsupported,
75}
76
77impl fmt::Display for OwnedValueError {
78    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
79        match self {
80            Self::ArrayShapeOverflow { rows, columns } => {
81                write!(formatter, "array shape {rows} x {columns} overflows usize")
82            }
83            Self::InvalidArrayShape {
84                rows,
85                columns,
86                elements,
87            } => write!(
88                formatter,
89                "array shape {rows} x {columns} does not match {elements} elements"
90            ),
91            Self::NestedArrayUnsupported => {
92                formatter.write_str("nested Excel arrays are unsupported")
93            }
94        }
95    }
96}
97
98impl std::error::Error for OwnedValueError {}
99
100/// Failure while converting between callback-borrowed and owned semantic
101/// values.
102#[derive(Clone, Debug, Eq, PartialEq)]
103pub enum ConversionError {
104    /// The source kind does not match the requested conversion.
105    UnexpectedType {
106        /// Human-readable requested kind.
107        expected: &'static str,
108        /// Human-readable source kind.
109        actual: &'static str,
110    },
111    /// A callback reference requires an explicit reference-preserving path.
112    UnsupportedReference,
113    /// A UTF-16 payload contained an unpaired surrogate.
114    InvalidUtf16,
115    /// A floating-point input was NaN or infinite.
116    NonFiniteNumber,
117    /// A floating-point input had a fractional component.
118    NonIntegralNumber,
119    /// An integral value did not fit the requested integer type.
120    IntegerOutOfRange,
121    /// The source array dimensions and elements were inconsistent.
122    InvalidArrayShape,
123    /// Text exceeded the configured conversion limit.
124    StringLimitExceeded {
125        /// Observed UTF-16 code-unit count.
126        actual: usize,
127        /// Configured maximum.
128        maximum: usize,
129    },
130    /// An array exceeded the configured element limit.
131    ArrayElementLimitExceeded {
132        /// Observed element count.
133        actual: usize,
134        /// Configured maximum.
135        maximum: usize,
136    },
137    /// Conversion would exceed its aggregate owned-allocation budget.
138    AggregateByteLimitExceeded {
139        /// Minimum required bytes.
140        required: usize,
141        /// Configured maximum bytes.
142        maximum: usize,
143    },
144    /// Nested Excel arrays have no supported semantic representation.
145    NestedArrayUnsupported,
146    /// Recursive conversion exceeded its configured depth.
147    ConversionDepthExceeded {
148        /// Observed conversion depth.
149        depth: usize,
150        /// Configured maximum depth.
151        maximum: usize,
152    },
153    /// A callback view became malformed while being decoded.
154    BorrowedValueDecode(DecodeError),
155}
156
157impl fmt::Display for ConversionError {
158    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
159        match self {
160            Self::UnexpectedType { expected, actual } => {
161                write!(formatter, "expected {expected}, received {actual}")
162            }
163            Self::UnsupportedReference => {
164                formatter.write_str("Excel references require explicit coercion")
165            }
166            Self::InvalidUtf16 => formatter.write_str("Excel text is not valid UTF-16"),
167            Self::NonFiniteNumber => formatter.write_str("number is not finite"),
168            Self::NonIntegralNumber => formatter.write_str("number is not an integer"),
169            Self::IntegerOutOfRange => formatter.write_str("integer is out of range"),
170            Self::InvalidArrayShape => formatter.write_str("array shape is invalid"),
171            Self::StringLimitExceeded { actual, maximum } => write!(
172                formatter,
173                "string has {actual} UTF-16 code units; conversion limit is {maximum}"
174            ),
175            Self::ArrayElementLimitExceeded { actual, maximum } => write!(
176                formatter,
177                "array has {actual} elements; conversion limit is {maximum}"
178            ),
179            Self::AggregateByteLimitExceeded { required, maximum } => write!(
180                formatter,
181                "conversion requires at least {required} bytes; limit is {maximum}"
182            ),
183            Self::NestedArrayUnsupported => {
184                formatter.write_str("nested Excel arrays are unsupported")
185            }
186            Self::ConversionDepthExceeded { depth, maximum } => write!(
187                formatter,
188                "conversion depth {depth} exceeds limit {maximum}"
189            ),
190            Self::BorrowedValueDecode(error) => {
191                write!(formatter, "borrowed Excel value became invalid: {error}")
192            }
193        }
194    }
195}
196
197impl std::error::Error for ConversionError {
198    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
199        match self {
200            Self::BorrowedValueDecode(error) => Some(error),
201            _ => None,
202        }
203    }
204}
205
206impl From<Utf16ConversionError> for ConversionError {
207    fn from(_: Utf16ConversionError) -> Self {
208        Self::InvalidUtf16
209    }
210}
211
212impl From<DecodeError> for ConversionError {
213    fn from(error: DecodeError) -> Self {
214        Self::BorrowedValueDecode(error)
215    }
216}
217
218impl From<OwnedValueError> for ConversionError {
219    fn from(error: OwnedValueError) -> Self {
220        match error {
221            OwnedValueError::NestedArrayUnsupported => Self::NestedArrayUnsupported,
222            OwnedValueError::ArrayShapeOverflow { .. }
223            | OwnedValueError::InvalidArrayShape { .. } => Self::InvalidArrayShape,
224        }
225    }
226}
227
228/// Failure to describe a future ABI-compatible Excel return.
229///
230/// Return errors contain only owned scalar metadata. They never contain raw
231/// pointers, callback lifetimes, or partially allocated return storage.
232#[derive(Clone, Debug, Eq, PartialEq)]
233pub enum ReturnError {
234    /// Text exceeds Excel's representable counted-string limit.
235    StringTooLongForExcel {
236        /// Requested UTF-16 code units.
237        actual: usize,
238        /// Excel's maximum UTF-16 code units.
239        maximum: usize,
240    },
241    /// Text exceeds the library's configured return limit.
242    StringLimitExceeded {
243        /// Requested UTF-16 code units.
244        actual: usize,
245        /// Configured maximum.
246        maximum: usize,
247    },
248    /// Flat elements do not match the requested return dimensions.
249    InvalidArrayShape {
250        /// Requested rows.
251        rows: usize,
252        /// Requested columns.
253        columns: usize,
254        /// Provided element count.
255        elements: usize,
256    },
257    /// Empty multidimensional ABI returns are not representable.
258    EmptyArrayUnsupported,
259    /// A dimension exceeds the Excel 12 ABI width or bounds.
260    ArrayDimensionExceedsAbi {
261        /// Requested rows.
262        rows: usize,
263        /// Requested columns.
264        columns: usize,
265    },
266    /// Multiplying return dimensions overflowed `usize`.
267    ArrayElementCountOverflow {
268        /// Requested rows.
269        rows: usize,
270        /// Requested columns.
271        columns: usize,
272    },
273    /// A return array exceeds its configured element budget.
274    ArrayElementLimitExceeded {
275        /// Requested element count.
276        actual: usize,
277        /// Configured maximum.
278        maximum: usize,
279    },
280    /// Nested arrays cannot be materialized as Excel 12 return storage.
281    NestedArrayUnsupported,
282    /// Semantic references are not valid return values in this framework.
283    ReferenceUnsupported,
284    /// A semantic value variant has no supported return representation.
285    UnsupportedSemanticVariant {
286        /// Stable semantic variant name.
287        variant: &'static str,
288    },
289    /// Total return-storage byte accounting overflowed.
290    TotalByteOverflow,
291    /// The return plan exceeds its aggregate allocation budget.
292    TotalByteLimitExceeded {
293        /// Minimum required bytes.
294        required: usize,
295        /// Configured maximum bytes.
296        maximum: usize,
297    },
298    /// Return allocation-count accounting overflowed.
299    AllocationCountOverflow,
300    /// The plan requires too many separate allocations.
301    AllocationCountLimitExceeded {
302        /// Required allocation count.
303        required: usize,
304        /// Configured maximum.
305        maximum: usize,
306    },
307    /// Recursive return planning exceeded its configured depth.
308    PlanningDepthExceeded {
309        /// Observed planning depth.
310        depth: usize,
311        /// Configured maximum depth.
312        maximum: usize,
313    },
314}
315
316impl fmt::Display for ReturnError {
317    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
318        match self {
319            Self::StringTooLongForExcel { actual, maximum } => write!(
320                formatter,
321                "return string has {actual} UTF-16 code units; Excel supports at most {maximum}"
322            ),
323            Self::StringLimitExceeded { actual, maximum } => write!(
324                formatter,
325                "return string has {actual} UTF-16 code units; project limit is {maximum}"
326            ),
327            Self::InvalidArrayShape {
328                rows,
329                columns,
330                elements,
331            } => write!(
332                formatter,
333                "return array shape {rows} x {columns} does not match {elements} elements"
334            ),
335            Self::EmptyArrayUnsupported => formatter.write_str(
336                "zero-dimensional xltypeMulti returns are unsupported; return Empty instead",
337            ),
338            Self::ArrayDimensionExceedsAbi { rows, columns } => write!(
339                formatter,
340                "return array dimensions {rows} x {columns} exceed the Excel 12 ABI limits"
341            ),
342            Self::ArrayElementCountOverflow { rows, columns } => write!(
343                formatter,
344                "return array element count {rows} x {columns} overflows usize"
345            ),
346            Self::ArrayElementLimitExceeded { actual, maximum } => write!(
347                formatter,
348                "return array has {actual} elements; project limit is {maximum}"
349            ),
350            Self::NestedArrayUnsupported => {
351                formatter.write_str("nested Excel return arrays are unsupported")
352            }
353            Self::ReferenceUnsupported => {
354                formatter.write_str("Excel references are unsupported return values")
355            }
356            Self::UnsupportedSemanticVariant { variant } => {
357                write!(
358                    formatter,
359                    "semantic variant {variant} is unsupported for returns"
360                )
361            }
362            Self::TotalByteOverflow => {
363                formatter.write_str("return storage byte accounting overflowed usize")
364            }
365            Self::TotalByteLimitExceeded { required, maximum } => write!(
366                formatter,
367                "return requires {required} ABI storage bytes; project limit is {maximum}"
368            ),
369            Self::AllocationCountOverflow => {
370                formatter.write_str("return allocation-count accounting overflowed usize")
371            }
372            Self::AllocationCountLimitExceeded { required, maximum } => write!(
373                formatter,
374                "return requires {required} allocations; project limit is {maximum}"
375            ),
376            Self::PlanningDepthExceeded { depth, maximum } => write!(
377                formatter,
378                "return planning depth {depth} exceeds project limit {maximum}"
379            ),
380        }
381    }
382}
383
384impl std::error::Error for ReturnError {}
385
386/// Failure while turning a validated return plan into stable ABI storage.
387#[derive(Clone, Debug, Eq, PartialEq)]
388pub enum ReturnMaterializationError {
389    /// Materialized storage contradicted an already validated plan field.
390    PlanStorageInvariantMismatch {
391        /// Invariant field name.
392        field: &'static str,
393        /// Planned amount.
394        planned: usize,
395        /// Actual materialized amount.
396        actual: usize,
397    },
398    /// UTF-8 to UTF-16 encoding did not match the planned length.
399    Utf8EncodedLengthMismatch {
400        /// Planned UTF-16 units.
401        planned: usize,
402        /// Actual UTF-16 units.
403        actual: usize,
404    },
405    /// A counted-string buffer length disagreed with its plan.
406    StringBufferLengthMismatch {
407        /// Planned units.
408        planned: usize,
409        /// Actual units.
410        actual: usize,
411    },
412    /// Array data contradicted the shape selected during planning.
413    ArrayShapeMismatch {
414        /// Planned rows.
415        rows: usize,
416        /// Planned columns.
417        columns: usize,
418        /// Actual element count.
419        elements: usize,
420    },
421    /// A planned semantic variant cannot be emitted as ABI storage.
422    UnsupportedPlannedValue {
423        /// Stable planned variant name.
424        variant: &'static str,
425    },
426    /// A required stable return allocation failed.
427    AllocationFailure {
428        /// Name of the storage allocation.
429        storage: &'static str,
430    },
431    /// A test-only injected materialization failure.
432    InjectedTestFailure {
433        /// Test-injected stage name.
434        stage: &'static str,
435    },
436}
437
438impl fmt::Display for ReturnMaterializationError {
439    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
440        match self {
441            Self::PlanStorageInvariantMismatch {
442                field,
443                planned,
444                actual,
445            } => write!(
446                formatter,
447                "return plan {field} is {planned}, but materialized storage requires {actual}"
448            ),
449            Self::Utf8EncodedLengthMismatch { planned, actual } => write!(
450                formatter,
451                "planned UTF-8 text requires {planned} UTF-16 units, but encoding produced {actual}"
452            ),
453            Self::StringBufferLengthMismatch { planned, actual } => write!(
454                formatter,
455                "planned counted string requires {planned} units, but materialization produced {actual}"
456            ),
457            Self::ArrayShapeMismatch {
458                rows,
459                columns,
460                elements,
461            } => write!(
462                formatter,
463                "planned return array shape {rows} x {columns} does not match {elements} elements"
464            ),
465            Self::UnsupportedPlannedValue { variant } => {
466                write!(formatter, "planned value {variant} cannot be materialized")
467            }
468            Self::AllocationFailure { storage } => {
469                write!(formatter, "could not allocate {storage} return storage")
470            }
471            Self::InjectedTestFailure { stage } => {
472                write!(formatter, "test injected a failure at {stage}")
473            }
474        }
475    }
476}
477
478impl std::error::Error for ReturnMaterializationError {}
479
480#[derive(Debug)]
481/// Failure contained by a generated Excel callback thunk.
482pub enum ThunkError {
483    /// Excel supplied a null argument root where a value was required.
484    NullArgument,
485    /// The callback-borrowed argument could not be decoded safely.
486    Decode(DecodeError),
487    /// A decoded argument could not become the requested Rust input.
488    Conversion(ConversionError),
489    /// User function code deliberately returned a worksheet error.
490    Function(ExcelError),
491    /// Pointer-free return planning failed.
492    ReturnPlanning(ReturnError),
493    /// Stable ABI return storage could not be materialized.
494    Materialization(ReturnMaterializationError),
495}
496
497impl fmt::Display for ThunkError {
498    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
499        match self {
500            Self::NullArgument => formatter.write_str("Excel supplied a null argument pointer"),
501            Self::Decode(error) => write!(formatter, "Excel argument decoding failed: {error}"),
502            Self::Conversion(error) => {
503                write!(formatter, "Excel argument conversion failed: {error}")
504            }
505            Self::Function(error) => write!(formatter, "worksheet function returned {error:?}"),
506            Self::ReturnPlanning(error) => write!(formatter, "return planning failed: {error}"),
507            Self::Materialization(error) => {
508                write!(formatter, "return materialization failed: {error}")
509            }
510        }
511    }
512}
513
514impl std::error::Error for ThunkError {}
515
516impl fmt::Display for DecodeError {
517    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
518        write!(formatter, "{self:?}")
519    }
520}
521
522impl std::error::Error for DecodeError {}