Skip to content
Myr

error.rs

This file

Path

src/error.rs

1,086 lines · 38.6 KiB · Rust

Last changed by

Merge pull request #436 from dtolnay/upDavid Tolnaybefore adoption67df012

History of this file

Take it

The walk stopped after 200 commits: lines older than 9bd74a1 point at it.

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 1–2why, one step back
1use crate::backtrace::Backtrace;
2use crate::chain::Chain;

Merge pull request #414 from dtolnay/nightlyDavid Tolnaybefore adoption213a9c2

lines 3–4why, one step back
3#[cfg(error_generic_member_access)]
4use crate::nightly::{self, Request};

Merge pull request #435 from dtolnay/upDavid Tolnaybefore adoptionb86c3c8

line 5why, one step back
5#[cfg(any(feature = "std", not(anyhow_no_core_error)))]

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 6–12why, one step back
6use crate::ptr::Mut;
7use crate::ptr::{Own, Ref};8use crate::{Error, StdError};9use alloc::boxed::Box;10use core::any::TypeId;11use core::fmt::{self, Debug, Display};12use core::mem::ManuallyDrop;

Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf

lines 13–14why, one step back
13#[cfg(any(feature = "std", not(anyhow_no_core_error)))]
14use core::ops::{Deref, DerefMut};

Merge pull request #386 from dtolnay/unwindsafeDavid Tolnaybefore adoption830c399

line 15why, one step back
15use core::panic::{RefUnwindSafe, UnwindSafe};

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 16–26why, one step back
16use core::ptr;
17use core::ptr::NonNull;1819impl Error {20 /// Create a new error object from any error type.21 ///22 /// The error type must be threadsafe and `'static`, so that the `Error`23 /// will be as well.24 ///25 /// If the error type does not provide a backtrace, a backtrace will be26 /// created here to ensure that a backtrace exists.

Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf

line 27why, one step back
27 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 28–34why, one step back
28 #[cold]
29 #[must_use]30 pub fn new<E>(error: E) -> Self31 where32 E: StdError + Send + Sync + 'static,33 {34 let backtrace = backtrace_if_absent!(&error);

Merge pull request #401 from dtolnay/constructDavid Tolnaybefore adoptionffecefc

line 35why, one step back
35 Error::construct_from_std(error, backtrace)

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 36–80why, one step back
36 }
3738 /// Create a new error object from a printable error message.39 ///40 /// If the argument implements std::error::Error, prefer `Error::new`41 /// instead which preserves the underlying error's cause chain and42 /// backtrace. If the argument may or may not implement std::error::Error43 /// now or in the future, use `anyhow!(err)` which handles either way44 /// correctly.45 ///46 /// `Error::msg("...")` is equivalent to `anyhow!("...")` but occasionally47 /// convenient in places where a function is preferable over a macro, such48 /// as iterator or stream combinators:49 ///50 /// ```51 /// # mod ffi {52 /// # pub struct Input;53 /// # pub struct Output;54 /// # pub async fn do_some_work(_: Input) -> Result<Output, &'static str> {55 /// # unimplemented!()56 /// # }57 /// # }58 /// #59 /// # use ffi::{Input, Output};60 /// #61 /// use anyhow::{Error, Result};62 /// use futures::stream::{Stream, StreamExt, TryStreamExt};63 ///64 /// async fn demo<S>(stream: S) -> Result<Vec<Output>>65 /// where66 /// S: Stream<Item = Input>,67 /// {68 /// stream69 /// .then(ffi::do_some_work) // returns Result<Output, &str>70 /// .map_err(Error::msg)71 /// .try_collect()72 /// .await73 /// }74 /// ```75 #[cold]76 #[must_use]77 pub fn msg<M>(message: M) -> Self78 where79 M: Display + Debug + Send + Sync + 'static,80 {

Merge pull request #401 from dtolnay/constructDavid Tolnaybefore adoptionffecefc

line 81why, one step back
81 Error::construct_from_adhoc(message, backtrace!())

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 82–83why, one step back
82 }
83

Merge pull request #402 from dtolnay/fromboxedDavid Tolnaybefore adoptiona03d6d6

lines 84–144why, one step back
84 /// Construct an error object from a type-erased standard library error.
85 ///86 /// This is mostly useful for interop with other error libraries.87 ///88 /// # Example89 ///90 /// Here is a skeleton of a library that provides its own error abstraction.91 /// The pair of `From` impls provide bidirectional support for `?`92 /// conversion between `Report` and `anyhow::Error`.93 ///94 /// ```95 /// use std::error::Error as StdError;96 ///97 /// pub struct Report {/* ... */}98 ///99 /// impl<E> From<E> for Report100 /// where101 /// E: Into<anyhow::Error>,102 /// Result<(), E>: anyhow::Context<(), E>,103 /// {104 /// fn from(error: E) -> Self {105 /// let anyhow_error: anyhow::Error = error.into();106 /// let boxed_error: Box<dyn StdError + Send + Sync + 'static> = anyhow_error.into();107 /// Report::from_boxed(boxed_error)108 /// }109 /// }110 ///111 /// impl From<Report> for anyhow::Error {112 /// fn from(report: Report) -> Self {113 /// let boxed_error: Box<dyn StdError + Send + Sync + 'static> = report.into_boxed();114 /// anyhow::Error::from_boxed(boxed_error)115 /// }116 /// }117 ///118 /// impl Report {119 /// fn from_boxed(boxed_error: Box<dyn StdError + Send + Sync + 'static>) -> Self {120 /// todo!()121 /// }122 /// fn into_boxed(self) -> Box<dyn StdError + Send + Sync + 'static> {123 /// todo!()124 /// }125 /// }126 ///127 /// // Example usage: can use `?` in both directions.128 /// fn a() -> anyhow::Result<()> {129 /// b()?;130 /// Ok(())131 /// }132 /// fn b() -> Result<(), Report> {133 /// a()?;134 /// Ok(())135 /// }136 /// ```137 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]138 #[cold]139 #[must_use]140 pub fn from_boxed(boxed_error: Box<dyn StdError + Send + Sync + 'static>) -> Self {141 let backtrace = backtrace_if_absent!(&*boxed_error);142 Error::construct_from_boxed(boxed_error, backtrace)143 }144

Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf

line 145why, one step back
145 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

line 146why, one step back
146 #[cold]

Merge pull request #401 from dtolnay/constructDavid Tolnaybefore adoptionffecefc

line 147why, one step back
147 pub(crate) fn construct_from_std<E>(error: E, backtrace: Option<Backtrace>) -> Self

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 148–154why, one step back
148 where
149 E: StdError + Send + Sync + 'static,150 {151 let vtable = &ErrorVTable {152 object_drop: object_drop::<E>,153 object_ref: object_ref::<E>,154 object_boxed: object_boxed::<E>,

