core/error.rs
1#![doc = include_str!("error.md")]
2#![stable(feature = "error_in_core", since = "1.81.0")]
3
4use crate::any::TypeId;
5use crate::fmt::{self, Debug, Display, Formatter};
6
7/// `Error` is a trait representing the basic expectations for error values,
8/// i.e., values of type `E` in [`Result<T, E>`].
9///
10/// Errors must describe themselves through the [`Display`] and [`Debug`]
11/// traits. Error messages are typically concise lowercase sentences without
12/// trailing punctuation:
13///
14/// ```
15/// let err = "NaN".parse::<u32>().unwrap_err();
16/// assert_eq!(err.to_string(), "invalid digit found in string");
17/// ```
18///
19/// # Error source
20///
21/// Errors may provide cause information. [`Error::source()`] is generally
22/// used when errors cross "abstraction boundaries". If one module must report
23/// an error that is caused by an error from a lower-level module, it can allow
24/// accessing that error via `Error::source()`. This makes it possible for the
25/// high-level module to provide its own errors while also revealing some of the
26/// implementation for debugging.
27///
28/// In error types that wrap an underlying error, the underlying error
29/// should be either returned by the outer error's `Error::source()`, or rendered
30/// by the outer error's `Display` implementation, but not both.
31///
32/// # Example
33///
34/// Implementing the `Error` trait only requires that `Debug` and `Display` are implemented too.
35///
36/// ```
37/// use std::error::Error;
38/// use std::fmt;
39/// use std::path::PathBuf;
40///
41/// #[derive(Debug)]
42/// struct ReadConfigError {
43/// path: PathBuf
44/// }
45///
46/// impl fmt::Display for ReadConfigError {
47/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48/// let path = self.path.display();
49/// write!(f, "unable to read configuration at {path}")
50/// }
51/// }
52///
53/// impl Error for ReadConfigError {}
54/// ```
55#[stable(feature = "rust1", since = "1.0.0")]
56#[rustc_diagnostic_item = "Error"]
57#[rustc_has_incoherent_inherent_impls]
58#[allow(multiple_supertrait_upcastable)]
59pub trait Error: Debug + Display {
60 /// Returns the lower-level source of this error, if any.
61 ///
62 /// # Examples
63 ///
64 /// ```
65 /// use std::error::Error;
66 /// use std::fmt;
67 ///
68 /// #[derive(Debug)]
69 /// struct SuperError {
70 /// source: SuperErrorSideKick,
71 /// }
72 ///
73 /// impl fmt::Display for SuperError {
74 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75 /// write!(f, "SuperError is here!")
76 /// }
77 /// }
78 ///
79 /// impl Error for SuperError {
80 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
81 /// Some(&self.source)
82 /// }
83 /// }
84 ///
85 /// #[derive(Debug)]
86 /// struct SuperErrorSideKick;
87 ///
88 /// impl fmt::Display for SuperErrorSideKick {
89 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90 /// write!(f, "SuperErrorSideKick is here!")
91 /// }
92 /// }
93 ///
94 /// impl Error for SuperErrorSideKick {}
95 ///
96 /// fn get_super_error() -> Result<(), SuperError> {
97 /// Err(SuperError { source: SuperErrorSideKick })
98 /// }
99 ///
100 /// fn main() {
101 /// match get_super_error() {
102 /// Err(e) => {
103 /// println!("Error: {e}");
104 /// println!("Caused by: {}", e.source().unwrap());
105 /// }
106 /// _ => println!("No error"),
107 /// }
108 /// }
109 /// ```
110 #[stable(feature = "error_source", since = "1.30.0")]
111 fn source(&self) -> Option<&(dyn Error + 'static)> {
112 None
113 }
114
115 /// Gets the `TypeId` of `self`.
116 #[doc(hidden)]
117 #[unstable(
118 feature = "error_type_id",
119 reason = "this is memory-unsafe to override in user code",
120 issue = "60784"
121 )]
122 fn type_id(&self, _: private::Internal) -> TypeId
123 where
124 Self: 'static,
125 {
126 TypeId::of::<Self>()
127 }
128
129 /// ```
130 /// if let Err(e) = "xc".parse::<u32>() {
131 /// // Print `e` itself, no need for description().
132 /// eprintln!("Error: {e}");
133 /// }
134 /// ```
135 #[stable(feature = "rust1", since = "1.0.0")]
136 #[deprecated(since = "1.42.0", note = "use the Display impl or to_string()")]
137 fn description(&self) -> &str {
138 "description() is deprecated; use Display"
139 }
140
141 #[stable(feature = "rust1", since = "1.0.0")]
142 #[deprecated(
143 since = "1.33.0",
144 note = "replaced by Error::source, which can support downcasting"
145 )]
146 #[allow(missing_docs)]
147 fn cause(&self) -> Option<&dyn Error> {
148 self.source()
149 }
150
151 /// Provides type-based access to context intended for error reports.
152 ///
153 /// Used in conjunction with [`Request::provide_value`] and [`Request::provide_ref`] to extract
154 /// references to member variables from `dyn Error` trait objects.
155 ///
156 /// # Example
157 ///
158 /// ```rust
159 /// #![feature(error_generic_member_access)]
160 /// use core::fmt;
161 /// use core::error::{request_ref, Request};
162 ///
163 /// #[derive(Debug)]
164 /// enum MyLittleTeaPot {
165 /// Empty,
166 /// }
167 ///
168 /// #[derive(Debug)]
169 /// struct MyBacktrace {
170 /// // ...
171 /// }
172 ///
173 /// impl MyBacktrace {
174 /// fn new() -> MyBacktrace {
175 /// // ...
176 /// # MyBacktrace {}
177 /// }
178 /// }
179 ///
180 /// #[derive(Debug)]
181 /// struct Error {
182 /// backtrace: MyBacktrace,
183 /// }
184 ///
185 /// impl fmt::Display for Error {
186 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
187 /// write!(f, "Example Error")
188 /// }
189 /// }
190 ///
191 /// impl std::error::Error for Error {
192 /// fn provide<'a>(&'a self, request: &mut Request<'a>) {
193 /// request
194 /// .provide_ref::<MyBacktrace>(&self.backtrace);
195 /// }
196 /// }
197 ///
198 /// fn main() {
199 /// let backtrace = MyBacktrace::new();
200 /// let error = Error { backtrace };
201 /// let dyn_error = &error as &dyn std::error::Error;
202 /// let backtrace_ref = request_ref::<MyBacktrace>(dyn_error).unwrap();
203 ///
204 /// assert!(core::ptr::eq(&error.backtrace, backtrace_ref));
205 /// assert!(request_ref::<MyLittleTeaPot>(dyn_error).is_none());
206 /// }
207 /// ```
208 ///
209 /// # Delegating Impls
210 ///
211 /// <div class="warning">
212 ///
213 /// **Warning**: We recommend implementors avoid delegating implementations of `provide` to
214 /// source error implementations.
215 ///
216 /// </div>
217 ///
218 /// This method should expose context from the current piece of the source chain only, not from
219 /// sources that are exposed in the chain of sources. Delegating `provide` implementations cause
220 /// the same context to be provided by multiple errors in the chain of sources which can cause
221 /// unintended duplication of information in error reports or require heuristics to deduplicate.
222 ///
223 /// In other words, the following implementation pattern for `provide` is discouraged and should
224 /// not be used for [`Error`] types exposed in public APIs to third parties.
225 ///
226 /// ```rust
227 /// # #![feature(error_generic_member_access)]
228 /// # use core::fmt;
229 /// # use core::error::Request;
230 /// # #[derive(Debug)]
231 /// struct MyError {
232 /// source: Error,
233 /// }
234 /// # #[derive(Debug)]
235 /// # struct Error;
236 /// # impl fmt::Display for Error {
237 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
238 /// # write!(f, "Example Source Error")
239 /// # }
240 /// # }
241 /// # impl fmt::Display for MyError {
242 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
243 /// # write!(f, "Example Error")
244 /// # }
245 /// # }
246 /// # impl std::error::Error for Error { }
247 ///
248 /// impl std::error::Error for MyError {
249 /// fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
250 /// Some(&self.source)
251 /// }
252 ///
253 /// fn provide<'a>(&'a self, request: &mut Request<'a>) {
254 /// self.source.provide(request) // <--- Discouraged
255 /// }
256 /// }
257 /// ```
258 #[unstable(feature = "error_generic_member_access", issue = "99301")]
259 #[allow(unused_variables)]
260 fn provide<'a>(&'a self, request: &mut Request<'a>) {}
261}
262
263mod private {
264 // This is a hack to prevent `type_id` from being overridden by `Error`
265 // implementations, since that can enable unsound downcasting.
266 #[unstable(feature = "error_type_id", issue = "60784")]
267 #[derive(Debug)]
268 pub struct Internal;
269}
270
271#[stable(feature = "never_type", since = "1.100.0")]
272impl Error for ! {}
273
274#[unstable(feature = "error_type_id_internal", issue = "none")]
275#[doc(hidden)]
276pub fn error_type_id<E: ?Sized + Error + 'static>(err: &E) -> TypeId {
277 E::type_id(err, private::Internal)
278}
279
280// Copied from `any.rs`.
281impl dyn Error + 'static {
282 /// Returns `true` if the inner type is the same as `T`.
283 #[stable(feature = "error_downcast", since = "1.3.0")]
284 #[inline]
285 pub fn is<T: Error + 'static>(&self) -> bool {
286 // Get `TypeId` of the type this function is instantiated with.
287 let t = TypeId::of::<T>();
288
289 // Get `TypeId` of the type in the trait object (`self`).
290 let concrete = error_type_id::<Self>(self);
291
292 // Compare both `TypeId`s on equality.
293 t == concrete
294 }
295
296 /// Returns some reference to the inner value if it is of type `T`, or
297 /// `None` if it isn't.
298 #[stable(feature = "error_downcast", since = "1.3.0")]
299 #[inline]
300 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
301 if self.is::<T>() {
302 // SAFETY: `is` ensures this type cast is correct
303 unsafe { Some(&*(self as *const dyn Error as *const T)) }
304 } else {
305 None
306 }
307 }
308
309 /// Returns some mutable reference to the inner value if it is of type `T`, or
310 /// `None` if it isn't.
311 #[stable(feature = "error_downcast", since = "1.3.0")]
312 #[inline]
313 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
314 if self.is::<T>() {
315 // SAFETY: `is` ensures this type cast is correct
316 unsafe { Some(&mut *(self as *mut dyn Error as *mut T)) }
317 } else {
318 None
319 }
320 }
321}
322
323impl dyn Error + 'static + Send {
324 /// Forwards to the method defined on the type `dyn Error`.
325 #[stable(feature = "error_downcast", since = "1.3.0")]
326 #[inline]
327 pub fn is<T: Error + 'static>(&self) -> bool {
328 <dyn Error + 'static>::is::<T>(self)
329 }
330
331 /// Forwards to the method defined on the type `dyn Error`.
332 #[stable(feature = "error_downcast", since = "1.3.0")]
333 #[inline]
334 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
335 <dyn Error + 'static>::downcast_ref::<T>(self)
336 }
337
338 /// Forwards to the method defined on the type `dyn Error`.
339 #[stable(feature = "error_downcast", since = "1.3.0")]
340 #[inline]
341 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
342 <dyn Error + 'static>::downcast_mut::<T>(self)
343 }
344}
345
346impl dyn Error + 'static + Send + Sync {
347 /// Forwards to the method defined on the type `dyn Error`.
348 #[stable(feature = "error_downcast", since = "1.3.0")]
349 #[inline]
350 pub fn is<T: Error + 'static>(&self) -> bool {
351 <dyn Error + 'static>::is::<T>(self)
352 }
353
354 /// Forwards to the method defined on the type `dyn Error`.
355 #[stable(feature = "error_downcast", since = "1.3.0")]
356 #[inline]
357 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
358 <dyn Error + 'static>::downcast_ref::<T>(self)
359 }
360
361 /// Forwards to the method defined on the type `dyn Error`.
362 #[stable(feature = "error_downcast", since = "1.3.0")]
363 #[inline]
364 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
365 <dyn Error + 'static>::downcast_mut::<T>(self)
366 }
367}
368
369impl dyn Error {
370 /// Returns an iterator starting with the current error and continuing with
371 /// recursively calling [`Error::source`].
372 ///
373 /// If you want to omit the current error and only use its sources,
374 /// use `skip(1)`.
375 ///
376 /// # Examples
377 ///
378 /// ```
379 /// #![feature(error_iter)]
380 /// use std::error::Error;
381 /// use std::fmt;
382 ///
383 /// #[derive(Debug)]
384 /// struct A;
385 ///
386 /// #[derive(Debug)]
387 /// struct B(Option<Box<dyn Error + 'static>>);
388 ///
389 /// impl fmt::Display for A {
390 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
391 /// write!(f, "A")
392 /// }
393 /// }
394 ///
395 /// impl fmt::Display for B {
396 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
397 /// write!(f, "B")
398 /// }
399 /// }
400 ///
401 /// impl Error for A {}
402 ///
403 /// impl Error for B {
404 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
405 /// self.0.as_ref().map(|e| e.as_ref())
406 /// }
407 /// }
408 ///
409 /// let b = B(Some(Box::new(A)));
410 ///
411 /// // let err : Box<Error> = b.into(); // or
412 /// let err = &b as &dyn Error;
413 ///
414 /// let mut iter = err.sources();
415 ///
416 /// assert_eq!("B".to_string(), iter.next().unwrap().to_string());
417 /// assert_eq!("A".to_string(), iter.next().unwrap().to_string());
418 /// assert!(iter.next().is_none());
419 /// assert!(iter.next().is_none());
420 /// ```
421 #[unstable(feature = "error_iter", issue = "58520")]
422 #[inline]
423 pub fn sources(&self) -> Source<'_> {
424 // You may think this method would be better in the `Error` trait, and you'd be right.
425 // Unfortunately that doesn't work, not because of the dyn-incompatibility rules but
426 // because we save a reference to `self` in `Source`s below as a trait object.
427 // If this method was declared in `Error`, then `self` would have the type `&T` where
428 // `T` is some concrete type which implements `Error`. We would need to coerce `self`
429 // to have type `&dyn Error`, but that requires that `Self` has a known size
430 // (i.e., `Self: Sized`). We can't put that bound on `Error` since that would forbid
431 // `Error` trait objects, and we can't put that bound on the method because that means
432 // the method can't be called on trait objects (we'd also need the `'static` bound,
433 // but that isn't allowed because methods with bounds on `Self` other than `Sized` are
434 // dyn-incompatible). Requiring an `Unsize` bound is not backwards compatible.
435
436 Source { current: Some(self) }
437 }
438}
439
440/// Requests a value of type `T` from the given `impl Error`.
441///
442/// # Examples
443///
444/// Get a string value from an error.
445///
446/// ```rust
447/// #![feature(error_generic_member_access)]
448/// use std::error::Error;
449/// use core::error::request_value;
450///
451/// fn get_string(err: &impl Error) -> String {
452/// request_value::<String>(err).unwrap()
453/// }
454/// ```
455#[unstable(feature = "error_generic_member_access", issue = "99301")]
456pub fn request_value<'a, T>(err: &'a (impl Error + ?Sized)) -> Option<T>
457where
458 T: 'static,
459{
460 request_by_type_tag::<'a, tags::Value<T>>(err)
461}
462
463/// Requests a reference of type `T` from the given `impl Error`.
464///
465/// # Examples
466///
467/// Get a string reference from an error.
468///
469/// ```rust
470/// #![feature(error_generic_member_access)]
471/// use core::error::Error;
472/// use core::error::request_ref;
473///
474/// fn get_str(err: &impl Error) -> &str {
475/// request_ref::<str>(err).unwrap()
476/// }
477/// ```
478#[unstable(feature = "error_generic_member_access", issue = "99301")]
479pub fn request_ref<'a, T>(err: &'a (impl Error + ?Sized)) -> Option<&'a T>
480where
481 T: 'static + ?Sized,
482{
483 request_by_type_tag::<'a, tags::Ref<tags::MaybeSizedValue<T>>>(err)
484}
485
486/// Request a specific value by tag from the `Error`.
487fn request_by_type_tag<'a, I>(err: &'a (impl Error + ?Sized)) -> Option<I::Reified>
488where
489 I: tags::Type<'a>,
490{
491 let mut tagged = Tagged { tag_id: TypeId::of::<I>(), value: TaggedOption::<'a, I>(None) };
492 err.provide(tagged.as_request());
493 tagged.value.0
494}
495
496///////////////////////////////////////////////////////////////////////////////
497// Request and its methods
498///////////////////////////////////////////////////////////////////////////////
499
500/// `Request` supports generic, type-driven access to data. Its use is currently restricted to the
501/// standard library in cases where trait authors wish to allow trait implementors to share generic
502/// information across trait boundaries. The motivating and prototypical use case is
503/// `core::error::Error` which would otherwise require a method per concrete type (e.g.
504/// `std::backtrace::Backtrace` instance that implementors want to expose to users).
505///
506/// # Data flow
507///
508/// To describe the intended data flow for Request objects, let's consider two conceptual users
509/// separated by API boundaries:
510///
511/// * Consumer - the consumer requests objects using a Request instance; e.g. a crate that offers
512/// fancy `Error`/`Result` reporting to users wants to request a Backtrace from a given `dyn Error`.
513///
514/// * Producer - the producer provides objects when requested via Request; e.g. a library with an
515/// an `Error` implementation that automatically captures backtraces at the time instances are
516/// created.
517///
518/// The consumer only needs to know where to submit their request and is expected to handle the
519/// request not being fulfilled by the use of `Option<T>` in the responses offered by the producer.
520///
521/// * A Producer initializes the value of one of its fields of a specific type. (or is otherwise
522/// prepared to generate a value requested). e.g., `backtrace::Backtrace` or
523/// `std::backtrace::Backtrace`.
524/// * A Consumer requests an object of a specific type (say `std::backtrace::Backtrace`). In the
525/// case of a `dyn Error` trait object (the Producer), there are functions called `request_ref` and
526/// `request_value` to simplify obtaining an `Option<T>` for a given type.
527/// * The Producer, when requested, populates the given Request object which is given as a mutable
528/// reference.
529/// * The Consumer extracts a value or reference to the requested type from the `Request` object
530/// wrapped in an `Option<T>`; in the case of `dyn Error` the aforementioned `request_ref` and
531/// `request_value` methods mean that `dyn Error` users don't have to deal with the `Request` type at
532/// all (but `Error` implementors do). The `None` case of the `Option` suggests only that the
533/// Producer cannot currently offer an instance of the requested type, not that it can't or never will.
534///
535/// # Examples
536///
537/// The best way to demonstrate this is using an example implementation of `Error`'s `provide` trait
538/// method:
539///
540/// ```
541/// #![feature(error_generic_member_access)]
542/// use core::fmt;
543/// use core::error::Request;
544/// use core::error::request_ref;
545///
546/// #[derive(Debug)]
547/// enum MyLittleTeaPot {
548/// Empty,
549/// }
550///
551/// #[derive(Debug)]
552/// struct MyBacktrace {
553/// // ...
554/// }
555///
556/// impl MyBacktrace {
557/// fn new() -> MyBacktrace {
558/// // ...
559/// # MyBacktrace {}
560/// }
561/// }
562///
563/// #[derive(Debug)]
564/// struct Error {
565/// backtrace: MyBacktrace,
566/// }
567///
568/// impl fmt::Display for Error {
569/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
570/// write!(f, "Example Error")
571/// }
572/// }
573///
574/// impl std::error::Error for Error {
575/// fn provide<'a>(&'a self, request: &mut Request<'a>) {
576/// request
577/// .provide_ref::<MyBacktrace>(&self.backtrace);
578/// }
579/// }
580///
581/// fn main() {
582/// let backtrace = MyBacktrace::new();
583/// let error = Error { backtrace };
584/// let dyn_error = &error as &dyn std::error::Error;
585/// let backtrace_ref = request_ref::<MyBacktrace>(dyn_error).unwrap();
586///
587/// assert!(core::ptr::eq(&error.backtrace, backtrace_ref));
588/// assert!(request_ref::<MyLittleTeaPot>(dyn_error).is_none());
589/// }
590/// ```
591///
592#[unstable(feature = "error_generic_member_access", issue = "99301")]
593#[repr(transparent)]
594pub struct Request<'a>(Tagged<dyn Erased<'a> + 'a>);
595
596impl<'a> Request<'a> {
597 /// Provides a value or other type with only static lifetimes.
598 ///
599 /// # Examples
600 ///
601 /// Provides an `u8`.
602 ///
603 /// ```rust
604 /// #![feature(error_generic_member_access)]
605 ///
606 /// use core::error::Request;
607 ///
608 /// #[derive(Debug)]
609 /// struct SomeConcreteType { field: u8 }
610 ///
611 /// impl std::fmt::Display for SomeConcreteType {
612 /// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
613 /// write!(f, "{} failed", self.field)
614 /// }
615 /// }
616 ///
617 /// impl std::error::Error for SomeConcreteType {
618 /// fn provide<'a>(&'a self, request: &mut Request<'a>) {
619 /// request.provide_value::<u8>(self.field);
620 /// }
621 /// }
622 /// ```
623 #[unstable(feature = "error_generic_member_access", issue = "99301")]
624 pub fn provide_value<T>(&mut self, value: T) -> &mut Self
625 where
626 T: 'static,
627 {
628 self.provide::<tags::Value<T>>(value)
629 }
630
631 /// Provides a value or other type with only static lifetimes computed using a closure.
632 ///
633 /// # Examples
634 ///
635 /// Provides a `String` by cloning.
636 ///
637 /// ```rust
638 /// #![feature(error_generic_member_access)]
639 ///
640 /// use core::error::Request;
641 ///
642 /// #[derive(Debug)]
643 /// struct SomeConcreteType { field: String }
644 ///
645 /// impl std::fmt::Display for SomeConcreteType {
646 /// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
647 /// write!(f, "{} failed", self.field)
648 /// }
649 /// }
650 ///
651 /// impl std::error::Error for SomeConcreteType {
652 /// fn provide<'a>(&'a self, request: &mut Request<'a>) {
653 /// request.provide_value_with::<String>(|| self.field.clone());
654 /// }
655 /// }
656 /// ```
657 #[unstable(feature = "error_generic_member_access", issue = "99301")]
658 pub fn provide_value_with<T>(&mut self, fulfil: impl FnOnce() -> T) -> &mut Self
659 where
660 T: 'static,
661 {
662 self.provide_with::<tags::Value<T>>(fulfil)
663 }
664
665 /// Provides a reference. The referee type must be bounded by `'static`,
666 /// but may be unsized.
667 ///
668 /// # Examples
669 ///
670 /// Provides a reference to a field as a `&str`.
671 ///
672 /// ```rust
673 /// #![feature(error_generic_member_access)]
674 ///
675 /// use core::error::Request;
676 ///
677 /// #[derive(Debug)]
678 /// struct SomeConcreteType { field: String }
679 ///
680 /// impl std::fmt::Display for SomeConcreteType {
681 /// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
682 /// write!(f, "{} failed", self.field)
683 /// }
684 /// }
685 ///
686 /// impl std::error::Error for SomeConcreteType {
687 /// fn provide<'a>(&'a self, request: &mut Request<'a>) {
688 /// request.provide_ref::<str>(&self.field);
689 /// }
690 /// }
691 /// ```
692 #[unstable(feature = "error_generic_member_access", issue = "99301")]
693 pub fn provide_ref<T: ?Sized + 'static>(&mut self, value: &'a T) -> &mut Self {
694 self.provide::<tags::Ref<tags::MaybeSizedValue<T>>>(value)
695 }
696
697 /// Provides a reference computed using a closure. The referee type
698 /// must be bounded by `'static`, but may be unsized.
699 ///
700 /// # Examples
701 ///
702 /// Provides a reference to a field as a `&str`.
703 ///
704 /// ```rust
705 /// #![feature(error_generic_member_access)]
706 ///
707 /// use core::error::Request;
708 ///
709 /// #[derive(Debug)]
710 /// struct SomeConcreteType { business: String, party: String }
711 /// fn today_is_a_weekday() -> bool { true }
712 ///
713 /// impl std::fmt::Display for SomeConcreteType {
714 /// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
715 /// write!(f, "{} failed", self.business)
716 /// }
717 /// }
718 ///
719 /// impl std::error::Error for SomeConcreteType {
720 /// fn provide<'a>(&'a self, request: &mut Request<'a>) {
721 /// request.provide_ref_with::<str>(|| {
722 /// if today_is_a_weekday() {
723 /// &self.business
724 /// } else {
725 /// &self.party
726 /// }
727 /// });
728 /// }
729 /// }
730 /// ```
731 #[unstable(feature = "error_generic_member_access", issue = "99301")]
732 pub fn provide_ref_with<T: ?Sized + 'static>(
733 &mut self,
734 fulfil: impl FnOnce() -> &'a T,
735 ) -> &mut Self {
736 self.provide_with::<tags::Ref<tags::MaybeSizedValue<T>>>(fulfil)
737 }
738
739 /// Provides a value with the given `Type` tag.
740 fn provide<I>(&mut self, value: I::Reified) -> &mut Self
741 where
742 I: tags::Type<'a>,
743 {
744 if let Some(res @ TaggedOption(None)) = self.0.downcast_mut::<I>() {
745 res.0 = Some(value);
746 }
747 self
748 }
749
750 /// Provides a value with the given `Type` tag, using a closure to prevent unnecessary work.
751 fn provide_with<I>(&mut self, fulfil: impl FnOnce() -> I::Reified) -> &mut Self
752 where
753 I: tags::Type<'a>,
754 {
755 if let Some(res @ TaggedOption(None)) = self.0.downcast_mut::<I>() {
756 res.0 = Some(fulfil());
757 }
758 self
759 }
760
761 /// Checks if the `Request` would be satisfied if provided with a
762 /// value of the specified type. If the type does not match or has
763 /// already been provided, returns false.
764 ///
765 /// # Examples
766 ///
767 /// Checks if a `u8` still needs to be provided and then provides
768 /// it.
769 ///
770 /// ```rust
771 /// #![feature(error_generic_member_access)]
772 ///
773 /// use core::error::Request;
774 /// use core::error::request_value;
775 ///
776 /// #[derive(Debug)]
777 /// struct Parent(Option<u8>);
778 ///
779 /// impl std::fmt::Display for Parent {
780 /// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
781 /// write!(f, "a parent failed")
782 /// }
783 /// }
784 ///
785 /// impl std::error::Error for Parent {
786 /// fn provide<'a>(&'a self, request: &mut Request<'a>) {
787 /// if let Some(v) = self.0 {
788 /// request.provide_value::<u8>(v);
789 /// }
790 /// }
791 /// }
792 ///
793 /// #[derive(Debug)]
794 /// struct Child {
795 /// parent: Parent,
796 /// }
797 ///
798 /// impl Child {
799 /// // Pretend that this takes a lot of resources to evaluate.
800 /// fn an_expensive_computation(&self) -> Option<u8> {
801 /// Some(99)
802 /// }
803 /// }
804 ///
805 /// impl std::fmt::Display for Child {
806 /// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
807 /// write!(f, "child failed: \n because of parent: {}", self.parent)
808 /// }
809 /// }
810 ///
811 /// impl std::error::Error for Child {
812 /// fn provide<'a>(&'a self, request: &mut Request<'a>) {
813 /// // In general, we don't know if this call will provide
814 /// // an `u8` value or not...
815 /// self.parent.provide(request);
816 ///
817 /// // ...so we check to see if the `u8` is needed before
818 /// // we run our expensive computation.
819 /// if request.would_be_satisfied_by_value_of::<u8>() {
820 /// if let Some(v) = self.an_expensive_computation() {
821 /// request.provide_value::<u8>(v);
822 /// }
823 /// }
824 ///
825 /// // The request will be satisfied now, regardless of if
826 /// // the parent provided the value or we did.
827 /// assert!(!request.would_be_satisfied_by_value_of::<u8>());
828 /// }
829 /// }
830 ///
831 /// let parent = Parent(Some(42));
832 /// let child = Child { parent };
833 /// assert_eq!(Some(42), request_value::<u8>(&child));
834 ///
835 /// let parent = Parent(None);
836 /// let child = Child { parent };
837 /// assert_eq!(Some(99), request_value::<u8>(&child));
838 ///
839 /// ```
840 #[unstable(feature = "error_generic_member_access", issue = "99301")]
841 pub fn would_be_satisfied_by_value_of<T>(&self) -> bool
842 where
843 T: 'static,
844 {
845 self.would_be_satisfied_by::<tags::Value<T>>()
846 }
847
848 /// Checks if the `Request` would be satisfied if provided with a
849 /// reference to a value of the specified type.
850 ///
851 /// If the type does not match or has already been provided, returns false.
852 ///
853 /// # Examples
854 ///
855 /// Checks if a `&str` still needs to be provided and then provides
856 /// it.
857 ///
858 /// ```rust
859 /// #![feature(error_generic_member_access)]
860 ///
861 /// use core::error::Request;
862 /// use core::error::request_ref;
863 ///
864 /// #[derive(Debug)]
865 /// struct Parent(Option<String>);
866 ///
867 /// impl std::fmt::Display for Parent {
868 /// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
869 /// write!(f, "a parent failed")
870 /// }
871 /// }
872 ///
873 /// impl std::error::Error for Parent {
874 /// fn provide<'a>(&'a self, request: &mut Request<'a>) {
875 /// if let Some(v) = &self.0 {
876 /// request.provide_ref::<str>(v);
877 /// }
878 /// }
879 /// }
880 ///
881 /// #[derive(Debug)]
882 /// struct Child {
883 /// parent: Parent,
884 /// name: String,
885 /// }
886 ///
887 /// impl Child {
888 /// // Pretend that this takes a lot of resources to evaluate.
889 /// fn an_expensive_computation(&self) -> Option<&str> {
890 /// Some(&self.name)
891 /// }
892 /// }
893 ///
894 /// impl std::fmt::Display for Child {
895 /// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
896 /// write!(f, "{} failed: \n {}", self.name, self.parent)
897 /// }
898 /// }
899 ///
900 /// impl std::error::Error for Child {
901 /// fn provide<'a>(&'a self, request: &mut Request<'a>) {
902 /// // In general, we don't know if this call will provide
903 /// // a `str` reference or not...
904 /// self.parent.provide(request);
905 ///
906 /// // ...so we check to see if the `&str` is needed before
907 /// // we run our expensive computation.
908 /// if request.would_be_satisfied_by_ref_of::<str>() {
909 /// if let Some(v) = self.an_expensive_computation() {
910 /// request.provide_ref::<str>(v);
911 /// }
912 /// }
913 ///
914 /// // The request will be satisfied now, regardless of if
915 /// // the parent provided the reference or we did.
916 /// assert!(!request.would_be_satisfied_by_ref_of::<str>());
917 /// }
918 /// }
919 ///
920 /// let parent = Parent(Some("parent".into()));
921 /// let child = Child { parent, name: "child".into() };
922 /// assert_eq!(Some("parent"), request_ref::<str>(&child));
923 ///
924 /// let parent = Parent(None);
925 /// let child = Child { parent, name: "child".into() };
926 /// assert_eq!(Some("child"), request_ref::<str>(&child));
927 /// ```
928 #[unstable(feature = "error_generic_member_access", issue = "99301")]
929 pub fn would_be_satisfied_by_ref_of<T>(&self) -> bool
930 where
931 T: ?Sized + 'static,
932 {
933 self.would_be_satisfied_by::<tags::Ref<tags::MaybeSizedValue<T>>>()
934 }
935
936 fn would_be_satisfied_by<I>(&self) -> bool
937 where
938 I: tags::Type<'a>,
939 {
940 matches!(self.0.downcast::<I>(), Some(TaggedOption(None)))
941 }
942}
943
944#[unstable(feature = "error_generic_member_access", issue = "99301")]
945impl<'a> Debug for Request<'a> {
946 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
947 f.debug_struct("Request").finish_non_exhaustive()
948 }
949}
950
951///////////////////////////////////////////////////////////////////////////////
952// Type tags
953///////////////////////////////////////////////////////////////////////////////
954
955pub(crate) mod tags {
956 //! Type tags are used to identify a type using a separate value. This module includes type tags
957 //! for some very common types.
958 //!
959 //! Currently type tags are not exposed to the user. But in the future, if you want to use the
960 //! Request API with more complex types (typically those including lifetime parameters), you
961 //! will need to write your own tags.
962
963 use crate::marker::PhantomData;
964
965 /// This trait is implemented by specific tag types in order to allow
966 /// describing a type which can be requested for a given lifetime `'a`.
967 ///
968 /// A few example implementations for type-driven tags can be found in this
969 /// module, although crates may also implement their own tags for more
970 /// complex types with internal lifetimes.
971 pub(crate) trait Type<'a>: Sized + 'static {
972 /// The type of values which may be tagged by this tag for the given
973 /// lifetime.
974 type Reified: 'a;
975 }
976
977 /// Similar to the [`Type`] trait, but represents a type which may be unsized (i.e., has a
978 /// `?Sized` bound). E.g., `str`.
979 pub(crate) trait MaybeSizedType<'a>: Sized + 'static {
980 type Reified: 'a + ?Sized;
981 }
982
983 impl<'a, T: Type<'a>> MaybeSizedType<'a> for T {
984 type Reified = T::Reified;
985 }
986
987 /// Type-based tag for types bounded by `'static`, i.e., with no borrowed elements.
988 #[derive(Debug)]
989 pub(crate) struct Value<T: 'static>(PhantomData<T>);
990
991 impl<'a, T: 'static> Type<'a> for Value<T> {
992 type Reified = T;
993 }
994
995 /// Type-based tag similar to [`Value`] but which may be unsized (i.e., has a `?Sized` bound).
996 #[derive(Debug)]
997 pub(crate) struct MaybeSizedValue<T: ?Sized + 'static>(PhantomData<T>);
998
999 impl<'a, T: ?Sized + 'static> MaybeSizedType<'a> for MaybeSizedValue<T> {
1000 type Reified = T;
1001 }
1002
1003 /// Type-based tag for reference types (`&'a T`, where T is represented by
1004 /// `<I as MaybeSizedType<'a>>::Reified`.
1005 #[derive(Debug)]
1006 pub(crate) struct Ref<I>(PhantomData<I>);
1007
1008 impl<'a, I: MaybeSizedType<'a>> Type<'a> for Ref<I> {
1009 type Reified = &'a I::Reified;
1010 }
1011}
1012
1013/// An `Option` with a type tag `I`.
1014///
1015/// Since this struct implements `Erased`, the type can be erased to make a dynamically typed
1016/// option. The type can be checked dynamically using `Tagged::tag_id` and since this is statically
1017/// checked for the concrete type, there is some degree of type safety.
1018#[repr(transparent)]
1019pub(crate) struct TaggedOption<'a, I: tags::Type<'a>>(pub Option<I::Reified>);
1020
1021impl<'a, I: tags::Type<'a>> Tagged<TaggedOption<'a, I>> {
1022 pub(crate) fn as_request(&mut self) -> &mut Request<'a> {
1023 let erased = self as &mut Tagged<dyn Erased<'a> + 'a>;
1024 // SAFETY: transmuting `&mut Tagged<dyn Erased<'a> + 'a>` to `&mut Request<'a>` is safe since
1025 // `Request` is repr(transparent).
1026 unsafe { &mut *(erased as *mut Tagged<dyn Erased<'a>> as *mut Request<'a>) }
1027 }
1028}
1029
1030/// Represents a type-erased but identifiable object.
1031///
1032/// This trait is exclusively implemented by the `TaggedOption` type.
1033unsafe trait Erased<'a>: 'a {}
1034
1035unsafe impl<'a, I: tags::Type<'a>> Erased<'a> for TaggedOption<'a, I> {}
1036
1037struct Tagged<E: ?Sized> {
1038 tag_id: TypeId,
1039 value: E,
1040}
1041
1042impl<'a> Tagged<dyn Erased<'a> + 'a> {
1043 /// Returns some reference to the dynamic value if it is tagged with `I`,
1044 /// or `None` otherwise.
1045 #[inline]
1046 fn downcast<I>(&self) -> Option<&TaggedOption<'a, I>>
1047 where
1048 I: tags::Type<'a>,
1049 {
1050 if self.tag_id == TypeId::of::<I>() {
1051 // SAFETY: Just checked whether we're pointing to an I.
1052 Some(&unsafe { &*(self as *const Self).cast::<Tagged<TaggedOption<'a, I>>>() }.value)
1053 } else {
1054 None
1055 }
1056 }
1057
1058 /// Returns some mutable reference to the dynamic value if it is tagged with `I`,
1059 /// or `None` otherwise.
1060 #[inline]
1061 fn downcast_mut<I>(&mut self) -> Option<&mut TaggedOption<'a, I>>
1062 where
1063 I: tags::Type<'a>,
1064 {
1065 if self.tag_id == TypeId::of::<I>() {
1066 Some(
1067 // SAFETY: Just checked whether we're pointing to an I.
1068 &mut unsafe { &mut *(self as *mut Self).cast::<Tagged<TaggedOption<'a, I>>>() }
1069 .value,
1070 )
1071 } else {
1072 None
1073 }
1074 }
1075}
1076
1077/// An iterator over an [`Error`] and its sources.
1078///
1079/// If you want to omit the initial error and only process
1080/// its sources, use `skip(1)`.
1081#[unstable(feature = "error_iter", issue = "58520")]
1082#[derive(Clone, Debug)]
1083pub struct Source<'a> {
1084 current: Option<&'a (dyn Error + 'static)>,
1085}
1086
1087#[unstable(feature = "error_iter", issue = "58520")]
1088impl<'a> Iterator for Source<'a> {
1089 type Item = &'a (dyn Error + 'static);
1090
1091 fn next(&mut self) -> Option<Self::Item> {
1092 let current = self.current;
1093 self.current = self.current.and_then(Error::source);
1094 current
1095 }
1096
1097 fn size_hint(&self) -> (usize, Option<usize>) {
1098 if self.current.is_some() { (1, None) } else { (0, Some(0)) }
1099 }
1100}
1101
1102#[unstable(feature = "error_iter", issue = "58520")]
1103impl<'a> crate::iter::FusedIterator for Source<'a> {}
1104
1105#[stable(feature = "error_by_ref", since = "1.51.0")]
1106impl<'a, T: Error + ?Sized> Error for &'a T {
1107 #[allow(deprecated)]
1108 fn cause(&self) -> Option<&dyn Error> {
1109 Error::cause(&**self)
1110 }
1111
1112 fn source(&self) -> Option<&(dyn Error + 'static)> {
1113 Error::source(&**self)
1114 }
1115
1116 fn provide<'b>(&'b self, request: &mut Request<'b>) {
1117 Error::provide(&**self, request);
1118 }
1119}
1120
1121#[stable(feature = "fmt_error", since = "1.11.0")]
1122impl Error for crate::fmt::Error {}
1123
1124#[stable(feature = "try_borrow", since = "1.13.0")]
1125impl Error for crate::cell::BorrowError {}
1126
1127#[stable(feature = "try_borrow", since = "1.13.0")]
1128impl Error for crate::cell::BorrowMutError {}
1129
1130#[stable(feature = "try_from", since = "1.34.0")]
1131impl Error for crate::char::CharTryFromError {}
1132
1133#[stable(feature = "duration_checked_float", since = "1.66.0")]
1134impl Error for crate::time::TryFromFloatSecsError {}
1135
1136#[stable(feature = "cstr_from_bytes_until_nul", since = "1.69.0")]
1137impl Error for crate::ffi::FromBytesUntilNulError {}
1138
1139#[stable(feature = "get_many_mut", since = "1.86.0")]
1140impl Error for crate::slice::GetDisjointMutError {}