Skip to main content

purrdf_hash/
error.rs

1// SPDX-FileCopyrightText: 2026 Blackcat Informatics Inc. <paudley@blackcatinformatics.ca>
2// SPDX-License-Identifier: MIT OR Apache-2.0 OR MulanPSL-2.0
3
4//! Borrowed error inspection, independent of human presentation.
5//!
6//! Producers report a stable variant code and every semantic field. A consumer
7//! handles this fixed value algebra, rather than matching each producer's enum.
8//! Stable nested owners are references a consumer can put on its own work list.
9//! Temporary views emit balanced record events with fields borrowed from their
10//! original owner. Inspection neither formats nor clones a payload.
11
12mod io;
13pub use io::{IoFailure, io_error};
14
15/// Implement the standard error source chain from single-field enum variants
16/// or a native-cause accessor (`error_sources!(Type, native accessor)`). Other
17/// enum variants have no underlying error. The original cause is borrowed
18/// without rendering, cloning or type erasure beyond the Error trait.
19/// Named fields and nested variants use `patterns Pattern => cause` arms.
20#[macro_export]
21macro_rules! error_sources {
22    ($kind:ty, patterns $($pattern:pat => $cause:expr),+ $(,)?) => {
23        impl ::core::error::Error for $kind {
24            fn source(&self) -> Option<&(dyn ::core::error::Error + 'static)> {
25                match self {
26                    $($pattern => Some($cause),)+
27                    _ => None,
28                }
29            }
30        }
31    };
32    ($kind:ty, native $method:ident) => {
33        impl ::core::error::Error for $kind {
34            fn source(&self) -> Option<&(dyn ::core::error::Error + 'static)> {
35                self.$method()
36                    .map(|cause| cause as &dyn ::core::error::Error)
37            }
38        }
39    };
40    ($kind:ty, $($variant:ident),+ $(,)?) => {
41        impl ::core::error::Error for $kind {
42            fn source(&self) -> Option<&(dyn ::core::error::Error + 'static)> {
43                match self {
44                    $(Self::$variant(cause) => Some(cause),)+
45                    _ => None,
46                }
47            }
48        }
49    };
50}
51
52/// An error, or a structured compound value carried by an error.
53///
54/// Variant codes and field names are stable public identities. Adding a producer
55/// variant or field does not add a variant to [`ErrorValue`]. Implementations
56/// report all semantic fields, including explicit absence and empty lists.
57/// Standard-library I/O categories report a portable `name` for public stable
58/// categories and the original `native_discriminant` for every category.
59/// That native discriminant is compiler-specific, not a persistent error code;
60/// hidden or future categories have an absent name and retain their exact value.
61pub trait StructuredError {
62    /// Report this value's variant and fields without rendering it to text.
63    /// Borrowed payloads remain valid for the original value's lifetime.
64    fn visit<'error>(&'error self, visitor: &mut dyn ErrorVisitor<'error>);
65}
66
67/// An original error whose typed fields survive shared or boxed type erasure.
68/// Standard error upcasting preserves downcasting and the source chain, while
69/// structured upcasting preserves borrowed fields without rendering a message.
70pub trait NativeError: std::error::Error + StructuredError + Send + Sync {}
71impl<T: std::error::Error + StructuredError + Send + Sync> NativeError for T {}
72
73impl StructuredError for core::convert::Infallible {
74    fn visit<'error>(&'error self, _visitor: &mut dyn ErrorVisitor<'error>) {
75        // Generic query errors can name Infallible without ever carrying one.
76        // Do not dereference an uninhabited reference to implement that bound.
77        unreachable!("an Infallible error has no value to inspect")
78    }
79}
80
81impl StructuredError for core::fmt::Error {
82    fn visit<'error>(&'error self, visitor: &mut dyn ErrorVisitor<'error>) {
83        visitor.variant("std-format");
84    }
85}
86
87impl StructuredError for std::collections::TryReserveError {
88    fn visit<'error>(&'error self, visitor: &mut dyn ErrorVisitor<'error>) {
89        // The stable API exposes no kind or allocator layout fields. Producers
90        // retain this original source and report their requested size alongside it.
91        visitor.variant("std-try-reserve");
92    }
93}
94
95impl StructuredError for core::num::TryFromIntError {
96    fn visit<'error>(&'error self, visitor: &mut dyn ErrorVisitor<'error>) {
97        // The standard error has no payload; the native producer retains the
98        // source value and destination limit alongside this original cause.
99        visitor.variant("integer-conversion-range");
100    }
101}
102
103impl StructuredError for core::num::IntErrorKind {
104    fn visit<'error>(&'error self, visitor: &mut dyn ErrorVisitor<'error>) {
105        let name = match self {
106            Self::Empty => Some("empty"),
107            Self::InvalidDigit => Some("invalid-digit"),
108            Self::PosOverflow => Some("positive-overflow"),
109            Self::NegOverflow => Some("negative-overflow"),
110            Self::Zero => Some("zero"),
111            _ => None,
112        };
113        visitor.variant("std-integer-kind");
114        visitor.value(
115            Some("name"),
116            name.map_or(ErrorValue::Absent, ErrorValue::Code),
117        );
118        // As for ErrorKind, retain unlisted external unit categories without
119        // formatting them or confusing them with a known category.
120        visitor.value(
121            Some("native_discriminant"),
122            ErrorValue::Unsigned(*self as u128),
123        );
124    }
125}
126
127impl StructuredError for core::num::ParseIntError {
128    fn visit<'error>(&'error self, visitor: &mut dyn ErrorVisitor<'error>) {
129        visitor.variant("std-integer-parse");
130        visitor.value(Some("kind"), ErrorValue::Cause(self.kind()));
131    }
132}
133
134impl StructuredError for core::str::Utf8Error {
135    fn visit<'error>(&'error self, visitor: &mut dyn ErrorVisitor<'error>) {
136        visitor.variant("std-utf8");
137        visitor.value(
138            Some("valid_up_to"),
139            ErrorValue::ByteCount(self.valid_up_to() as u128),
140        );
141        visitor.value(
142            Some("error_len"),
143            self.error_len()
144                .map_or(ErrorValue::Absent, |len| ErrorValue::ByteCount(len as u128)),
145        );
146    }
147}
148
149impl StructuredError for std::time::SystemTimeError {
150    fn visit<'error>(&'error self, visitor: &mut dyn ErrorVisitor<'error>) {
151        visitor.variant("std-system-time");
152        let duration = self.duration();
153        visitor.value(
154            Some("seconds"),
155            ErrorValue::Unsigned(u128::from(duration.as_secs())),
156        );
157        visitor.value(
158            Some("nanoseconds"),
159            ErrorValue::Unsigned(u128::from(duration.subsec_nanos())),
160        );
161    }
162}
163
164/// Portable name of an original I/O kind, when the standard category is known.
165/// Unknown categories retain their native discriminant through structured inspection.
166#[must_use]
167pub fn io_error_kind_name(kind: std::io::ErrorKind) -> Option<&'static str> {
168    match kind {
169        std::io::ErrorKind::NotFound => Some("not-found"),
170        std::io::ErrorKind::PermissionDenied => Some("permission-denied"),
171        std::io::ErrorKind::ConnectionRefused => Some("connection-refused"),
172        std::io::ErrorKind::ConnectionReset => Some("connection-reset"),
173        std::io::ErrorKind::HostUnreachable => Some("host-unreachable"),
174        std::io::ErrorKind::NetworkUnreachable => Some("network-unreachable"),
175        std::io::ErrorKind::ConnectionAborted => Some("connection-aborted"),
176        std::io::ErrorKind::NotConnected => Some("not-connected"),
177        std::io::ErrorKind::AddrInUse => Some("address-in-use"),
178        std::io::ErrorKind::AddrNotAvailable => Some("address-not-available"),
179        std::io::ErrorKind::NetworkDown => Some("network-down"),
180        std::io::ErrorKind::BrokenPipe => Some("broken-pipe"),
181        std::io::ErrorKind::AlreadyExists => Some("already-exists"),
182        std::io::ErrorKind::WouldBlock => Some("would-block"),
183        std::io::ErrorKind::NotADirectory => Some("not-a-directory"),
184        std::io::ErrorKind::IsADirectory => Some("is-a-directory"),
185        std::io::ErrorKind::DirectoryNotEmpty => Some("directory-not-empty"),
186        std::io::ErrorKind::ReadOnlyFilesystem => Some("read-only-filesystem"),
187        std::io::ErrorKind::StaleNetworkFileHandle => Some("stale-network-file-handle"),
188        std::io::ErrorKind::InvalidInput => Some("invalid-input"),
189        std::io::ErrorKind::InvalidData => Some("invalid-data"),
190        std::io::ErrorKind::TimedOut => Some("timed-out"),
191        std::io::ErrorKind::WriteZero => Some("write-zero"),
192        std::io::ErrorKind::StorageFull => Some("storage-full"),
193        std::io::ErrorKind::NotSeekable => Some("not-seekable"),
194        std::io::ErrorKind::QuotaExceeded => Some("quota-exceeded"),
195        std::io::ErrorKind::FileTooLarge => Some("file-too-large"),
196        std::io::ErrorKind::ResourceBusy => Some("resource-busy"),
197        std::io::ErrorKind::ExecutableFileBusy => Some("executable-file-busy"),
198        std::io::ErrorKind::Deadlock => Some("deadlock"),
199        std::io::ErrorKind::CrossesDevices => Some("crosses-devices"),
200        std::io::ErrorKind::TooManyLinks => Some("too-many-links"),
201        std::io::ErrorKind::InvalidFilename => Some("invalid-filename"),
202        std::io::ErrorKind::ArgumentListTooLong => Some("argument-list-too-long"),
203        std::io::ErrorKind::Interrupted => Some("interrupted"),
204        std::io::ErrorKind::Unsupported => Some("unsupported"),
205        std::io::ErrorKind::UnexpectedEof => Some("unexpected-eof"),
206        std::io::ErrorKind::OutOfMemory => Some("out-of-memory"),
207        std::io::ErrorKind::Other => Some("other"),
208        _ => None,
209    }
210}
211
212impl StructuredError for std::io::ErrorKind {
213    fn visit<'error>(&'error self, visitor: &mut dyn ErrorVisitor<'error>) {
214        // Public stable categories have portable names. The standard library
215        // also produces hidden categories and may add further ones. Retain
216        // their actual unit discriminant rather than calling them Other or
217        // formatting them. This native value is not a persistent identity.
218        visitor.variant("std-io-kind");
219        visit_io_kind_fields(*self, visitor);
220    }
221}
222
223fn visit_io_kind_fields(kind: std::io::ErrorKind, visitor: &mut dyn ErrorVisitor<'_>) {
224    visitor.value(
225        Some("name"),
226        io_error_kind_name(kind).map_or(ErrorValue::Absent, ErrorValue::Code),
227    );
228    visitor.value(
229        Some("native_discriminant"),
230        ErrorValue::Unsigned(kind as u128),
231    );
232}
233
234/// One field value. These primitive kinds form a closed interchange algebra.
235///
236/// Compound values use [`Self::Record`], [`Self::Term`] or [`Self::Cause`]; lists
237/// use the visitor's list events. New producer variants and fields therefore do
238/// not require a consumer wildcard or an enum mirror. Float bit patterns retain
239/// every value, including negative zero and NaN payloads, without formatting.
240#[derive(Clone, Copy)]
241pub enum ErrorValue<'error> {
242    /// An optional field is present in the schema but has no value.
243    Absent,
244    /// An exact unsigned integer, including full-width capacity counters.
245    Unsigned(u128),
246    /// An exact signed integer.
247    Signed(i128),
248    /// A Boolean condition.
249    Boolean(bool),
250    /// An IEEE 754 binary32 value's original bits.
251    Float32Bits(u32),
252    /// An IEEE 754 binary64 value's original bits.
253    Float64Bits(u64),
254    /// One Unicode scalar value.
255    Character(char),
256    /// A machine-readable code or discriminant, distinct from prose.
257    Code(&'error str),
258    /// Text that is itself data, such as an input lexical form.
259    Text(&'error str),
260    /// A genuine caller or external message, not a rendered native cause.
261    Message(&'error str),
262    /// An IRI-valued field; inspection does not parse or normalize its bytes.
263    Iri(&'error str),
264    /// Original bytes, without an encoding or allocation.
265    Bytes(&'error [u8]),
266    /// A byte quantity, distinct from an unqualified integer.
267    ByteCount(u128),
268    /// A nested error retaining its own stable variant and fields.
269    Cause(&'error dyn StructuredError),
270    /// A compound non-error payload retaining its variant and fields.
271    Record(&'error dyn StructuredError),
272    /// A structured RDF term payload, visited without converting it to a string.
273    Term(&'error dyn StructuredError),
274}
275
276// A debug view must not accidentally render a retained or recursively nested
277// cause. The visitor, not Debug, is the complete structural interface.
278crate::debug_non_exhaustive!(ErrorValue<'_> {});
279
280/// Receives one structured error and its fields.
281///
282/// A value starts with `variant`. Named fields have `Some(name)`; list entries
283/// have `None`. A list's begin/end pair encloses its values, including nested
284/// lists. Nested records/causes are borrowed values: the producer does not call
285/// their visitor recursively. No method has a default that can discard a field.
286pub trait ErrorVisitor<'error> {
287    /// Stable identity of the current error or compound payload variant.
288    fn variant(&mut self, code: &'static str);
289
290    /// A named field or an unnamed list entry, preserving its primitive kind.
291    fn value(&mut self, name: Option<&'static str>, value: ErrorValue<'error>);
292
293    /// Begin a named list field or an unnamed nested list entry.
294    fn begin_list(&mut self, name: Option<&'static str>, length: usize);
295
296    /// End the most recently begun list.
297    fn end_list(&mut self);
298
299    /// Begin a compound view whose temporary adapter need not survive inspection.
300    /// Its field values still borrow the original owner for `'error`. A named
301    /// record is a field; an unnamed record is an entry of the enclosing list.
302    fn begin_record(&mut self, name: Option<&'static str>, code: &'static str);
303
304    /// End the most recently begun record, after its fields and nested lists.
305    fn end_record(&mut self);
306}
307
308impl StructuredError for () {
309    fn visit<'error>(&'error self, visitor: &mut dyn ErrorVisitor<'error>) {
310        visitor.variant("unit");
311    }
312}
313
314// Native views use these scalar counters as their original evidence. The
315// consumer sees the exact count rather than needing a wrapper or a downcast.
316macro_rules! unsigned_evidence {
317    ($($integer:ty => $widen:expr),* $(,)?) => {$ (
318        impl StructuredError for $integer {
319            fn visit<'error>(&'error self, visitor: &mut dyn ErrorVisitor<'error>) {
320                visitor.variant("unsigned-evidence");
321                visitor.value(Some("value"), ErrorValue::Unsigned(($widen)(*self)));
322            }
323        }
324    )*};
325}
326unsigned_evidence!(u32 => u128::from, usize => |value: usize| value as u128);
327
328impl StructuredError for str {
329    fn visit<'error>(&'error self, visitor: &mut dyn ErrorVisitor<'error>) {
330        visitor.variant("text-value");
331        visitor.value(Some("text"), ErrorValue::Text(self));
332    }
333}
334
335impl StructuredError for String {
336    fn visit<'error>(&'error self, visitor: &mut dyn ErrorVisitor<'error>) {
337        self.as_str().visit(visitor);
338    }
339}
340
341impl<First: StructuredError, Second: StructuredError> StructuredError for (First, Second) {
342    fn visit<'error>(&'error self, visitor: &mut dyn ErrorVisitor<'error>) {
343        let (first, second) = self;
344        visitor.variant("pair");
345        visitor.value(Some("first"), ErrorValue::Record(first));
346        visitor.value(Some("second"), ErrorValue::Record(second));
347    }
348}
349
350impl<T: StructuredError + ?Sized> StructuredError for &T {
351    fn visit<'error>(&'error self, visitor: &mut dyn ErrorVisitor<'error>) {
352        T::visit(*self, visitor);
353    }
354}
355
356/// Emit a borrowed list without materializing or cloning its items.
357///
358/// The iterator's exact length includes absent entries. A consumer receives an
359/// empty begin/end pair for an empty list, rather than losing the field.
360pub fn visit_list<'error>(
361    visitor: &mut dyn ErrorVisitor<'error>,
362    name: Option<&'static str>,
363    values: impl ExactSizeIterator<Item = ErrorValue<'error>>,
364) {
365    visitor.begin_list(name, values.len());
366    for value in values {
367        visitor.value(None, value);
368    }
369    visitor.end_list();
370}
371
372/// Implement an enum's borrowed visitor through exhaustive producer patterns.
373///
374/// Use inside its [`StructuredError`](crate::error::StructuredError) impl.
375/// Every variant and named/tuple field
376/// must be listed; the grammar supplies no wildcard or rest pattern. New fields
377/// or variants therefore require producer support at compilation, while a
378/// consumer continues to handle the fixed [`ErrorValue`](crate::error::ErrorValue)
379/// algebra. A field is
380/// `"name" => Kind(value)`, `"name" => Absent`, or `"name" => List(iterator)`.
381/// `Value(expression)` forwards an existing value, for example an optional
382/// cause mapped to either `Cause` or `Absent`.
383/// For a named struct, `@record self { all, physical, fields } => "code" { ... }`
384/// checks its complete shape while expressions use its existing semantic
385/// accessors. Encoded private fields need not be decoded a second time.
386///
387/// A producer cannot add a variant without exposing it:
388///
389/// ```compile_fail,E0004
390/// use purrdf_hash::error::StructuredError;
391/// pub enum Failure { Original, Added }
392/// impl StructuredError for Failure {
393///     purrdf_hash::error_visit! { Original => "original" {} }
394/// }
395/// ```
396///
397/// Nor can it add a named payload field without updating the visitor:
398///
399/// ```compile_fail
400/// use purrdf_hash::error::StructuredError;
401/// pub enum Failure { Refused { attempted: u128, limit: u128 } }
402/// impl StructuredError for Failure {
403///     purrdf_hash::error_visit! {
404///         Refused { attempted } => "refused" { "attempted" => Unsigned(*attempted) }
405///     }
406/// }
407/// ```
408///
409/// Structs must also account for every physical field:
410///
411/// ```compile_fail
412/// use purrdf_hash::error::StructuredError;
413/// pub struct Failure { attempted: u128, limit: u128 }
414/// impl StructuredError for Failure {
415///     purrdf_hash::error_visit! {
416///         @record self { attempted } => "refused" {
417///             "attempted" => Unsigned(self.attempted),
418///         }
419///     }
420/// }
421/// ```
422///
423/// Tuple owners likewise enumerate their complete physical shape:
424///
425/// ```compile_fail
426/// use purrdf_hash::error::StructuredError;
427/// pub struct Owner(u64, u64);
428/// impl StructuredError for Owner {
429///     purrdf_hash::error_visit! {
430///         @tuple self (value) => "owner" { "value" => Unsigned(u128::from(*value)) }
431///     }
432/// }
433/// ```
434#[macro_export]
435macro_rules! error_visit {
436    (
437        @tuple $this:ident ($($member:ident),* $(,)?) => $code:literal {
438            $($field:literal => $kind:ident $(($value:expr))?),* $(,)?
439        }
440    ) => {
441        fn visit<'error>(
442            &'error $this,
443            visitor: &mut dyn $crate::error::ErrorVisitor<'error>,
444        ) {
445            // Bind the complete shape, as for named records and enum variants.
446            let Self($($member),*) = $this;
447            visitor.variant($code);
448            $($crate::error_visit!(@field visitor, $field, $kind $(($value))?);)*
449        }
450    };
451    (
452        @record $this:ident { $($member:ident),* $(,)? } => $code:literal {
453            $($field:literal => $kind:ident $(($value:expr))?),* $(,)?
454        }
455    ) => {
456        fn visit<'error>(
457            &'error $this,
458            visitor: &mut dyn $crate::error::ErrorVisitor<'error>,
459        ) {
460            // Check the complete physical shape, while semantic accessors can
461            // decode private representations without duplicating their logic.
462            let Self { $($member: _),* } = $this;
463            visitor.variant($code);
464            $($crate::error_visit!(@field visitor, $field, $kind $(($value))?);)*
465        }
466    };
467    (
468        $(
469            $variant:ident
470            $({ $($named:ident),* $(,)? })?
471            $(($($tuple:ident),* $(,)?))?
472            => $code:literal {
473                $($field:literal => $kind:ident $(($value:expr))?),* $(,)?
474            }
475        ),* $(,)?
476    ) => {
477        fn visit<'error>(
478            &'error self,
479            visitor: &mut dyn $crate::error::ErrorVisitor<'error>,
480        ) {
481            match self {
482                $(Self::$variant $({ $($named),* })? $(($($tuple),*))? => {
483                    visitor.variant($code);
484                    $($crate::error_visit!(@field visitor, $field, $kind $(($value))?);)*
485                }),*
486            }
487        }
488    };
489    (@field $visitor:ident, $field:literal, List($value:expr)) => {
490        $crate::error::visit_list($visitor, Some($field), $value)
491    };
492    (@field $visitor:ident, $field:literal, Value($value:expr)) => {
493        $visitor.value(Some($field), $value)
494    };
495    (@field $visitor:ident, $field:literal, $kind:ident $(($value:expr))?) => {
496        $visitor.value(Some($field), $crate::error::ErrorValue::$kind $(($value))?)
497    };
498}