Merge pull request #415 from dtolnay/intodynDavid Tolnaybefore adoptioncbc1ad2

line 155why, one step back
155 object_reallocate_boxed: object_reallocate_boxed::<E>,

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 156–157why, one step back
156 object_downcast: object_downcast::<E>,
157 object_drop_rest: object_drop_front::<E>,

Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194

lines 158–159why, one step back
158 #[cfg(all(
159 not(error_generic_member_access),

Merge pull request #332 from dtolnay/stdbacktraceDavid Tolnaybefore adoption53109e6

line 160why, one step back
160 any(std_backtrace, feature = "backtrace")

Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194

line 161why, one step back
161 ))]

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 162–169why, one step back
162 object_backtrace: no_backtrace,
163 };164165 // Safety: passing vtable that operates on the right type E.166 unsafe { Error::construct(error, vtable, backtrace) }167 }168169 #[cold]

Merge pull request #401 from dtolnay/constructDavid Tolnaybefore adoptionffecefc

line 170why, one step back
170 pub(crate) fn construct_from_adhoc<M>(message: M, backtrace: Option<Backtrace>) -> Self

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 171–178why, one step back
171 where
172 M: Display + Debug + Send + Sync + 'static,173 {174 use crate::wrapper::MessageError;175 let error: MessageError<M> = MessageError(message);176 let vtable = &ErrorVTable {177 object_drop: object_drop::<MessageError<M>>,178 object_ref: object_ref::<MessageError<M>>,

Merge pull request #416 from dtolnay/oldnostdDavid Tolnaybefore adoption29f2edd

line 179why, one step back
179 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

line 180why, one step back
180 object_boxed: object_boxed::<MessageError<M>>,

Merge pull request #415 from dtolnay/intodynDavid Tolnaybefore adoptioncbc1ad2

lines 181–182why, one step back
181 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
182 object_reallocate_boxed: object_reallocate_boxed::<MessageError<M>>,

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 183–184why, one step back
183 object_downcast: object_downcast::<M>,
184 object_drop_rest: object_drop_front::<M>,

Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194

lines 185–186why, one step back
185 #[cfg(all(
186 not(error_generic_member_access),

Merge pull request #332 from dtolnay/stdbacktraceDavid Tolnaybefore adoption53109e6

line 187why, one step back
187 any(std_backtrace, feature = "backtrace")

Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194

line 188why, one step back
188 ))]

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 189–197why, one step back
189 object_backtrace: no_backtrace,
190 };191192 // Safety: MessageError is repr(transparent) so it is okay for the193 // vtable to allow casting the MessageError<M> to M.194 unsafe { Error::construct(error, vtable, backtrace) }195 }196197 #[cold]

Merge pull request #401 from dtolnay/constructDavid Tolnaybefore adoptionffecefc

line 198why, one step back
198 pub(crate) fn construct_from_display<M>(message: M, backtrace: Option<Backtrace>) -> Self

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 199–206why, one step back
199 where
200 M: Display + Send + Sync + 'static,201 {202 use crate::wrapper::DisplayError;203 let error: DisplayError<M> = DisplayError(message);204 let vtable = &ErrorVTable {205 object_drop: object_drop::<DisplayError<M>>,206 object_ref: object_ref::<DisplayError<M>>,

Merge pull request #416 from dtolnay/oldnostdDavid Tolnaybefore adoption29f2edd

line 207why, one step back
207 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

line 208why, one step back
208 object_boxed: object_boxed::<DisplayError<M>>,

Merge pull request #415 from dtolnay/intodynDavid Tolnaybefore adoptioncbc1ad2

lines 209–210why, one step back
209 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
210 object_reallocate_boxed: object_reallocate_boxed::<DisplayError<M>>,

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 211–212why, one step back
211 object_downcast: object_downcast::<M>,
212 object_drop_rest: object_drop_front::<M>,

Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194

lines 213–214why, one step back
213 #[cfg(all(
214 not(error_generic_member_access),

Merge pull request #332 from dtolnay/stdbacktraceDavid Tolnaybefore adoption53109e6

line 215why, one step back
215 any(std_backtrace, feature = "backtrace")

Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194

line 216why, one step back
216 ))]

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 217–224why, one step back
217 object_backtrace: no_backtrace,
218 };219220 // Safety: DisplayError is repr(transparent) so it is okay for the221 // vtable to allow casting the DisplayError<M> to M.222 unsafe { Error::construct(error, vtable, backtrace) }223 }224

Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf

line 225why, one step back
225 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

line 226why, one step back
226 #[cold]

Merge pull request #401 from dtolnay/constructDavid Tolnaybefore adoptionffecefc

lines 227–231why, one step back
227 pub(crate) fn construct_from_context<C, E>(
228 context: C,229 error: E,230 backtrace: Option<Backtrace>,231 ) -> Self

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 232–240why, one step back
232 where
233 C: Display + Send + Sync + 'static,234 E: StdError + Send + Sync + 'static,235 {236 let error: ContextError<C, E> = ContextError { context, error };237238 let vtable = &ErrorVTable {239 object_drop: object_drop::<ContextError<C, E>>,240 object_ref: object_ref::<ContextError<C, E>>,

Merge pull request #416 from dtolnay/oldnostdDavid Tolnaybefore adoption29f2edd

line 241why, one step back
241 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

line 242why, one step back
242 object_boxed: object_boxed::<ContextError<C, E>>,

Merge pull request #415 from dtolnay/intodynDavid Tolnaybefore adoptioncbc1ad2

lines 243–244why, one step back
243 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
244 object_reallocate_boxed: object_reallocate_boxed::<ContextError<C, E>>,

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 245–246why, one step back
245 object_downcast: context_downcast::<C, E>,
246 object_drop_rest: context_drop_rest::<C, E>,

Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194

lines 247–248why, one step back
247 #[cfg(all(
248 not(error_generic_member_access),

Merge pull request #332 from dtolnay/stdbacktraceDavid Tolnaybefore adoption53109e6

line 249why, one step back
249 any(std_backtrace, feature = "backtrace")

Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194

line 250why, one step back
250 ))]

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 251–257why, one step back
251 object_backtrace: no_backtrace,
252 };253254 // Safety: passing vtable that operates on the right type.255 unsafe { Error::construct(error, vtable, backtrace) }256 }257

Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf

line 258why, one step back
258 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

line 259why, one step back
259 #[cold]

Merge pull request #401 from dtolnay/constructDavid Tolnaybefore adoptionffecefc

