Skip to main content

error_kind/envelopes/alloc/
diagnostic.rs

1// =============================================================================
2// MODULES
3// =============================================================================
4
5// -----------------------------------------------------------------------------
6#[cfg(test)]
7#[path = "diagnostic.tests.rs"]
8mod tests;
9
10// =============================================================================
11// USES
12// =============================================================================
13
14// -----------------------------------------------------------------------------
15use crate::details::StaticString;
16use crate::envelopes::alloc::{ContextEntry, ErrorMetadata};
17use crate::envelopes::{Described, ErrorEnvelope, Located};
18use crate::{Context, ErrorContext, ErrorKind};
19use core::fmt::{Debug, Display, Formatter};
20use core::panic::Location;
21use std_alloc::string::String;
22use std_alloc::sync::Arc;
23
24// =============================================================================
25// TYPES
26// =============================================================================
27
28// -----------------------------------------------------------------------------
29#[derive(Clone)]
30struct BoxedData<K> {
31    pub kind: K,
32    pub metadata: ErrorMetadata,
33}
34
35/// An envelope that collects detailed diagnostic information.
36///
37/// The backtrace will only be collected if the `backtrace` feature is enabled,
38/// *and* either `RUST_BACKTRACE` or `RUST_LIB_BACKTRACE` are set.
39///
40/// # Collects
41///
42/// - backtrace *(if enabled)*
43/// - context
44/// - description
45/// - error kind
46/// - locations
47///
48/// # When To Use
49///
50/// When you are debugging an issue with your crate, or you want to allow a
51/// dependant to debug an issue with your crate.
52///
53/// # Example Display
54///
55/// When printed normally (`"{error}"`):
56///
57/// ```text
58/// static error code: detailed dynamic error message
59///   with context
60///   ├─ we found that a (12) is not b (34)
61///   ╰─ while working in my_procedure (a: 12, b: 34)
62/// ```
63///
64/// When printed in alternate form (`"{error:#}"`):
65///
66/// ```text
67/// static error code: detailed dynamic error message
68///   at my-crate/src/main.rs:25:16
69///   with context
70///   ├─ we found that a (12) is not b (34)
71///   │    at my-crate/src/main.rs:25:16
72///   ╰─ while working in my_procedure (a: 12, b: 34)
73///        at my-crate/src/main.rs:22:1
74/// ```
75#[derive(Clone)]
76pub struct Diagnostic<K> {
77    // TODO: Perf Test: It might be better to move `kind` out here?
78    // TODO: Does this *need* to be Send/Sync ala `Arc`; why not `Box`?
79    //       One reason it might need to be is to keep the traits implemented
80    //       as similar as possible between error envelopes - let's think about
81    //       this more, however. (The whole `Diagnostic` envelope, really.)
82    inner: Arc<BoxedData<K>>,
83}
84
85// =============================================================================
86// IMPLS
87// =============================================================================
88
89// -----------------------------------------------------------------------------
90impl<K: ErrorKind> Diagnostic<K> {
91    #[inline]
92    pub(crate) fn into_description(self) -> String {
93        self.into_metadata().description
94    }
95
96    #[inline]
97    pub(crate) fn into_location(self) -> Option<&'static Location<'static>> {
98        self.into_metadata().location
99    }
100
101    #[inline]
102    pub(crate) fn into_metadata(self) -> ErrorMetadata {
103        Arc::unwrap_or_clone(self.inner).metadata
104    }
105}
106
107// -----------------------------------------------------------------------------
108impl<K> Diagnostic<K> {
109    #[inline]
110    pub(crate) fn error_kind_ref(&self) -> &K {
111        &self.inner.kind
112    }
113}
114
115// =============================================================================
116// TRAIT IMPLS
117// =============================================================================
118
119// -----------------------------------------------------------------------------
120crate::envelopes::impl_error_adapter_traits! {
121    others={
122        alloc=[Described],
123        core=[Located],
124    },
125    type=Diagnostic,
126}
127
128// -----------------------------------------------------------------------------
129impl<K: Debug> Debug for Diagnostic<K> {
130    #[track_caller]
131    #[inline]
132    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
133        let inner = &*self.inner;
134        cfg_select! {
135            feature = "backtrace" => f.debug_struct("Diagnostic")
136            .field("backtrace", &inner.metadata.backtrace)
137            .field("context", &inner.metadata.context)
138            .field("description", &inner.metadata.description)
139            .field("kind", &inner.kind)
140            .field("location", &inner.metadata.location)
141            .finish(),
142           _ => f.debug_struct("Diagnostic")
143            .field("context", &inner.metadata.context)
144            .field("description", &inner.metadata.description)
145            .field("kind", &inner.kind)
146            .field("location", &inner.metadata.location)
147            .finish(),
148        }
149    }
150}
151
152// -----------------------------------------------------------------------------
153impl<K: ErrorKind> Display for Diagnostic<K> {
154    #[track_caller]
155    #[inline]
156    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
157        let inner = &*self.inner;
158        Display::fmt(&inner.kind, f)?;
159        inner.metadata.write_metadata(f)
160    }
161}
162
163// -----------------------------------------------------------------------------
164impl<K: ErrorKind> ErrorEnvelope for Diagnostic<K> {
165    type Kind = K;
166    type Envelope<T: ErrorKind> = Diagnostic<T>;
167
168    #[track_caller]
169    #[inline]
170    fn convert<T>(self) -> Self::Envelope<T>
171    where
172        T: ErrorKind + From<Self::Kind>,
173    {
174        let inner = Arc::unwrap_or_clone(self.inner);
175        Diagnostic {
176            inner: Arc::new(BoxedData {
177                kind: From::from(inner.kind),
178                metadata: inner.metadata,
179            }),
180        }
181    }
182
183    #[track_caller]
184    #[inline]
185    fn error_kind(&self) -> Self::Kind {
186        self.inner.kind
187    }
188
189    #[track_caller]
190    #[inline]
191    fn new(kind: Self::Kind) -> Self {
192        Self::with_description(kind, String::new())
193    }
194
195    #[track_caller]
196    #[inline]
197    fn with_description<S>(kind: Self::Kind, description: S) -> Self
198    where
199        S: StaticString,
200    {
201        Self {
202            inner: Arc::new(BoxedData {
203                kind,
204                metadata: ErrorMetadata::new(description, Some(Location::caller())),
205            }),
206        }
207    }
208}
209
210// -----------------------------------------------------------------------------
211impl<K: ErrorKind> ErrorContext for Diagnostic<K> {
212    #[track_caller]
213    #[inline]
214    fn with_context<C, F>(mut self, context: F) -> Self
215    where
216        C: Context,
217        F: FnOnce() -> C,
218    {
219        Arc::make_mut(&mut self.inner)
220            .metadata
221            .context
222            .push(ContextEntry {
223                data: Arc::new(context()),
224                location: Location::caller(),
225            });
226        self
227    }
228}
229
230// -----------------------------------------------------------------------------
231impl<K: ErrorKind> From<K> for Diagnostic<K> {
232    #[inline]
233    fn from(orig: K) -> Self {
234        Self {
235            inner: Arc::new(BoxedData {
236                kind: orig,
237                metadata: ErrorMetadata::new("", None),
238            }),
239        }
240    }
241}
242
243// -----------------------------------------------------------------------------
244impl<K: ErrorKind> From<Described<K>> for Diagnostic<K> {
245    #[track_caller]
246    #[inline]
247    fn from(orig: Described<K>) -> Self {
248        Self {
249            inner: Arc::new(BoxedData {
250                kind: orig.error_kind(),
251                metadata: ErrorMetadata::new(orig.into_description(), None),
252            }),
253        }
254    }
255}
256
257// -----------------------------------------------------------------------------
258impl<K: ErrorKind> From<Located<K>> for Diagnostic<K> {
259    #[track_caller]
260    #[inline]
261    fn from(orig: Located<K>) -> Self {
262        Self {
263            inner: Arc::new(BoxedData {
264                kind: orig.error_kind(),
265                metadata: ErrorMetadata::new("", orig.into_location()),
266            }),
267        }
268    }
269}