1use crate::chain::Chain;
2use crate::EyreHandler;
3use crate::{Report, StdError};
4use core::any::TypeId;
5use core::fmt::{self, Debug, Display};
6use core::mem::{self, ManuallyDrop};
7use core::ptr::{self, NonNull};
8
9use core::ops::{Deref, DerefMut};
10
11impl Report {
12 /// Create a new error object from any error type.
13 ///
14 /// The error type must be threadsafe and `'static`, so that the `Report`
15 /// will be as well.
16 ///
17 /// If the error type does not provide a backtrace, a backtrace will be
18 /// created here to ensure that a backtrace exists.
19 #[cfg_attr(track_caller, track_caller)]
20 pub fn new<E>(error: E) -> Self
21 where
22 E: StdError + Send + Sync + 'static,
23 {
24 Report::from_std(error)
25 }
26
27 /// Create a new error object from a printable error message.
28 ///
29 /// If the argument implements std::error::Error, prefer `Report::new`
30 /// instead which preserves the underlying error's cause chain and
31 /// backtrace. If the argument may or may not implement std::error::Error
32 /// now or in the future, use `eyre!(err)` which handles either way
33 /// correctly.
34 ///
35 /// `Report::msg("...")` is equivalent to `eyre!("...")` but occasionally
36 /// convenient in places where a function is preferable over a macro, such
37 /// as iterator or stream combinators:
38 ///
39 /// ```
40 /// # mod ffi {
41 /// # pub struct Input;
42 /// # pub struct Output;
43 /// # pub async fn do_some_work(_: Input) -> Result<Output, &'static str> {
44 /// # unimplemented!()
45 /// # }
46 /// # }
47 /// #
48 /// # use ffi::{Input, Output};
49 /// #
50 /// use eyre::{Report, Result};
51 /// use futures::stream::{Stream, StreamExt, TryStreamExt};
52 ///
53 /// async fn demo<S>(stream: S) -> Result<Vec<Output>>
54 /// where
55 /// S: Stream<Item = Input>,
56 /// {
57 /// stream
58 /// .then(ffi::do_some_work) // returns Result<Output, &str>
59 /// .map_err(Report::msg)
60 /// .try_collect()
61 /// .await
62 /// }
63 /// ```
64 #[cfg_attr(track_caller, track_caller)]
65 pub fn msg<M>(message: M) -> Self
66 where
67 M: Display + Debug + Send + Sync + 'static,
68 {
69 Report::from_adhoc(message)
70 }
71
72 #[cfg_attr(track_caller, track_caller)]
73 pub(crate) fn from_std<E>(error: E) -> Self
74 where
75 E: StdError + Send + Sync + 'static,
76 {
77 let vtable = &ErrorVTable {
78 object_drop: object_drop::<E>,
79 object_ref: object_ref::<E>,
80 object_mut: object_mut::<E>,
81 object_boxed: object_boxed::<E>,
82 object_downcast: object_downcast::<E>,
83 object_drop_rest: object_drop_front::<E>,
84 };
85
86 // Safety: passing vtable that operates on the right type E.
87 let handler = Some(crate::capture_handler(&error));
88
89 unsafe { Report::construct(error, vtable, handler) }
90 }
91
92 #[cfg_attr(track_caller, track_caller)]
93 pub(crate) fn from_adhoc<M>(message: M) -> Self
94 where
95 M: Display + Debug + Send + Sync + 'static,
96 {
97 use crate::wrapper::MessageError;
98 let error: MessageError<M> = MessageError(message);
99 let vtable = &ErrorVTable {
100 object_drop: object_drop::<MessageError<M>>,
101 object_ref: object_ref::<MessageError<M>>,
102 object_mut: object_mut::<MessageError<M>>,
103 object_boxed: object_boxed::<MessageError<M>>,
104 object_downcast: object_downcast::<M>,
105 object_drop_rest: object_drop_front::<M>,
106 };
107
108 // Safety: MessageError is repr(transparent) so it is okay for the
109 // vtable to allow casting the MessageError<M> to M.
110 let handler = Some(crate::capture_handler(&error));
111
112 unsafe { Report::construct(error, vtable, handler) }
113 }
114
115 #[cfg_attr(track_caller, track_caller)]
116 pub(crate) fn from_display<M>(message: M) -> Self
117 where
118 M: Display + Send + Sync + 'static,
119 {
120 use crate::wrapper::{DisplayError, NoneError};
121 let error: DisplayError<M> = DisplayError(message);
122 let vtable = &ErrorVTable {
123 object_drop: object_drop::<DisplayError<M>>,
124 object_ref: object_ref::<DisplayError<M>>,
125 object_mut: object_mut::<DisplayError<M>>,
126 object_boxed: object_boxed::<DisplayError<M>>,
127 object_downcast: object_downcast::<M>,
128 object_drop_rest: object_drop_front::<M>,
129 };
130
131 // Safety: DisplayError is repr(transparent) so it is okay for the
132 // vtable to allow casting the DisplayError<M> to M.
133 let handler = Some(crate::capture_handler(&NoneError));
134
135 unsafe { Report::construct(error, vtable, handler) }
136 }
137
138 #[cfg_attr(track_caller, track_caller)]
139 pub(crate) fn from_msg<D, E>(msg: D, error: E) -> Self
140 where
141 D: Display + Send + Sync + 'static,
142 E: StdError + Send + Sync + 'static,
143 {
144 let error: ContextError<D, E> = ContextError { msg, error };
145
146 let vtable = &ErrorVTable {
147 object_drop: object_drop::<ContextError<D, E>>,
148 object_ref: object_ref::<ContextError<D, E>>,
149 object_mut: object_mut::<ContextError<D, E>>,
150 object_boxed: object_boxed::<ContextError<D, E>>,
151 object_downcast: context_downcast::<D, E>,
152 object_drop_rest: context_drop_rest::<D, E>,
153 };
154
155 // Safety: passing vtable that operates on the right type.
156 let handler = Some(crate::capture_handler(&error));
157
158 unsafe { Report::construct(error, vtable, handler) }
159 }
160
161 #[cfg_attr(track_caller, track_caller)]
162 pub(crate) fn from_boxed(error: Box<dyn StdError + Send + Sync>) -> Self {
163 use crate::wrapper::BoxedError;
164 let error = BoxedError(error);
165 let handler = Some(crate::capture_handler(&error));
166
167 let vtable = &ErrorVTable {
168 object_drop: object_drop::<BoxedError>,
169 object_ref: object_ref::<BoxedError>,
170 object_mut: object_mut::<BoxedError>,
171 object_boxed: object_boxed::<BoxedError>,
172 object_downcast: object_downcast::<Box<dyn StdError + Send + Sync>>,
173 object_drop_rest: object_drop_front::<Box<dyn StdError + Send + Sync>>,
174 };
175
176 // Safety: BoxedError is repr(transparent) so it is okay for the vtable
177 // to allow casting to Box<dyn StdError + Send + Sync>.
178 unsafe { Report::construct(error, vtable, handler) }
179 }
180
181 // Takes backtrace as argument rather than capturing it here so that the
182 // user sees one fewer layer of wrapping noise in the backtrace.
183 //
184 // Unsafe because the given vtable must have sensible behavior on the error
185 // value of type E.
186 unsafe fn construct<E>(
187 error: E,
188 vtable: &'static ErrorVTable,
189 handler: Option<Box<dyn EyreHandler>>,
190 ) -> Self
191 where
192 E: StdError + Send + Sync + 'static,
193 {
194 let inner = Box::new(ErrorImpl {
195 vtable,
196 handler,
197 _object: error,
198 });
199 // Erase the concrete type of E from the compile-time type system. This
200 // is equivalent to the safe unsize coersion from Box<ErrorImpl<E>> to
201 // Box<ErrorImpl<dyn StdError + Send + Sync + 'static>> except that the
202 // result is a thin pointer. The necessary behavior for manipulating the
203 // underlying ErrorImpl<E> is preserved in the vtable provided by the
204 // caller rather than a builtin fat pointer vtable.
205 let erased = mem::transmute::<Box<ErrorImpl<E>>, Box<ErrorImpl<()>>>(inner);
206 let inner = ManuallyDrop::new(erased);
207 Report { inner }
208 }
209
210 /// Create a new error from an error message to wrap the existing error.
211 ///
212 /// For attaching a higher level error message to a `Result` as it is propagated, the
213 /// [`WrapErr`][crate::WrapErr] extension trait may be more convenient than this function.
214 ///
215 /// The primary reason to use `error.wrap_err(...)` instead of `result.wrap_err(...)` via the
216 /// `WrapErr` trait would be if the message needs to depend on some data held by the underlying
217 /// error:
218 ///
219 /// ```
220 /// # use std::fmt::{self, Debug, Display};
221 /// #
222 /// # type T = ();
223 /// #
224 /// # impl std::error::Error for ParseError {}
225 /// # impl Debug for ParseError {
226 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
227 /// # unimplemented!()
228 /// # }
229 /// # }
230 /// # impl Display for ParseError {
231 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
232 /// # unimplemented!()
233 /// # }
234 /// # }
235 /// #
236 /// use eyre::Result;
237 /// use std::fs::File;
238 /// use std::path::Path;
239 ///
240 /// struct ParseError {
241 /// line: usize,
242 /// column: usize,
243 /// }
244 ///
245 /// fn parse_impl(file: File) -> Result<T, ParseError> {
246 /// # const IGNORE: &str = stringify! {
247 /// ...
248 /// # };
249 /// # unimplemented!()
250 /// }
251 ///
252 /// pub fn parse(path: impl AsRef<Path>) -> Result<T> {
253 /// let file = File::open(&path)?;
254 /// parse_impl(file).map_err(|error| {
255 /// let message = format!(
256 /// "only the first {} lines of {} are valid",
257 /// error.line, path.as_ref().display(),
258 /// );
259 /// eyre::Report::new(error).wrap_err(message)
260 /// })
261 /// }
262 /// ```
263 pub fn wrap_err<D>(mut self, msg: D) -> Self
264 where
265 D: Display + Send + Sync + 'static,
266 {
267 let handler = self.inner.handler.take();
268 let error: ContextError<D, Report> = ContextError { msg, error: self };
269
270 let vtable = &ErrorVTable {
271 object_drop: object_drop::<ContextError<D, Report>>,
272 object_ref: object_ref::<ContextError<D, Report>>,
273 object_mut: object_mut::<ContextError<D, Report>>,
274 object_boxed: object_boxed::<ContextError<D, Report>>,
275 object_downcast: context_chain_downcast::<D>,
276 object_drop_rest: context_chain_drop_rest::<D>,
277 };
278
279 // Safety: passing vtable that operates on the right type.
280 unsafe { Report::construct(error, vtable, handler) }
281 }
282
283 /// An iterator of the chain of source errors contained by this Report.
284 ///
285 /// This iterator will visit every error in the cause chain of this error
286 /// object, beginning with the error that this error object was created
287 /// from.
288 ///
289 /// # Example
290 ///
291 /// ```
292 /// use eyre::Report;
293 /// use std::io;
294 ///
295 /// pub fn underlying_io_error_kind(error: &Report) -> Option<io::ErrorKind> {
296 /// for cause in error.chain() {
297 /// if let Some(io_error) = cause.downcast_ref::<io::Error>() {
298 /// return Some(io_error.kind());
299 /// }
300 /// }
301 /// None
302 /// }
303 /// ```
304 pub fn chain(&self) -> Chain<'_> {
305 self.inner.chain()
306 }
307
308 /// The lowest level cause of this error &mdash; this error's cause's
309 /// cause's cause etc.
310 ///
311 /// The root cause is the last error in the iterator produced by
312 /// [`chain()`][Report::chain].
313 pub fn root_cause(&self) -> &(dyn StdError + 'static) {
314 let mut chain = self.chain();
315 let mut root_cause = chain.next().unwrap();
316 for cause in chain {
317 root_cause = cause;
318 }
319 root_cause
320 }
321
322 /// Returns true if `E` is the type held by this error object.
323 ///
324 /// For errors constructed from messages, this method returns true if `E` matches the type of
325 /// the message `D` **or** the type of the error on which the message has been attached. For
326 /// details about the interaction between message and downcasting, [see here].
327 ///
328 /// [see here]: trait.WrapErr.html#effect-on-downcasting
329 pub fn is<E>(&self) -> bool
330 where
331 E: Display + Debug + Send + Sync + 'static,
332 {
333 self.downcast_ref::<E>().is_some()
334 }
335
336 /// Attempt to downcast the error object to a concrete type.
337 pub fn downcast<E>(self) -> Result<E, Self>
338 where
339 E: Display + Debug + Send + Sync + 'static,
340 {
341 let target = TypeId::of::<E>();
342 unsafe {
343 // Use vtable to find NonNull<()> which points to a value of type E
344 // somewhere inside the data structure.
345 let addr = match (self.inner.vtable.object_downcast)(&self.inner, target) {
346 Some(addr) => addr,
347 None => return Err(self),
348 };
349
350 // Prepare to read E out of the data structure. We'll drop the rest
351 // of the data structure separately so that E is not dropped.
352 let outer = ManuallyDrop::new(self);
353
354 // Read E from where the vtable found it.
355 let error = ptr::read(addr.cast::<E>().as_ptr());
356
357 // Read Box<ErrorImpl<()>> from self. Can't move it out because
358 // Report has a Drop impl which we want to not run.
359 let inner = ptr::read(&outer.inner);
360 let erased = ManuallyDrop::into_inner(inner);
361
362 // Drop rest of the data structure outside of E.
363 (erased.vtable.object_drop_rest)(erased, target);
364
365 Ok(error)
366 }
367 }
368
369 /// Downcast this error object by reference.
370 ///
371 /// # Example
372 ///
373 /// ```
374 /// # use eyre::{Report, eyre};
375 /// # use std::fmt::{self, Display};
376 /// # use std::task::Poll;
377 /// #
378 /// # #[derive(Debug)]
379 /// # enum DataStoreError {
380 /// # Censored(()),
381 /// # }
382 /// #
383 /// # impl Display for DataStoreError {
384 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
385 /// # unimplemented!()
386 /// # }
387 /// # }
388 /// #
389 /// # impl std::error::Error for DataStoreError {}
390 /// #
391 /// # const REDACTED_CONTENT: () = ();
392 /// #
393 /// # #[cfg(not(feature = "auto-install"))]
394 /// # eyre::set_hook(Box::new(eyre::DefaultHandler::default_with)).unwrap();
395 /// #
396 /// # let error: Report = eyre!("...");
397 /// # let root_cause = &error;
398 /// #
399 /// # let ret =
400 /// // If the error was caused by redaction, then return a tombstone instead
401 /// // of the content.
402 /// match root_cause.downcast_ref::<DataStoreError>() {
403 /// Some(DataStoreError::Censored(_)) => Ok(Poll::Ready(REDACTED_CONTENT)),
404 /// None => Err(error),
405 /// }
406 /// # ;
407 /// ```
408 pub fn downcast_ref<E>(&self) -> Option<&E>
409 where
410 E: Display + Debug + Send + Sync + 'static,
411 {
412 let target = TypeId::of::<E>();
413 unsafe {
414 // Use vtable to find NonNull<()> which points to a value of type E
415 // somewhere inside the data structure.
416 let addr = (self.inner.vtable.object_downcast)(&self.inner, target)?;
417 Some(&*addr.cast::<E>().as_ptr())
418 }
419 }
420
421 /// Downcast this error object by mutable reference.
422 pub fn downcast_mut<E>(&mut self) -> Option<&mut E>
423 where
424 E: Display + Debug + Send + Sync + 'static,
425 {
426 let target = TypeId::of::<E>();
427 unsafe {
428 // Use vtable to find NonNull<()> which points to a value of type E
429 // somewhere inside the data structure.
430 let addr = (self.inner.vtable.object_downcast)(&self.inner, target)?;
431 Some(&mut *addr.cast::<E>().as_ptr())
432 }
433 }
434
435 /// Get a reference to the Handler for this Report.
436 pub fn handler(&self) -> &dyn EyreHandler {
437 self.inner.handler.as_ref().unwrap().as_ref()
438 }
439
440 /// Get a mutable reference to the Handler for this Report.
441 pub fn handler_mut(&mut self) -> &mut dyn EyreHandler {
442 self.inner.handler.as_mut().unwrap().as_mut()
443 }
444
445 /// Get a reference to the Handler for this Report.
446 #[doc(hidden)]
447 pub fn context(&self) -> &dyn EyreHandler {
448 self.inner.handler.as_ref().unwrap().as_ref()
449 }
450
451 /// Get a mutable reference to the Handler for this Report.
452 #[doc(hidden)]
453 pub fn context_mut(&mut self) -> &mut dyn EyreHandler {
454 self.inner.handler.as_mut().unwrap().as_mut()
455 }
456}
457
458impl<E> From<E> for Report
459where
460 E: StdError + Send + Sync + 'static,
461{
462 #[cfg_attr(track_caller, track_caller)]
463 fn from(error: E) -> Self {
464 Report::from_std(error)
465 }
466}
467
468impl Deref for Report {
469 type Target = dyn StdError + Send + Sync + 'static;
470
471 fn deref(&self) -> &Self::Target {
472 self.inner.error()
473 }
474}
475
476impl DerefMut for Report {
477 fn deref_mut(&mut self) -> &mut Self::Target {
478 self.inner.error_mut()
479 }
480}
481
482impl Display for Report {
483 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
484 self.inner.display(formatter)
485 }
486}
487
488impl Debug for Report {
489 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
490 self.inner.debug(formatter)
491 }
492}
493
494impl Drop for Report {
495 fn drop(&mut self) {
496 unsafe {
497 // Read Box<ErrorImpl<()>> from self.
498 let inner: ManuallyDrop>> = ptr::read(&self.inner);
499 let erased: Box> = ManuallyDrop::into_inner(slot:inner);
500
501 // Invoke the vtable's drop behavior.
502 (erased.vtable.object_drop)(erased);
503 }
504 }
505}
506
507struct ErrorVTable {
508 object_drop: unsafe fn(Box<ErrorImpl<()>>),
509 object_ref: unsafe fn(&ErrorImpl<()>) -> &(dyn StdError + Send + Sync + 'static),
510 object_mut: unsafe fn(&mut ErrorImpl<()>) -> &mut (dyn StdError + Send + Sync + 'static),
511 #[allow(clippy::type_complexity)]
512 object_boxed: unsafe fn(Box<ErrorImpl<()>>) -> Box<dyn StdError + Send + Sync + 'static>,
513 object_downcast: unsafe fn(&ErrorImpl<()>, TypeId) -> Option<NonNull<()>>,
514 object_drop_rest: unsafe fn(Box<ErrorImpl<()>>, TypeId),
515}
516
517// Safety: requires layout of *e to match ErrorImpl<E>.
518unsafe fn object_drop<E>(e: Box<ErrorImpl<()>>) {
519 // Cast back to ErrorImpl<E> so that the allocator receives the correct
520 // Layout to deallocate the Box's memory.
521 let unerased: Box> = mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<E>>>(src:e);
522 drop(unerased);
523}
524
525// Safety: requires layout of *e to match ErrorImpl<E>.
526unsafe fn object_drop_front<E>(e: Box<ErrorImpl<()>>, target: TypeId) {
527 // Drop the fields of ErrorImpl other than E as well as the Box allocation,
528 // without dropping E itself. This is used by downcast after doing a
529 // ptr::read to take ownership of the E.
530 let _ = target;
531 let unerased: Box>> = mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<ManuallyDrop<E>>>>(src:e);
532 drop(unerased);
533}
534
535// Safety: requires layout of *e to match ErrorImpl<E>.
536unsafe fn object_ref<E>(e: &ErrorImpl<()>) -> &(dyn StdError + Send + Sync + 'static)
537where
538 E: StdError + Send + Sync + 'static,
539{
540 // Attach E's native StdError vtable onto a pointer to self._object.
541 &(*(e as *const ErrorImpl<()> as *const ErrorImpl<E>))._object
542}
543
544// Safety: requires layout of *e to match ErrorImpl<E>.
545unsafe fn object_mut<E>(e: &mut ErrorImpl<()>) -> &mut (dyn StdError + Send + Sync + 'static)
546where
547 E: StdError + Send + Sync + 'static,
548{
549 // Attach E's native StdError vtable onto a pointer to self._object.
550 &mut (*(e as *mut ErrorImpl<()> as *mut ErrorImpl<E>))._object
551}
552
553// Safety: requires layout of *e to match ErrorImpl<E>.
554unsafe fn object_boxed<E>(e: Box<ErrorImpl<()>>) -> Box<dyn StdError + Send + Sync + 'static>
555where
556 E: StdError + Send + Sync + 'static,
557{
558 // Attach ErrorImpl<E>'s native StdError vtable. The StdError impl is below.
559 mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<E>>>(src:e)
560}
561
562// Safety: requires layout of *e to match ErrorImpl<E>.
563unsafe fn object_downcast<E>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>
564where
565 E: 'static,
566{
567 if TypeId::of::<E>() == target {
568 // Caller is looking for an E pointer and e is ErrorImpl<E>, take a
569 // pointer to its E field.
570 let unerased: *const ErrorImpl = e as *const ErrorImpl<()> as *const ErrorImpl<E>;
571 let addr: *mut () = &(*unerased)._object as *const E as *mut ();
572 Some(NonNull::new_unchecked(ptr:addr))
573 } else {
574 None
575 }
576}
577
578// Safety: requires layout of *e to match ErrorImpl<ContextError<D, E>>.
579unsafe fn context_downcast<D, E>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>
580where
581 D: 'static,
582 E: 'static,
583{
584 if TypeId::of::<D>() == target {
585 let unerased: *const ErrorImpl> = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<D, E>>;
586 let addr: *mut () = &(*unerased)._object.msg as *const D as *mut ();
587 Some(NonNull::new_unchecked(ptr:addr))
588 } else if TypeId::of::<E>() == target {
589 let unerased: *const ErrorImpl> = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<D, E>>;
590 let addr: *mut () = &(*unerased)._object.error as *const E as *mut ();
591 Some(NonNull::new_unchecked(ptr:addr))
592 } else {
593 None
594 }
595}
596
597// Safety: requires layout of *e to match ErrorImpl<ContextError<D, E>>.
598unsafe fn context_drop_rest<D, E>(e: Box<ErrorImpl<()>>, target: TypeId)
599where
600 D: 'static,
601 E: 'static,
602{
603 // Called after downcasting by value to either the D or the E and doing a
604 // ptr::read to take ownership of that value.
605 if TypeId::of::<D>() == target {
606 let unerased: Box>> = mem::transmute::<
607 Box<ErrorImpl<()>>,
608 Box<ErrorImpl<ContextError<ManuallyDrop<D>, E>>>,
609 >(src:e);
610 drop(unerased);
611 } else {
612 let unerased: Box>> = mem::transmute::<
613 Box<ErrorImpl<()>>,
614 Box<ErrorImpl<ContextError<D, ManuallyDrop<E>>>>,
615 >(src:e);
616 drop(unerased);
617 }
618}
619
620// Safety: requires layout of *e to match ErrorImpl<ContextError<D, Report>>.
621unsafe fn context_chain_downcast<D>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>
622where
623 D: 'static,
624{
625 let unerased: *const ErrorImpl> = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<D, Report>>;
626 if TypeId::of::<D>() == target {
627 let addr: *mut () = &(*unerased)._object.msg as *const D as *mut ();
628 Some(NonNull::new_unchecked(ptr:addr))
629 } else {
630 // Recurse down the context chain per the inner error's vtable.
631 let source: &Report = &(*unerased)._object.error;
632 (source.inner.vtable.object_downcast)(&source.inner, target)
633 }
634}
635
636// Safety: requires layout of *e to match ErrorImpl<ContextError<D, Report>>.
637unsafe fn context_chain_drop_rest<D>(e: Box<ErrorImpl<()>>, target: TypeId)
638where
639 D: 'static,
640{
641 // Called after downcasting by value to either the D or one of the causes
642 // and doing a ptr::read to take ownership of that value.
643 if TypeId::of::<D>() == target {
644 let unerased: Box>> = mem::transmute::<
645 Box<ErrorImpl<()>>,
646 Box<ErrorImpl<ContextError<ManuallyDrop<D>, Report>>>,
647 >(src:e);
648 // Drop the entire rest of the data structure rooted in the next Report.
649 drop(unerased);
650 } else {
651 let unerased: Box>> = mem::transmute::<
652 Box<ErrorImpl<()>>,
653 Box<ErrorImpl<ContextError<D, ManuallyDrop<Report>>>>,
654 >(src:e);
655 // Read out a ManuallyDrop<Box<ErrorImpl<()>>> from the next error.
656 let inner: ManuallyDrop>> = ptr::read(&unerased._object.error.inner);
657 drop(unerased);
658 let erased: Box> = ManuallyDrop::into_inner(slot:inner);
659 // Recursively drop the next error using the same target typeid.
660 (erased.vtable.object_drop_rest)(erased, target);
661 }
662}
663
664// repr C to ensure that E remains in the final position.
665#[repr(C)]
666pub(crate) struct ErrorImpl<E> {
667 vtable: &'static ErrorVTable,
668 pub(crate) handler: Option<Box<dyn EyreHandler>>,
669 // NOTE: Don't use directly. Use only through vtable. Erased type may have
670 // different alignment.
671 _object: E,
672}
673
674// repr C to ensure that ContextError<D, E> has the same layout as
675// ContextError<ManuallyDrop<D>, E> and ContextError<D, ManuallyDrop<E>>.
676#[repr(C)]
677pub(crate) struct ContextError<D, E> {
678 pub(crate) msg: D,
679 pub(crate) error: E,
680}
681
682impl<E> ErrorImpl<E> {
683 fn erase(&self) -> &ErrorImpl<()> {
684 // Erase the concrete type of E but preserve the vtable in self.vtable
685 // for manipulating the resulting thin pointer. This is analogous to an
686 // unsize coersion.
687 unsafe { &*(self as *const ErrorImpl<E> as *const ErrorImpl<()>) }
688 }
689}
690
691impl ErrorImpl<()> {
692 pub(crate) fn error(&self) -> &(dyn StdError + Send + Sync + 'static) {
693 // Use vtable to attach E's native StdError vtable for the right
694 // original type E.
695 unsafe { &*(self.vtable.object_ref)(self) }
696 }
697
698 pub(crate) fn error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static) {
699 // Use vtable to attach E's native StdError vtable for the right
700 // original type E.
701 unsafe { &mut *(self.vtable.object_mut)(self) }
702 }
703
704 pub(crate) fn chain(&self) -> Chain<'_> {
705 Chain::new(self.error())
706 }
707}
708
709impl<E> StdError for ErrorImpl<E>
710where
711 E: StdError,
712{
713 fn source(&self) -> Option<&(dyn StdError + 'static)> {
714 self.erase().error().source()
715 }
716}
717
718impl<E> Debug for ErrorImpl<E>
719where
720 E: Debug,
721{
722 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
723 self.erase().debug(formatter)
724 }
725}
726
727impl<E> Display for ErrorImpl<E>
728where
729 E: Display,
730{
731 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
732 Display::fmt(&self.erase().error(), f:formatter)
733 }
734}
735
736impl From<Report> for Box<dyn StdError + Send + Sync + 'static> {
737 fn from(error: Report) -> Self {
738 let outer: ManuallyDrop = ManuallyDrop::new(error);
739 unsafe {
740 // Read Box<ErrorImpl<()>> from error. Can't move it out because
741 // Report has a Drop impl which we want to not run.
742 let inner: ManuallyDrop>> = ptr::read(&outer.inner);
743 let erased: Box> = ManuallyDrop::into_inner(slot:inner);
744
745 // Use vtable to attach ErrorImpl<E>'s native StdError vtable for
746 // the right original type E.
747 (erased.vtable.object_boxed)(erased)
748 }
749 }
750}
751
752impl From<Report> for Box<dyn StdError + 'static> {
753 fn from(error: Report) -> Self {
754 Box::<dyn StdError + Send + Sync>::from(error)
755 }
756}
757
758impl AsRef<dyn StdError + Send + Sync> for Report {
759 fn as_ref(&self) -> &(dyn StdError + Send + Sync + 'static) {
760 &**self
761 }
762}
763
764impl AsRef<dyn StdError> for Report {
765 fn as_ref(&self) -> &(dyn StdError + 'static) {
766 &**self
767 }
768}
769
770#[cfg(feature = "pyo3")]
771mod pyo3_compat;
772