line 260why, one step back
260 pub(crate) fn construct_from_boxed(

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 261–268why, one step back
261 error: Box<dyn StdError + Send + Sync>,
262 backtrace: Option<Backtrace>,263 ) -> Self {264 use crate::wrapper::BoxedError;265 let error = BoxedError(error);266 let vtable = &ErrorVTable {267 object_drop: object_drop::<BoxedError>,268 object_ref: object_ref::<BoxedError>,

Merge pull request #416 from dtolnay/oldnostdDavid Tolnaybefore adoption29f2edd

line 269why, one step back
269 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

line 270why, one step back
270 object_boxed: object_boxed::<BoxedError>,

Merge pull request #415 from dtolnay/intodynDavid Tolnaybefore adoptioncbc1ad2

lines 271–272why, one step back
271 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
272 object_reallocate_boxed: object_reallocate_boxed::<BoxedError>,

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 273–274why, one step back
273 object_downcast: object_downcast::<Box<dyn StdError + Send + Sync>>,
274 object_drop_rest: object_drop_front::<Box<dyn StdError + Send + Sync>>,

Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194

lines 275–276why, one step back
275 #[cfg(all(
276 not(error_generic_member_access),

Merge pull request #332 from dtolnay/stdbacktraceDavid Tolnaybefore adoption53109e6

line 277why, one step back
277 any(std_backtrace, feature = "backtrace")

Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194

line 278why, one step back
278 ))]

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 279–383why, one step back
279 object_backtrace: no_backtrace,
280 };281282 // Safety: BoxedError is repr(transparent) so it is okay for the vtable283 // to allow casting to Box<dyn StdError + Send + Sync>.284 unsafe { Error::construct(error, vtable, backtrace) }285 }286287 // Takes backtrace as argument rather than capturing it here so that the288 // user sees one fewer layer of wrapping noise in the backtrace.289 //290 // Unsafe because the given vtable must have sensible behavior on the error291 // value of type E.292 #[cold]293 unsafe fn construct<E>(294 error: E,295 vtable: &'static ErrorVTable,296 backtrace: Option<Backtrace>,297 ) -> Self298 where299 E: StdError + Send + Sync + 'static,300 {301 let inner: Box<ErrorImpl<E>> = Box::new(ErrorImpl {302 vtable,303 backtrace,304 _object: error,305 });306 // Erase the concrete type of E from the compile-time type system. This307 // is equivalent to the safe unsize coercion from Box<ErrorImpl<E>> to308 // Box<ErrorImpl<dyn StdError + Send + Sync + 'static>> except that the309 // result is a thin pointer. The necessary behavior for manipulating the310 // underlying ErrorImpl<E> is preserved in the vtable provided by the311 // caller rather than a builtin fat pointer vtable.312 let inner = Own::new(inner).cast::<ErrorImpl>();313 Error { inner }314 }315316 /// Wrap the error value with additional context.317 ///318 /// For attaching context to a `Result` as it is propagated, the319 /// [`Context`][crate::Context] extension trait may be more convenient than320 /// this function.321 ///322 /// The primary reason to use `error.context(...)` instead of323 /// `result.context(...)` via the `Context` trait would be if the context324 /// needs to depend on some data held by the underlying error:325 ///326 /// ```327 /// # use std::fmt::{self, Debug, Display};328 /// #329 /// # type T = ();330 /// #331 /// # impl std::error::Error for ParseError {}332 /// # impl Debug for ParseError {333 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {334 /// # unimplemented!()335 /// # }336 /// # }337 /// # impl Display for ParseError {338 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {339 /// # unimplemented!()340 /// # }341 /// # }342 /// #343 /// use anyhow::Result;344 /// use std::fs::File;345 /// use std::path::Path;346 ///347 /// struct ParseError {348 /// line: usize,349 /// column: usize,350 /// }351 ///352 /// fn parse_impl(file: File) -> Result<T, ParseError> {353 /// # const IGNORE: &str = stringify! {354 /// ...355 /// # };356 /// # unimplemented!()357 /// }358 ///359 /// pub fn parse(path: impl AsRef<Path>) -> Result<T> {360 /// let file = File::open(&path)?;361 /// parse_impl(file).map_err(|error| {362 /// let context = format!(363 /// "only the first {} lines of {} are valid",364 /// error.line, path.as_ref().display(),365 /// );366 /// anyhow::Error::new(error).context(context)367 /// })368 /// }369 /// ```370 #[cold]371 #[must_use]372 pub fn context<C>(self, context: C) -> Self373 where374 C: Display + Send + Sync + 'static,375 {376 let error: ContextError<C, Error> = ContextError {377 context,378 error: self,379 };380381 let vtable = &ErrorVTable {382 object_drop: object_drop::<ContextError<C, Error>>,383 object_ref: object_ref::<ContextError<C, Error>>,

Merge pull request #416 from dtolnay/oldnostdDavid Tolnaybefore adoption29f2edd

line 384why, one step back
384 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

line 385why, one step back
385 object_boxed: object_boxed::<ContextError<C, Error>>,

Merge pull request #415 from dtolnay/intodynDavid Tolnaybefore adoptioncbc1ad2

lines 386–387why, one step back
386 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
387 object_reallocate_boxed: object_reallocate_boxed::<ContextError<C, Error>>,

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 388–389why, one step back
388 object_downcast: context_chain_downcast::<C>,
389 object_drop_rest: context_chain_drop_rest::<C>,

Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194

lines 390–391why, one step back
390 #[cfg(all(
391 not(error_generic_member_access),

Merge pull request #332 from dtolnay/stdbacktraceDavid Tolnaybefore adoption53109e6

line 392why, one step back
392 any(std_backtrace, feature = "backtrace")

Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194

line 393why, one step back
393 ))]

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 394–420why, one step back
394 object_backtrace: context_backtrace::<C>,
395 };396397 // As the cause is anyhow::Error, we already have a backtrace for it.398 let backtrace = None;399400 // Safety: passing vtable that operates on the right type.401 unsafe { Error::construct(error, vtable, backtrace) }402 }403404 /// Get the backtrace for this Error.405 ///406 /// In order for the backtrace to be meaningful, one of the two environment407 /// variables `RUST_LIB_BACKTRACE=1` or `RUST_BACKTRACE=1` must be defined408 /// and `RUST_LIB_BACKTRACE` must not be `0`. Backtraces are somewhat409 /// expensive to capture in Rust, so we don't necessarily want to be410 /// capturing them all over the place all the time.411 ///412 /// - If you want panics and errors to both have backtraces, set413 /// `RUST_BACKTRACE=1`;414 /// - If you want only errors to have backtraces, set415 /// `RUST_LIB_BACKTRACE=1`;416 /// - If you want only panics to have backtraces, set `RUST_BACKTRACE=1` and417 /// `RUST_LIB_BACKTRACE=0`.418 ///419 /// # Stability420 ///

Touch up PR 293David Tolnaybefore adoptionb6ac995

lines 421–422why, one step back
421 /// Standard library backtraces are only available when using Rust &ge;
422 /// 1.65. On older compilers, this function is only available if the crate's

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

line 423why, one step back
423 /// "backtrace" feature is enabled, and will use the `backtrace` crate as

Touch up PR 293David Tolnaybefore adoptionb6ac995

lines 424–425why, one step back
424 /// the underlying backtrace implementation. The return type of this
425 /// function on old compilers is `&(impl Debug + Display)`.

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 426–430why, one step back
426 ///
427 /// ```toml428 /// [dependencies]429 /// anyhow = { version = "1.0", features = ["backtrace"] }430 /// ```

Merge pull request #332 from dtolnay/stdbacktraceDavid Tolnaybefore adoption53109e6

line 431why, one step back
431 #[cfg(any(std_backtrace, feature = "backtrace"))]

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 432–456why, one step back
432 pub fn backtrace(&self) -> &impl_backtrace!() {
433 unsafe { ErrorImpl::backtrace(self.inner.by_ref()) }434 }435436 /// An iterator of the chain of source errors contained by this Error.437 ///438 /// This iterator will visit every error in the cause chain of this error439 /// object, beginning with the error that this error object was created440 /// from.441 ///442 /// # Example443 ///444 /// ```445 /// use anyhow::Error;446 /// use std::io;447 ///448 /// pub fn underlying_io_error_kind(error: &Error) -> Option<io::ErrorKind> {449 /// for cause in error.chain() {450 /// if let Some(io_error) = cause.downcast_ref::<io::Error>() {451 /// return Some(io_error.kind());452 /// }453 /// }454 /// None455 /// }456 /// ```

Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf

line 457why, one step back
457 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 458–467why, one step back
458 #[cold]
459 pub fn chain(&self) -> Chain {460 unsafe { ErrorImpl::chain(self.inner.by_ref()) }461 }462463 /// The lowest level cause of this error &mdash; this error's cause's464 /// cause's cause etc.465 ///466 /// The root cause is the last error in the iterator produced by467 /// [`chain()`][Error::chain].

Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf

line 468why, one step back
468 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]

Ignore double_ended_iterator_last clippy lintDavid Tolnaybefore adoption4d71a84

line 469why, one step back
469 #[allow(clippy::double_ended_iterator_last)]

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 470–480why, one step back
470 pub fn root_cause(&self) -> &(dyn StdError + 'static) {
471 self.chain().last().unwrap()472 }473474 /// Returns true if `E` is the type held by this error object.475 ///476 /// For errors with context, this method returns true if `E` matches the477 /// type of the context `C` **or** the type of the error on which the478 /// context has been attached. For details about the interaction between479 /// context and downcasting, [see here].480 ///

Convert html links to intra-doc linksDavid Tolnaybefore adoptionbc33c24

line 481why, one step back
481 /// [see here]: crate::Context#effect-on-downcasting

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 482–581why, one step back
482 pub fn is<E>(&self) -> bool
483 where484 E: Display + Debug + Send + Sync + 'static,485 {486 self.downcast_ref::<E>().is_some()487 }488489 /// Attempt to downcast the error object to a concrete type.490 pub fn downcast<E>(mut self) -> Result<E, Self>491 where492 E: Display + Debug + Send + Sync + 'static,493 {494 let target = TypeId::of::<E>();495 let inner = self.inner.by_mut();496 unsafe {497 // Use vtable to find NonNull<()> which points to a value of type E498 // somewhere inside the data structure.499 let addr = match (vtable(inner.ptr).object_downcast)(inner.by_ref(), target) {500 Some(addr) => addr.by_mut().extend(),501 None => return Err(self),502 };503504 // Prepare to read E out of the data structure. We'll drop the rest505 // of the data structure separately so that E is not dropped.506 let outer = ManuallyDrop::new(self);507508 // Read E from where the vtable found it.509 let error = addr.cast::<E>().read();510511 // Drop rest of the data structure outside of E.512 (vtable(outer.inner.ptr).object_drop_rest)(outer.inner, target);513514 Ok(error)515 }516 }517518 /// Downcast this error object by reference.519 ///520 /// # Example521 ///522 /// ```523 /// # use anyhow::anyhow;524 /// # use std::fmt::{self, Display};525 /// # use std::task::Poll;526 /// #527 /// # #[derive(Debug)]528 /// # enum DataStoreError {529 /// # Censored(()),530 /// # }531 /// #532 /// # impl Display for DataStoreError {533 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {534 /// # unimplemented!()535 /// # }536 /// # }537 /// #538 /// # impl std::error::Error for DataStoreError {}539 /// #540 /// # const REDACTED_CONTENT: () = ();541 /// #542 /// # let error = anyhow!("...");543 /// # let root_cause = &error;544 /// #545 /// # let ret =546 /// // If the error was caused by redaction, then return a tombstone instead547 /// // of the content.548 /// match root_cause.downcast_ref::<DataStoreError>() {549 /// Some(DataStoreError::Censored(_)) => Ok(Poll::Ready(REDACTED_CONTENT)),550 /// None => Err(error),551 /// }552 /// # ;553 /// ```554 pub fn downcast_ref<E>(&self) -> Option<&E>555 where556 E: Display + Debug + Send + Sync + 'static,557 {558 let target = TypeId::of::<E>();559 unsafe {560 // Use vtable to find NonNull<()> which points to a value of type E561 // somewhere inside the data structure.562 let addr = (vtable(self.inner.ptr).object_downcast)(self.inner.by_ref(), target)?;563 Some(addr.cast::<E>().deref())564 }565 }566567 /// Downcast this error object by mutable reference.568 pub fn downcast_mut<E>(&mut self) -> Option<&mut E>569 where570 E: Display + Debug + Send + Sync + 'static,571 {572 let target = TypeId::of::<E>();573 unsafe {574 // Use vtable to find NonNull<()> which points to a value of type E575 // somewhere inside the data structure.576 let addr =577 (vtable(self.inner.ptr).object_downcast)(self.inner.by_ref(), target)?.by_mut();578 Some(addr.cast::<E>().deref_mut())579 }580 }581

Merge pull request #415 from dtolnay/intodynDavid Tolnaybefore adoptioncbc1ad2

lines 582–673why, one step back
582 /// Convert to a standard library error trait object.
583 ///584 /// This is implemented as a cheap pointer cast that does not allocate or585 /// deallocate memory. Like [`anyhow::Error::from_boxed`], it's useful for586 /// interop with other error libraries.587 ///588 /// The same conversion is also available as589 /// <code style="display:inline;white-space:normal;">impl From&lt;anyhow::Error&gt;590 /// for Box&lt;dyn Error + Send + Sync + &apos;static&gt;</code>.591 ///592 /// If a backtrace was collected during construction of the `anyhow::Error`,593 /// that backtrace remains accessible using the standard library `Error`594 /// trait's provider API, but as a consequence, the resulting boxed error595 /// can no longer be downcast to its original underlying type.596 ///597 /// ```598 #[cfg_attr(not(error_generic_member_access), doc = "# _ = stringify! {")]599 /// #![feature(error_generic_member_access)]600 ///601 /// use anyhow::anyhow;602 /// use std::backtrace::Backtrace;603 /// use thiserror::Error;604 ///605 /// #[derive(Error, Debug)]606 /// #[error("...")]607 /// struct MyError;608 ///609 /// let anyhow_error = anyhow!(MyError);610 /// println!("{}", anyhow_error.backtrace()); // has Backtrace611 /// assert!(anyhow_error.downcast_ref::<MyError>().is_some()); // can downcast612 ///613 /// let boxed_dyn_error = anyhow_error.into_boxed_dyn_error();614 /// assert!(std::error::request_ref::<Backtrace>(&*boxed_dyn_error).is_some()); // has Backtrace615 /// assert!(boxed_dyn_error.downcast_ref::<MyError>().is_none()); // can no longer downcast616 #[cfg_attr(not(error_generic_member_access), doc = "# };")]617 /// ```618 ///619 /// [`anyhow::Error::from_boxed`]: Self::from_boxed620 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]621 #[must_use]622 pub fn into_boxed_dyn_error(self) -> Box<dyn StdError + Send + Sync + 'static> {623 let outer = ManuallyDrop::new(self);624 unsafe {625 // Use vtable to attach ErrorImpl<E>'s native StdError vtable for626 // the right original type E.627 (vtable(outer.inner.ptr).object_boxed)(outer.inner)628 }629 }630631 /// Convert to a standard library error trait object.632 ///633 /// Unlike `self.into_boxed_dyn_error()`, this method relocates the634 /// underlying error into a new allocation in order to make it downcastable635 /// to `&E` or `Box<E>` for its original underlying error type. Any636 /// backtrace collected during construction of the `anyhow::Error` is637 /// discarded.638 ///639 /// ```640 #[cfg_attr(not(error_generic_member_access), doc = "# _ = stringify!{")]641 /// #![feature(error_generic_member_access)]642 ///643 /// use anyhow::anyhow;644 /// use std::backtrace::Backtrace;645 /// use thiserror::Error;646 ///647 /// #[derive(Error, Debug)]648 /// #[error("...")]649 /// struct MyError;650 ///651 /// let anyhow_error = anyhow!(MyError);652 /// println!("{}", anyhow_error.backtrace()); // has Backtrace653 /// assert!(anyhow_error.downcast_ref::<MyError>().is_some()); // can downcast654 ///655 /// let boxed_dyn_error = anyhow_error.reallocate_into_boxed_dyn_error_without_backtrace();656 /// assert!(std::error::request_ref::<Backtrace>(&*boxed_dyn_error).is_none()); // Backtrace lost657 /// assert!(boxed_dyn_error.downcast_ref::<MyError>().is_some()); // can downcast to &MyError658 /// assert!(boxed_dyn_error.downcast::<MyError>().is_ok()); // can downcast to Box<MyError>659 #[cfg_attr(not(error_generic_member_access), doc = "# };")]660 /// ```661 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]662 #[must_use]663 pub fn reallocate_into_boxed_dyn_error_without_backtrace(664 self,665 ) -> Box<dyn StdError + Send + Sync + 'static> {666 let outer = ManuallyDrop::new(self);667 unsafe {668 // Use vtable to attach E's native StdError vtable for the right669 // original type E.670 (vtable(outer.inner.ptr).object_reallocate_boxed)(outer.inner)671 }672 }673

Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194

line 674why, one step back
674 #[cfg(error_generic_member_access)]

Merge pull request #319 from dtolnay/errorprovideDavid Tolnaybefore adoption8cf1d15

lines 675–678why, one step back
675 pub(crate) fn provide<'a>(&'a self, request: &mut Request<'a>) {
676 unsafe { ErrorImpl::provide(self.inner.by_ref(), request) }677 }678

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 679–683why, one step back
679 // Called by thiserror when you have `#[source] anyhow::Error`. This provide
680 // implementation includes the anyhow::Error's Backtrace if any, unlike681 // deref'ing to dyn Error where the provide implementation would include682 // only the original error's Backtrace from before it got wrapped into an683 // anyhow::Error.

Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194

line 684why, one step back
684 #[cfg(error_generic_member_access)]

Merge pull request #319 from dtolnay/errorprovideDavid Tolnaybefore adoption8cf1d15

lines 685–687why, one step back
685 #[doc(hidden)]
686 pub fn thiserror_provide<'a>(&'a self, request: &mut Request<'a>) {687 Self::provide(self, request);

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 688–690why, one step back
688 }
689}690

Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf

line 691why, one step back
691#[cfg(any(feature = "std", not(anyhow_no_core_error)))]

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 692–698why, one step back
692impl<E> From<E> for Error
693where694 E: StdError + Send + Sync + 'static,695{696 #[cold]697 fn from(error: E) -> Self {698 let backtrace = backtrace_if_absent!(&error);

Merge pull request #401 from dtolnay/constructDavid Tolnaybefore adoptionffecefc

line 699why, one step back
699 Error::construct_from_std(error, backtrace)

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 700–702why, one step back
700 }
701}702

Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf

line 703why, one step back
703#[cfg(any(feature = "std", not(anyhow_no_core_error)))]

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 704–711why, one step back
704impl Deref for Error {
705 type Target = dyn StdError + Send + Sync + 'static;706707 fn deref(&self) -> &Self::Target {708 unsafe { ErrorImpl::error(self.inner.by_ref()) }709 }710}711

Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf

line 712why, one step back
712#[cfg(any(feature = "std", not(anyhow_no_core_error)))]

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 713–742why, one step back
713impl DerefMut for Error {
714 fn deref_mut(&mut self) -> &mut Self::Target {715 unsafe { ErrorImpl::error_mut(self.inner.by_mut()) }716 }717}718719impl Display for Error {720 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {721 unsafe { ErrorImpl::display(self.inner.by_ref(), formatter) }722 }723}724725impl Debug for Error {726 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {727 unsafe { ErrorImpl::debug(self.inner.by_ref(), formatter) }728 }729}730731impl Drop for Error {732 fn drop(&mut self) {733 unsafe {734 // Invoke the vtable's drop behavior.735 (vtable(self.inner.ptr).object_drop)(self.inner);736 }737 }738}739740struct ErrorVTable {741 object_drop: unsafe fn(Own<ErrorImpl>),742 object_ref: unsafe fn(Ref<ErrorImpl>) -> Ref<dyn StdError + Send + Sync + 'static>,

Merge pull request #416 from dtolnay/oldnostdDavid Tolnaybefore adoption29f2edd

line 743why, one step back
743 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

line 744why, one step back
744 object_boxed: unsafe fn(Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>,

Merge pull request #415 from dtolnay/intodynDavid Tolnaybefore adoptioncbc1ad2

lines 745–746why, one step back
745 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
746 object_reallocate_boxed: unsafe fn(Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>,

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 747–748why, one step back
747 object_downcast: unsafe fn(Ref<ErrorImpl>, TypeId) -> Option<Ref<()>>,
748 object_drop_rest: unsafe fn(Own<ErrorImpl>, TypeId),

Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194

lines 749–750why, one step back
749 #[cfg(all(
750 not(error_generic_member_access),

Merge pull request #332 from dtolnay/stdbacktraceDavid Tolnaybefore adoption53109e6

line 751why, one step back
751 any(std_backtrace, feature = "backtrace")

Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194

line 752why, one step back
752 ))]

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 753–759why, one step back
753 object_backtrace: unsafe fn(Ref<ErrorImpl>) -> Option<&Backtrace>,
754}755756// Safety: requires layout of *e to match ErrorImpl<E>.757unsafe fn object_drop<E>(e: Own<ErrorImpl>) {758 // Cast back to ErrorImpl<E> so that the allocator receives the correct759 // Layout to deallocate the Box's memory.

Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49

lines 760–761why, one step back
760 let unerased_own = e.cast::<ErrorImpl<E>>();
761 drop(unsafe { unerased_own.boxed() });

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 762–769why, one step back
762}
763764// Safety: requires layout of *e to match ErrorImpl<E>.765unsafe fn object_drop_front<E>(e: Own<ErrorImpl>, target: TypeId) {766 // Drop the fields of ErrorImpl other than E as well as the Box allocation,767 // without dropping E itself. This is used by downcast after doing a768 // ptr::read to take ownership of the E.769 let _ = target;

Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49

lines 770–771why, one step back
770 let unerased_own = e.cast::<ErrorImpl<ManuallyDrop<E>>>();
771 drop(unsafe { unerased_own.boxed() });

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 772–779why, one step back
772}
773774// Safety: requires layout of *e to match ErrorImpl<E>.775unsafe fn object_ref<E>(e: Ref<ErrorImpl>) -> Ref<dyn StdError + Send + Sync + 'static>776where777 E: StdError + Send + Sync + 'static,778{779 // Attach E's native StdError vtable onto a pointer to self._object.

Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49

line 780why, one step back
780 let unerased_ref = e.cast::<ErrorImpl<E>>();

Merge pull request #435 from dtolnay/upDavid Tolnaybefore adoptionb86c3c8

line 781why, one step back
781 Ref::from_raw(unsafe {

Merge pull request #436 from dtolnay/upDavid Tolnaybefore adoption67df012

line 782why, one step back
782 NonNull::new_unchecked(ptr::addr_of!((*unerased_ref.as_ptr())._object).cast_mut())

Merge pull request #435 from dtolnay/upDavid Tolnaybefore adoptionb86c3c8

line 783why, one step back
783 })

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 784–786why, one step back
784}
785786// Safety: requires layout of *e to match ErrorImpl<E>.

Merge pull request #416 from dtolnay/oldnostdDavid Tolnaybefore adoption29f2edd

line 787why, one step back
787#[cfg(any(feature = "std", not(anyhow_no_core_error)))]

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 788–792why, one step back
788unsafe fn object_boxed<E>(e: Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>
789where790 E: StdError + Send + Sync + 'static,791{792 // Attach ErrorImpl<E>'s native StdError vtable. The StdError impl is below.

Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49

lines 793–794why, one step back
793 let unerased_own = e.cast::<ErrorImpl<E>>();
794 unsafe { unerased_own.boxed() }

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 795–797why, one step back
795}
796797// Safety: requires layout of *e to match ErrorImpl<E>.

Merge pull request #415 from dtolnay/intodynDavid Tolnaybefore adoptioncbc1ad2

lines 798–808why, one step back
798#[cfg(any(feature = "std", not(anyhow_no_core_error)))]
799unsafe fn object_reallocate_boxed<E>(e: Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>800where801 E: StdError + Send + Sync + 'static,802{803 // Attach E's native StdError vtable.804 let unerased_own = e.cast::<ErrorImpl<E>>();805 Box::new(unsafe { unerased_own.boxed() }._object)806}807808// Safety: requires layout of *e to match ErrorImpl<E>.

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 809–815why, one step back
809unsafe fn object_downcast<E>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>
810where811 E: 'static,812{813 if TypeId::of::<E>() == target {814 // Caller is looking for an E pointer and e is ErrorImpl<E>, take a815 // pointer to its E field.

Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49

line 816why, one step back
816 let unerased_ref = e.cast::<ErrorImpl<E>>();

Merge pull request #435 from dtolnay/upDavid Tolnaybefore adoptionb86c3c8

line 817why, one step back
817 Some(

Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49

line 818why, one step back
818 Ref::from_raw(unsafe {

Merge pull request #436 from dtolnay/upDavid Tolnaybefore adoption67df012

line 819why, one step back
819 NonNull::new_unchecked(ptr::addr_of!((*unerased_ref.as_ptr())._object).cast_mut())

Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49

line 820why, one step back
820 })

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

line 821why, one step back
821 .cast::<()>(),

Merge pull request #435 from dtolnay/upDavid Tolnaybefore adoptionb86c3c8

line 822why, one step back
822 )

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 823–827why, one step back
823 } else {
824 None825 }826}827

Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194

lines 828–829why, one step back
828#[cfg(all(
829 not(error_generic_member_access),

Merge pull request #332 from dtolnay/stdbacktraceDavid Tolnaybefore adoption53109e6

line 830why, one step back
830 any(std_backtrace, feature = "backtrace")

Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194

line 831why, one step back
831))]

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 832–837why, one step back
832fn no_backtrace(e: Ref<ErrorImpl>) -> Option<&Backtrace> {
833 let _ = e;834 None835}836837// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.

Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf

line 838why, one step back
838#[cfg(any(feature = "std", not(anyhow_no_core_error)))]

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 839–844why, one step back
839unsafe fn context_downcast<C, E>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>
840where841 C: 'static,842 E: 'static,843{844 if TypeId::of::<C>() == target {

Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49

lines 845–846why, one step back
845 let unerased_ref = e.cast::<ErrorImpl<ContextError<C, E>>>();
846 let unerased = unsafe { unerased_ref.deref() };

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 847–848why, one step back
847 Some(Ref::new(&unerased._object.context).cast::<()>())
848 } else if TypeId::of::<E>() == target {

Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49

lines 849–850why, one step back
849 let unerased_ref = e.cast::<ErrorImpl<ContextError<C, E>>>();
850 let unerased = unsafe { unerased_ref.deref() };

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 851–857why, one step back
851 Some(Ref::new(&unerased._object.error).cast::<()>())
852 } else {853 None854 }855}856857// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.

Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf

line 858why, one step back
858#[cfg(any(feature = "std", not(anyhow_no_core_error)))]

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 859–866why, one step back
859unsafe fn context_drop_rest<C, E>(e: Own<ErrorImpl>, target: TypeId)
860where861 C: 'static,862 E: 'static,863{864 // Called after downcasting by value to either the C or the E and doing a865 // ptr::read to take ownership of that value.866 if TypeId::of::<C>() == target {

Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49

lines 867–868why, one step back
867 let unerased_own = e.cast::<ErrorImpl<ContextError<ManuallyDrop<C>, E>>>();
868 drop(unsafe { unerased_own.boxed() });

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

line 869why, one step back
869 } else {

Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49

lines 870–871why, one step back
870 let unerased_own = e.cast::<ErrorImpl<ContextError<C, ManuallyDrop<E>>>>();
871 drop(unsafe { unerased_own.boxed() });

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 872–879why, one step back
872 }
873}874875// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.876unsafe fn context_chain_downcast<C>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>877where878 C: 'static,879{

Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49

lines 880–881why, one step back
880 let unerased_ref = e.cast::<ErrorImpl<ContextError<C, Error>>>();
881 let unerased = unsafe { unerased_ref.deref() };

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 882–886why, one step back
882 if TypeId::of::<C>() == target {
883 Some(Ref::new(&unerased._object.context).cast::<()>())884 } else {885 // Recurse down the context chain per the inner error's vtable.886 let source = &unerased._object.error;

Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49

line 887why, one step back
887 unsafe { (vtable(source.inner.ptr).object_downcast)(source.inner.by_ref(), target) }

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 888–898why, one step back
888 }
889}890891// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.892unsafe fn context_chain_drop_rest<C>(e: Own<ErrorImpl>, target: TypeId)893where894 C: 'static,895{896 // Called after downcasting by value to either the C or one of the causes897 // and doing a ptr::read to take ownership of that value.898 if TypeId::of::<C>() == target {

Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49

line 899why, one step back
899 let unerased_own = e.cast::<ErrorImpl<ContextError<ManuallyDrop<C>, Error>>>();

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

line 900why, one step back
900 // Drop the entire rest of the data structure rooted in the next Error.

Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49

line 901why, one step back
901 drop(unsafe { unerased_own.boxed() });

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

line 902why, one step back
902 } else {

Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49

lines 903–904why, one step back
903 let unerased_own = e.cast::<ErrorImpl<ContextError<C, ManuallyDrop<Error>>>>();
904 let unerased = unsafe { unerased_own.boxed() };

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 905–907why, one step back
905 // Read the Own<ErrorImpl> from the next error.
906 let inner = unerased._object.error.inner;907 drop(unerased);

Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49

line 908why, one step back
908 let vtable = unsafe { vtable(inner.ptr) };

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

line 909why, one step back
909 // Recursively drop the next error using the same target typeid.

Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49

line 910why, one step back
910 unsafe { (vtable.object_drop_rest)(inner, target) };

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 911–914why, one step back
911 }
912}913914// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.

Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194

lines 915–916why, one step back
915#[cfg(all(
916 not(error_generic_member_access),

Merge pull request #332 from dtolnay/stdbacktraceDavid Tolnaybefore adoption53109e6

line 917why, one step back
917 any(std_backtrace, feature = "backtrace")

Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194

line 918why, one step back
918))]

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 919–923why, one step back
919#[allow(clippy::unnecessary_wraps)]
920unsafe fn context_backtrace<C>(e: Ref<ErrorImpl>) -> Option<&Backtrace>921where922 C: 'static,923{

Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49

lines 924–926why, one step back
924 let unerased_ref = e.cast::<ErrorImpl<ContextError<C, Error>>>();
925 let unerased = unsafe { unerased_ref.deref() };926 let backtrace = unsafe { ErrorImpl::backtrace(unerased._object.error.inner.by_ref()) };

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 927–945why, one step back
927 Some(backtrace)
928}929930// NOTE: If working with `ErrorImpl<()>`, references should be avoided in favor931// of raw pointers and `NonNull`.932// repr C to ensure that E remains in the final position.933#[repr(C)]934pub(crate) struct ErrorImpl<E = ()> {935 vtable: &'static ErrorVTable,936 backtrace: Option<Backtrace>,937 // NOTE: Don't use directly. Use only through vtable. Erased type may have938 // different alignment.939 _object: E,940}941942// Reads the vtable out of `p`. This is the same as `p.as_ref().vtable`, but943// avoids converting `p` into a reference.944unsafe fn vtable(p: NonNull<ErrorImpl>) -> &'static ErrorVTable {945 // NOTE: This assumes that `ErrorVTable` is the first field of ErrorImpl.

Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49

line 946why, one step back
946 unsafe { *(p.as_ptr() as *const &'static ErrorVTable) }

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 947–969why, one step back
947}
948949// repr C to ensure that ContextError<C, E> has the same layout as950// ContextError<ManuallyDrop<C>, E> and ContextError<C, ManuallyDrop<E>>.951#[repr(C)]952pub(crate) struct ContextError<C, E> {953 pub context: C,954 pub error: E,955}956957impl<E> ErrorImpl<E> {958 fn erase(&self) -> Ref<ErrorImpl> {959 // Erase the concrete type of E but preserve the vtable in self.vtable960 // for manipulating the resulting thin pointer. This is analogous to an961 // unsize coercion.962 Ref::new(self).cast::<ErrorImpl>()963 }964}965966impl ErrorImpl {967 pub(crate) unsafe fn error(this: Ref<Self>) -> &(dyn StdError + Send + Sync + 'static) {968 // Use vtable to attach E's native StdError vtable for the right969 // original type E.

Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49

line 970why, one step back
970 unsafe { (vtable(this.ptr).object_ref)(this).deref() }

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 971–972why, one step back
971 }
972

Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf

line 973why, one step back
973 #[cfg(any(feature = "std", not(anyhow_no_core_error)))]

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 974–976why, one step back
974 pub(crate) unsafe fn error_mut(this: Mut<Self>) -> &mut (dyn StdError + Send + Sync + 'static) {
975 // Use vtable to attach E's native StdError vtable for the right976 // original type E.

Merge pull request #435 from dtolnay/upDavid Tolnaybefore adoptionb86c3c8

line 977why, one step back
977 unsafe {

Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49

lines 978–980why, one step back
978 (vtable(this.ptr).object_ref)(this.by_ref())
979 .by_mut()980 .deref_mut()

Merge pull request #435 from dtolnay/upDavid Tolnaybefore adoptionb86c3c8

line 981why, one step back
981 }

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 982–983why, one step back
982 }
983

Merge pull request #332 from dtolnay/stdbacktraceDavid Tolnaybefore adoption53109e6

line 984why, one step back
984 #[cfg(any(std_backtrace, feature = "backtrace"))]

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 985–988why, one step back
985 pub(crate) unsafe fn backtrace(this: Ref<Self>) -> &Backtrace {
986 // This unwrap can only panic if the underlying error's backtrace method987 // is nondeterministic, which would only happen in maliciously988 // constructed code.

Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49

line 989why, one step back
989 unsafe { this.deref() }

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 990–992why, one step back
990 .backtrace
991 .as_ref()992 .or_else(|| {

Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194

line 993why, one step back
993 #[cfg(error_generic_member_access)]

Merge pull request #414 from dtolnay/nightlyDavid Tolnaybefore adoption213a9c2

line 994why, one step back
994 return nightly::request_ref_backtrace(unsafe { Self::error(this) });

Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194

line 995why, one step back
995 #[cfg(not(error_generic_member_access))]

Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49

line 996why, one step back
996 return unsafe { (vtable(this.ptr).object_backtrace)(this) };

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 997–1000why, one step back
997 })
998 .expect("backtrace capture failed")999 }1000

Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194

line 1001why, one step back
1001 #[cfg(error_generic_member_access)]

Merge pull request #319 from dtolnay/errorprovideDavid Tolnaybefore adoption8cf1d15

line 1002why, one step back
1002 unsafe fn provide<'a>(this: Ref<'a, Self>, request: &mut Request<'a>) {

Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49

line 1003why, one step back
1003 if let Some(backtrace) = unsafe { &this.deref().backtrace } {

Merge pull request #414 from dtolnay/nightlyDavid Tolnaybefore adoption213a9c2

line 1004why, one step back
1004 nightly::provide_ref_backtrace(request, backtrace);

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

line 1005why, one step back
1005 }

Merge pull request #414 from dtolnay/nightlyDavid Tolnaybefore adoption213a9c2

line 1006why, one step back
1006 nightly::provide(unsafe { Self::error(this) }, request);

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 1007–1010why, one step back
1007 }
10081009 #[cold]1010 pub(crate) unsafe fn chain(this: Ref<Self>) -> Chain {

Merge pull request #329 from dtolnay/unsafeopDavid Tolnaybefore adoptiond371a49

line 1011why, one step back
1011 Chain::new(unsafe { Self::error(this) })

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 1012–1022why, one step back
1012 }
1013}10141015impl<E> StdError for ErrorImpl<E>1016where1017 E: StdError,1018{1019 fn source(&self) -> Option<&(dyn StdError + 'static)> {1020 unsafe { ErrorImpl::error(self.erase()).source() }1021 }1022

Merge pull request #331 from dtolnay/backtraceDavid Tolnaybefore adoptioncf66194

line 1023why, one step back
1023 #[cfg(error_generic_member_access)]

Merge pull request #319 from dtolnay/errorprovideDavid Tolnaybefore adoption8cf1d15

lines 1024–1025why, one step back
1024 fn provide<'a>(&'a self, request: &mut Request<'a>) {
1025 unsafe { ErrorImpl::provide(self.erase(), request) }

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 1026–1046why, one step back
1026 }
1027}10281029impl<E> Debug for ErrorImpl<E>1030where1031 E: Debug,1032{1033 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {1034 unsafe { ErrorImpl::debug(self.erase(), formatter) }1035 }1036}10371038impl<E> Display for ErrorImpl<E>1039where1040 E: Display,1041{1042 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {1043 unsafe { Display::fmt(ErrorImpl::error(self.erase()), formatter) }1044 }1045}1046

Merge pull request #416 from dtolnay/oldnostdDavid Tolnaybefore adoption29f2edd

line 1047why, one step back
1047#[cfg(any(feature = "std", not(anyhow_no_core_error)))]

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 1048–1050why, one step back
1048impl From<Error> for Box<dyn StdError + Send + Sync + 'static> {
1049 #[cold]1050 fn from(error: Error) -> Self {

Merge pull request #415 from dtolnay/intodynDavid Tolnaybefore adoptioncbc1ad2

line 1051why, one step back
1051 error.into_boxed_dyn_error()

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 1052–1054why, one step back
1052 }
1053}1054

Merge pull request #416 from dtolnay/oldnostdDavid Tolnaybefore adoption29f2edd

line 1055why, one step back
1055#[cfg(any(feature = "std", not(anyhow_no_core_error)))]

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

line 1056why, one step back
1056impl From<Error> for Box<dyn StdError + Send + 'static> {

Merge pull request #415 from dtolnay/intodynDavid Tolnaybefore adoptioncbc1ad2

line 1057why, one step back
1057 #[cold]

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

line 1058why, one step back
1058 fn from(error: Error) -> Self {

Merge pull request #415 from dtolnay/intodynDavid Tolnaybefore adoptioncbc1ad2

line 1059why, one step back
1059 error.into_boxed_dyn_error()

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 1060–1062why, one step back
1060 }
1061}1062

Merge pull request #416 from dtolnay/oldnostdDavid Tolnaybefore adoption29f2edd

line 1063why, one step back
1063#[cfg(any(feature = "std", not(anyhow_no_core_error)))]

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

line 1064why, one step back
1064impl From<Error> for Box<dyn StdError + 'static> {

Merge pull request #415 from dtolnay/intodynDavid Tolnaybefore adoptioncbc1ad2

line 1065why, one step back
1065 #[cold]

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

line 1066why, one step back
1066 fn from(error: Error) -> Self {

Merge pull request #415 from dtolnay/intodynDavid Tolnaybefore adoptioncbc1ad2

line 1067why, one step back
1067 error.into_boxed_dyn_error()

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 1068–1070why, one step back
1068 }
1069}1070

Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf

line 1071why, one step back
1071#[cfg(any(feature = "std", not(anyhow_no_core_error)))]

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 1072–1077why, one step back
1072impl AsRef<dyn StdError + Send + Sync> for Error {
1073 fn as_ref(&self) -> &(dyn StdError + Send + Sync + 'static) {1074 &**self1075 }1076}1077

Merge pull request #383 from dtolnay/nostdDavid Tolnaybefore adoption8ecfcdf

line 1078why, one step back
1078#[cfg(any(feature = "std", not(anyhow_no_core_error)))]

Restore pre-nightly-2022-10-05 behavior of test_path PhantomData testsDavid Tolnaybefore adoption9bd74a1

lines 1079–1083why, one step back
1079impl AsRef<dyn StdError> for Error {
1080 fn as_ref(&self) -> &(dyn StdError + 'static) {1081 &**self1082 }1083}

Merge pull request #386 from dtolnay/unwindsafeDavid Tolnaybefore adoption830c399

lines 1084–1086why, one step back
1084
1085impl UnwindSafe for Error {}1086impl RefUnwindSafe for Error {}