summaryrefslogtreecommitdiffstats
path: root/library/std/src/error.rs
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-17 12:03:36 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-17 12:03:36 +0000
commit17d40c6057c88f4c432b0d7bac88e1b84cb7e67f (patch)
tree3f66c4a5918660bb8a758ab6cda5ff8ee4f6cdcd /library/std/src/error.rs
parentAdding upstream version 1.64.0+dfsg1. (diff)
downloadrustc-17d40c6057c88f4c432b0d7bac88e1b84cb7e67f.tar.xz
rustc-17d40c6057c88f4c432b0d7bac88e1b84cb7e67f.zip
Adding upstream version 1.65.0+dfsg1.upstream/1.65.0+dfsg1
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'library/std/src/error.rs')
-rw-r--r--library/std/src/error.rs379
1 files changed, 116 insertions, 263 deletions
diff --git a/library/std/src/error.rs b/library/std/src/error.rs
index 722df119d..e45059595 100644
--- a/library/std/src/error.rs
+++ b/library/std/src/error.rs
@@ -1,175 +1,51 @@
-//! Interfaces for working with Errors.
-//!
-//! # Error Handling In Rust
-//!
-//! The Rust language provides two complementary systems for constructing /
-//! representing, reporting, propagating, reacting to, and discarding errors.
-//! These responsibilities are collectively known as "error handling." The
-//! components of the first system, the panic runtime and interfaces, are most
-//! commonly used to represent bugs that have been detected in your program. The
-//! components of the second system, `Result`, the error traits, and user
-//! defined types, are used to represent anticipated runtime failure modes of
-//! your program.
-//!
-//! ## The Panic Interfaces
-//!
-//! The following are the primary interfaces of the panic system and the
-//! responsibilities they cover:
-//!
-//! * [`panic!`] and [`panic_any`] (Constructing, Propagated automatically)
-//! * [`PanicInfo`] (Reporting)
-//! * [`set_hook`], [`take_hook`], and [`#[panic_handler]`][panic-handler] (Reporting)
-//! * [`catch_unwind`] and [`resume_unwind`] (Discarding, Propagating)
-//!
-//! The following are the primary interfaces of the error system and the
-//! responsibilities they cover:
-//!
-//! * [`Result`] (Propagating, Reacting)
-//! * The [`Error`] trait (Reporting)
-//! * User defined types (Constructing / Representing)
-//! * [`match`] and [`downcast`] (Reacting)
-//! * The question mark operator ([`?`]) (Propagating)
-//! * The partially stable [`Try`] traits (Propagating, Constructing)
-//! * [`Termination`] (Reporting)
-//!
-//! ## Converting Errors into Panics
-//!
-//! The panic and error systems are not entirely distinct. Often times errors
-//! that are anticipated runtime failures in an API might instead represent bugs
-//! to a caller. For these situations the standard library provides APIs for
-//! constructing panics with an `Error` as it's source.
-//!
-//! * [`Result::unwrap`]
-//! * [`Result::expect`]
-//!
-//! These functions are equivalent, they either return the inner value if the
-//! `Result` is `Ok` or panic if the `Result` is `Err` printing the inner error
-//! as the source. The only difference between them is that with `expect` you
-//! provide a panic error message to be printed alongside the source, whereas
-//! `unwrap` has a default message indicating only that you unwraped an `Err`.
-//!
-//! Of the two, `expect` is generally preferred since its `msg` field allows you
-//! to convey your intent and assumptions which makes tracking down the source
-//! of a panic easier. `unwrap` on the other hand can still be a good fit in
-//! situations where you can trivially show that a piece of code will never
-//! panic, such as `"127.0.0.1".parse::<std::net::IpAddr>().unwrap()` or early
-//! prototyping.
-//!
-//! # Common Message Styles
-//!
-//! There are two common styles for how people word `expect` messages. Using
-//! the message to present information to users encountering a panic
-//! ("expect as error message") or using the message to present information
-//! to developers debugging the panic ("expect as precondition").
-//!
-//! In the former case the expect message is used to describe the error that
-//! has occurred which is considered a bug. Consider the following example:
-//!
-//! ```should_panic
-//! // Read environment variable, panic if it is not present
-//! let path = std::env::var("IMPORTANT_PATH").unwrap();
-//! ```
-//!
-//! In the "expect as error message" style we would use expect to describe
-//! that the environment variable was not set when it should have been:
-//!
-//! ```should_panic
-//! let path = std::env::var("IMPORTANT_PATH")
-//! .expect("env variable `IMPORTANT_PATH` is not set");
-//! ```
-//!
-//! In the "expect as precondition" style, we would instead describe the
-//! reason we _expect_ the `Result` should be `Ok`. With this style we would
-//! prefer to write:
-//!
-//! ```should_panic
-//! let path = std::env::var("IMPORTANT_PATH")
-//! .expect("env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`");
-//! ```
-//!
-//! The "expect as error message" style does not work as well with the
-//! default output of the std panic hooks, and often ends up repeating
-//! information that is already communicated by the source error being
-//! unwrapped:
-//!
-//! ```text
-//! thread 'main' panicked at 'env variable `IMPORTANT_PATH` is not set: NotPresent', src/main.rs:4:6
-//! ```
-//!
-//! In this example we end up mentioning that an env variable is not set,
-//! followed by our source message that says the env is not present, the
-//! only additional information we're communicating is the name of the
-//! environment variable being checked.
-//!
-//! The "expect as precondition" style instead focuses on source code
-//! readability, making it easier to understand what must have gone wrong in
-//! situations where panics are being used to represent bugs exclusively.
-//! Also, by framing our expect in terms of what "SHOULD" have happened to
-//! prevent the source error, we end up introducing new information that is
-//! independent from our source error.
-//!
-//! ```text
-//! thread 'main' panicked at 'env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`: NotPresent', src/main.rs:4:6
-//! ```
-//!
-//! In this example we are communicating not only the name of the
-//! environment variable that should have been set, but also an explanation
-//! for why it should have been set, and we let the source error display as
-//! a clear contradiction to our expectation.
-//!
-//! **Hint**: If you're having trouble remembering how to phrase
-//! expect-as-precondition style error messages remember to focus on the word
-//! "should" as in "env variable should be set by blah" or "the given binary
-//! should be available and executable by the current user".
-//!
-//! [`panic_any`]: crate::panic::panic_any
-//! [`PanicInfo`]: crate::panic::PanicInfo
-//! [`catch_unwind`]: crate::panic::catch_unwind
-//! [`resume_unwind`]: crate::panic::resume_unwind
-//! [`downcast`]: crate::error::Error
-//! [`Termination`]: crate::process::Termination
-//! [`Try`]: crate::ops::Try
-//! [panic hook]: crate::panic::set_hook
-//! [`set_hook`]: crate::panic::set_hook
-//! [`take_hook`]: crate::panic::take_hook
-//! [panic-handler]: <https://doc.rust-lang.org/nomicon/panic-handler.html>
-//! [`match`]: ../../std/keyword.match.html
-//! [`?`]: ../../std/result/index.html#the-question-mark-operator-
-
+#![doc = include_str!("../../core/src/error.md")]
#![stable(feature = "rust1", since = "1.0.0")]
-// A note about crates and the facade:
-//
-// Originally, the `Error` trait was defined in libcore, and the impls
-// were scattered about. However, coherence objected to this
-// arrangement, because to create the blanket impls for `Box` required
-// knowing that `&str: !Error`, and we have no means to deal with that
-// sort of conflict just now. Therefore, for the time being, we have
-// moved the `Error` trait into libstd. As we evolve a sol'n to the
-// coherence challenge (e.g., specialization, neg impls, etc) we can
-// reconsider what crate these items belong in.
-
#[cfg(test)]
mod tests;
+#[cfg(bootstrap)]
use core::array;
+#[cfg(bootstrap)]
use core::convert::Infallible;
+#[cfg(bootstrap)]
use crate::alloc::{AllocError, LayoutError};
-use crate::any::{Demand, Provider, TypeId};
+#[cfg(bootstrap)]
+use crate::any::Demand;
+#[cfg(bootstrap)]
+use crate::any::{Provider, TypeId};
use crate::backtrace::Backtrace;
+#[cfg(bootstrap)]
use crate::borrow::Cow;
+#[cfg(bootstrap)]
use crate::cell;
+#[cfg(bootstrap)]
use crate::char;
-use crate::fmt::{self, Debug, Display, Write};
+#[cfg(bootstrap)]
+use crate::fmt::Debug;
+#[cfg(bootstrap)]
+use crate::fmt::Display;
+use crate::fmt::{self, Write};
+#[cfg(bootstrap)]
use crate::io;
+#[cfg(bootstrap)]
use crate::mem::transmute;
+#[cfg(bootstrap)]
use crate::num;
+#[cfg(bootstrap)]
use crate::str;
+#[cfg(bootstrap)]
use crate::string;
+#[cfg(bootstrap)]
use crate::sync::Arc;
+#[cfg(bootstrap)]
use crate::time;
+#[cfg(not(bootstrap))]
+#[stable(feature = "rust1", since = "1.0.0")]
+pub use core::error::Error;
+
/// `Error` is a trait representing the basic expectations for error values,
/// i.e., values of type `E` in [`Result<T, E>`].
///
@@ -182,14 +58,15 @@ use crate::time;
/// assert_eq!(err.to_string(), "invalid digit found in string");
/// ```
///
-/// Errors may provide cause chain information. [`Error::source()`] is generally
+/// Errors may provide cause information. [`Error::source()`] is generally
/// used when errors cross "abstraction boundaries". If one module must report
/// an error that is caused by an error from a lower-level module, it can allow
/// accessing that error via [`Error::source()`]. This makes it possible for the
/// high-level module to provide its own errors while also revealing some of the
-/// implementation for debugging via `source` chains.
+/// implementation for debugging.
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg_attr(not(test), rustc_diagnostic_item = "Error")]
+#[cfg(bootstrap)]
pub trait Error: Debug + Display {
/// The lower-level source of this error, if any.
///
@@ -333,8 +210,8 @@ pub trait Error: Debug + Display {
/// }
///
/// impl std::error::Error for Error {
- /// fn provide<'a>(&'a self, req: &mut Demand<'a>) {
- /// req
+ /// fn provide<'a>(&'a self, demand: &mut Demand<'a>) {
+ /// demand
/// .provide_ref::<MyBacktrace>(&self.backtrace)
/// .provide_ref::<dyn std::error::Error + 'static>(&self.source);
/// }
@@ -352,13 +229,14 @@ pub trait Error: Debug + Display {
/// ```
#[unstable(feature = "error_generic_member_access", issue = "99301")]
#[allow(unused_variables)]
- fn provide<'a>(&'a self, req: &mut Demand<'a>) {}
+ fn provide<'a>(&'a self, demand: &mut Demand<'a>) {}
}
+#[cfg(bootstrap)]
#[unstable(feature = "error_generic_member_access", issue = "99301")]
impl<'b> Provider for dyn Error + 'b {
- fn provide<'a>(&'a self, req: &mut Demand<'a>) {
- self.provide(req)
+ fn provide<'a>(&'a self, demand: &mut Demand<'a>) {
+ self.provide(demand)
}
}
@@ -370,6 +248,7 @@ mod private {
pub struct Internal;
}
+#[cfg(bootstrap)]
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, E: Error + 'a> From<E> for Box<dyn Error + 'a> {
/// Converts a type of [`Error`] into a box of dyn [`Error`].
@@ -402,6 +281,7 @@ impl<'a, E: Error + 'a> From<E> for Box<dyn Error + 'a> {
}
}
+#[cfg(bootstrap)]
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<dyn Error + Send + Sync + 'a> {
/// Converts a type of [`Error`] + [`Send`] + [`Sync`] into a box of
@@ -440,6 +320,7 @@ impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<dyn Error + Send + Sync +
}
}
+#[cfg(bootstrap)]
#[stable(feature = "rust1", since = "1.0.0")]
impl From<String> for Box<dyn Error + Send + Sync> {
/// Converts a [`String`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
@@ -483,6 +364,7 @@ impl From<String> for Box<dyn Error + Send + Sync> {
}
}
+#[cfg(bootstrap)]
#[stable(feature = "string_box_error", since = "1.6.0")]
impl From<String> for Box<dyn Error> {
/// Converts a [`String`] into a box of dyn [`Error`].
@@ -504,6 +386,7 @@ impl From<String> for Box<dyn Error> {
}
}
+#[cfg(bootstrap)]
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a> {
/// Converts a [`str`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
@@ -527,6 +410,7 @@ impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a> {
}
}
+#[cfg(bootstrap)]
#[stable(feature = "string_box_error", since = "1.6.0")]
impl From<&str> for Box<dyn Error> {
/// Converts a [`str`] into a box of dyn [`Error`].
@@ -548,6 +432,7 @@ impl From<&str> for Box<dyn Error> {
}
}
+#[cfg(bootstrap)]
#[stable(feature = "cow_box_error", since = "1.22.0")]
impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a> {
/// Converts a [`Cow`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
@@ -569,6 +454,7 @@ impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a> {
}
}
+#[cfg(bootstrap)]
#[stable(feature = "cow_box_error", since = "1.22.0")]
impl<'a> From<Cow<'a, str>> for Box<dyn Error> {
/// Converts a [`Cow`] into a box of dyn [`Error`].
@@ -589,9 +475,11 @@ impl<'a> From<Cow<'a, str>> for Box<dyn Error> {
}
}
+#[cfg(bootstrap)]
#[unstable(feature = "never_type", issue = "35121")]
impl Error for ! {}
+#[cfg(bootstrap)]
#[unstable(
feature = "allocator_api",
reason = "the precise API and guarantees it provides may be tweaked.",
@@ -599,9 +487,11 @@ impl Error for ! {}
)]
impl Error for AllocError {}
+#[cfg(bootstrap)]
#[stable(feature = "alloc_layout", since = "1.28.0")]
impl Error for LayoutError {}
+#[cfg(bootstrap)]
#[stable(feature = "rust1", since = "1.0.0")]
impl Error for str::ParseBoolError {
#[allow(deprecated)]
@@ -610,6 +500,7 @@ impl Error for str::ParseBoolError {
}
}
+#[cfg(bootstrap)]
#[stable(feature = "rust1", since = "1.0.0")]
impl Error for str::Utf8Error {
#[allow(deprecated)]
@@ -618,6 +509,7 @@ impl Error for str::Utf8Error {
}
}
+#[cfg(bootstrap)]
#[stable(feature = "rust1", since = "1.0.0")]
impl Error for num::ParseIntError {
#[allow(deprecated)]
@@ -626,6 +518,7 @@ impl Error for num::ParseIntError {
}
}
+#[cfg(bootstrap)]
#[stable(feature = "try_from", since = "1.34.0")]
impl Error for num::TryFromIntError {
#[allow(deprecated)]
@@ -634,6 +527,7 @@ impl Error for num::TryFromIntError {
}
}
+#[cfg(bootstrap)]
#[stable(feature = "try_from", since = "1.34.0")]
impl Error for array::TryFromSliceError {
#[allow(deprecated)]
@@ -642,6 +536,7 @@ impl Error for array::TryFromSliceError {
}
}
+#[cfg(bootstrap)]
#[stable(feature = "rust1", since = "1.0.0")]
impl Error for num::ParseFloatError {
#[allow(deprecated)]
@@ -650,6 +545,7 @@ impl Error for num::ParseFloatError {
}
}
+#[cfg(bootstrap)]
#[stable(feature = "rust1", since = "1.0.0")]
impl Error for string::FromUtf8Error {
#[allow(deprecated)]
@@ -658,6 +554,7 @@ impl Error for string::FromUtf8Error {
}
}
+#[cfg(bootstrap)]
#[stable(feature = "rust1", since = "1.0.0")]
impl Error for string::FromUtf16Error {
#[allow(deprecated)]
@@ -666,6 +563,7 @@ impl Error for string::FromUtf16Error {
}
}
+#[cfg(bootstrap)]
#[stable(feature = "str_parse_error2", since = "1.8.0")]
impl Error for Infallible {
fn description(&self) -> &str {
@@ -673,6 +571,7 @@ impl Error for Infallible {
}
}
+#[cfg(bootstrap)]
#[stable(feature = "decode_utf16", since = "1.9.0")]
impl Error for char::DecodeUtf16Error {
#[allow(deprecated)]
@@ -681,9 +580,11 @@ impl Error for char::DecodeUtf16Error {
}
}
+#[cfg(bootstrap)]
#[stable(feature = "u8_from_char", since = "1.59.0")]
impl Error for char::TryFromCharError {}
+#[cfg(bootstrap)]
#[unstable(feature = "map_try_insert", issue = "82766")]
impl<'a, K: Debug + Ord, V: Debug> Error
for crate::collections::btree_map::OccupiedError<'a, K, V>
@@ -694,6 +595,7 @@ impl<'a, K: Debug + Ord, V: Debug> Error
}
}
+#[cfg(bootstrap)]
#[unstable(feature = "map_try_insert", issue = "82766")]
impl<'a, K: Debug, V: Debug> Error for crate::collections::hash_map::OccupiedError<'a, K, V> {
#[allow(deprecated)]
@@ -702,6 +604,7 @@ impl<'a, K: Debug, V: Debug> Error for crate::collections::hash_map::OccupiedErr
}
}
+#[cfg(bootstrap)]
#[stable(feature = "box_error", since = "1.8.0")]
impl<T: Error> Error for Box<T> {
#[allow(deprecated, deprecated_in_future)]
@@ -719,6 +622,7 @@ impl<T: Error> Error for Box<T> {
}
}
+#[cfg(bootstrap)]
#[unstable(feature = "thin_box", issue = "92791")]
impl<T: ?Sized + crate::error::Error> crate::error::Error for crate::boxed::ThinBox<T> {
fn source(&self) -> Option<&(dyn crate::error::Error + 'static)> {
@@ -727,6 +631,7 @@ impl<T: ?Sized + crate::error::Error> crate::error::Error for crate::boxed::Thin
}
}
+#[cfg(bootstrap)]
#[stable(feature = "error_by_ref", since = "1.51.0")]
impl<'a, T: Error + ?Sized> Error for &'a T {
#[allow(deprecated, deprecated_in_future)]
@@ -743,11 +648,12 @@ impl<'a, T: Error + ?Sized> Error for &'a T {
Error::source(&**self)
}
- fn provide<'b>(&'b self, req: &mut Demand<'b>) {
- Error::provide(&**self, req);
+ fn provide<'b>(&'b self, demand: &mut Demand<'b>) {
+ Error::provide(&**self, demand);
}
}
+#[cfg(bootstrap)]
#[stable(feature = "arc_error", since = "1.52.0")]
impl<T: Error + ?Sized> Error for Arc<T> {
#[allow(deprecated, deprecated_in_future)]
@@ -764,11 +670,12 @@ impl<T: Error + ?Sized> Error for Arc<T> {
Error::source(&**self)
}
- fn provide<'a>(&'a self, req: &mut Demand<'a>) {
- Error::provide(&**self, req);
+ fn provide<'a>(&'a self, demand: &mut Demand<'a>) {
+ Error::provide(&**self, demand);
}
}
+#[cfg(bootstrap)]
#[stable(feature = "fmt_error", since = "1.11.0")]
impl Error for fmt::Error {
#[allow(deprecated)]
@@ -777,6 +684,7 @@ impl Error for fmt::Error {
}
}
+#[cfg(bootstrap)]
#[stable(feature = "try_borrow", since = "1.13.0")]
impl Error for cell::BorrowError {
#[allow(deprecated)]
@@ -785,6 +693,7 @@ impl Error for cell::BorrowError {
}
}
+#[cfg(bootstrap)]
#[stable(feature = "try_borrow", since = "1.13.0")]
impl Error for cell::BorrowMutError {
#[allow(deprecated)]
@@ -793,6 +702,7 @@ impl Error for cell::BorrowMutError {
}
}
+#[cfg(bootstrap)]
#[stable(feature = "try_from", since = "1.34.0")]
impl Error for char::CharTryFromError {
#[allow(deprecated)]
@@ -801,6 +711,7 @@ impl Error for char::CharTryFromError {
}
}
+#[cfg(bootstrap)]
#[stable(feature = "char_from_str", since = "1.20.0")]
impl Error for char::ParseCharError {
#[allow(deprecated)]
@@ -809,12 +720,15 @@ impl Error for char::ParseCharError {
}
}
+#[cfg(bootstrap)]
#[stable(feature = "try_reserve", since = "1.57.0")]
impl Error for alloc::collections::TryReserveError {}
+#[cfg(bootstrap)]
#[unstable(feature = "duration_checked_float", issue = "83400")]
impl Error for time::FromFloatSecsError {}
+#[cfg(bootstrap)]
#[stable(feature = "rust1", since = "1.0.0")]
impl Error for alloc::ffi::NulError {
#[allow(deprecated)]
@@ -823,6 +737,7 @@ impl Error for alloc::ffi::NulError {
}
}
+#[cfg(bootstrap)]
#[stable(feature = "rust1", since = "1.0.0")]
impl From<alloc::ffi::NulError> for io::Error {
/// Converts a [`alloc::ffi::NulError`] into a [`io::Error`].
@@ -831,6 +746,7 @@ impl From<alloc::ffi::NulError> for io::Error {
}
}
+#[cfg(bootstrap)]
#[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
impl Error for core::ffi::FromBytesWithNulError {
#[allow(deprecated)]
@@ -839,12 +755,15 @@ impl Error for core::ffi::FromBytesWithNulError {
}
}
+#[cfg(bootstrap)]
#[unstable(feature = "cstr_from_bytes_until_nul", issue = "95027")]
impl Error for core::ffi::FromBytesUntilNulError {}
+#[cfg(bootstrap)]
#[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
impl Error for alloc::ffi::FromVecWithNulError {}
+#[cfg(bootstrap)]
#[stable(feature = "cstring_into", since = "1.7.0")]
impl Error for alloc::ffi::IntoStringError {
#[allow(deprecated)]
@@ -857,6 +776,7 @@ impl Error for alloc::ffi::IntoStringError {
}
}
+#[cfg(bootstrap)]
impl<'a> dyn Error + 'a {
/// Request a reference of type `T` as context about this error.
#[unstable(feature = "error_generic_member_access", issue = "99301")]
@@ -872,6 +792,7 @@ impl<'a> dyn Error + 'a {
}
// Copied from `any.rs`.
+#[cfg(bootstrap)]
impl dyn Error + 'static {
/// Returns `true` if the inner type is the same as `T`.
#[stable(feature = "error_downcast", since = "1.3.0")]
@@ -912,6 +833,7 @@ impl dyn Error + 'static {
}
}
+#[cfg(bootstrap)]
impl dyn Error + 'static + Send {
/// Forwards to the method defined on the type `dyn Error`.
#[stable(feature = "error_downcast", since = "1.3.0")]
@@ -947,6 +869,7 @@ impl dyn Error + 'static + Send {
}
}
+#[cfg(bootstrap)]
impl dyn Error + 'static + Send + Sync {
/// Forwards to the method defined on the type `dyn Error`.
#[stable(feature = "error_downcast", since = "1.3.0")]
@@ -982,6 +905,7 @@ impl dyn Error + 'static + Send + Sync {
}
}
+#[cfg(bootstrap)]
impl dyn Error {
#[inline]
#[stable(feature = "error_downcast", since = "1.3.0")]
@@ -1041,7 +965,7 @@ impl dyn Error {
/// // let err : Box<Error> = b.into(); // or
/// let err = &b as &(dyn Error);
///
- /// let mut iter = err.chain();
+ /// let mut iter = err.sources();
///
/// assert_eq!("B".to_string(), iter.next().unwrap().to_string());
/// assert_eq!("A".to_string(), iter.next().unwrap().to_string());
@@ -1050,8 +974,19 @@ impl dyn Error {
/// ```
#[unstable(feature = "error_iter", issue = "58520")]
#[inline]
- pub fn chain(&self) -> Chain<'_> {
- Chain { current: Some(self) }
+ pub fn sources(&self) -> Sources<'_> {
+ // You may think this method would be better in the Error trait, and you'd be right.
+ // Unfortunately that doesn't work, not because of the object safety rules but because we
+ // save a reference to self in Sources below as a trait object. If this method was
+ // declared in Error, then self would have the type &T where T is some concrete type which
+ // implements Error. We would need to coerce self to have type &dyn Error, but that requires
+ // that Self has a known size (i.e., Self: Sized). We can't put that bound on Error
+ // since that would forbid Error trait objects, and we can't put that bound on the method
+ // because that means the method can't be called on trait objects (we'd also need the
+ // 'static bound, but that isn't allowed because methods with bounds on Self other than
+ // Sized are not object-safe). Requiring an Unsize bound is not backwards compatible.
+
+ Sources { current: Some(self) }
}
}
@@ -1061,12 +996,14 @@ impl dyn Error {
/// its sources, use `skip(1)`.
#[unstable(feature = "error_iter", issue = "58520")]
#[derive(Clone, Debug)]
-pub struct Chain<'a> {
+#[cfg(bootstrap)]
+pub struct Sources<'a> {
current: Option<&'a (dyn Error + 'static)>,
}
+#[cfg(bootstrap)]
#[unstable(feature = "error_iter", issue = "58520")]
-impl<'a> Iterator for Chain<'a> {
+impl<'a> Iterator for Sources<'a> {
type Item = &'a (dyn Error + 'static);
fn next(&mut self) -> Option<Self::Item> {
@@ -1076,6 +1013,7 @@ impl<'a> Iterator for Chain<'a> {
}
}
+#[cfg(bootstrap)]
impl dyn Error + Send {
#[inline]
#[stable(feature = "error_downcast", since = "1.3.0")]
@@ -1089,6 +1027,7 @@ impl dyn Error + Send {
}
}
+#[cfg(bootstrap)]
impl dyn Error + Send + Sync {
#[inline]
#[stable(feature = "error_downcast", since = "1.3.0")]
@@ -1104,8 +1043,8 @@ impl dyn Error + Send + Sync {
/// An error reporter that prints an error and its sources.
///
-/// Report also exposes configuration options for formatting the error chain, either entirely on a
-/// single line, or in multi-line format with each cause in the error chain on a new line.
+/// Report also exposes configuration options for formatting the error sources, either entirely on a
+/// single line, or in multi-line format with each source on a new line.
///
/// `Report` only requires that the wrapped error implement `Error`. It doesn't require that the
/// wrapped error be `Send`, `Sync`, or `'static`.
@@ -1246,7 +1185,7 @@ impl dyn Error + Send + Sync {
/// # Err(SuperError { source: SuperErrorSideKick })
/// # }
///
-/// fn main() -> Result<(), Report> {
+/// fn main() -> Result<(), Report<SuperError>> {
/// get_super_error()?;
/// Ok(())
/// }
@@ -1293,7 +1232,7 @@ impl dyn Error + Send + Sync {
/// # Err(SuperError { source: SuperErrorSideKick })
/// # }
///
-/// fn main() -> Result<(), Report> {
+/// fn main() -> Result<(), Report<SuperError>> {
/// get_super_error()
/// .map_err(Report::from)
/// .map_err(|r| r.pretty(true).show_backtrace(true))?;
@@ -1450,11 +1389,10 @@ impl<E> Report<E> {
///
/// **Note**: Report will search for the first `Backtrace` it can find starting from the
/// outermost error. In this example it will display the backtrace from the second error in the
- /// chain, `SuperErrorSideKick`.
+ /// sources, `SuperErrorSideKick`.
///
/// ```rust
/// #![feature(error_reporter)]
- /// #![feature(backtrace)]
/// #![feature(provide_any)]
/// #![feature(error_generic_member_access)]
/// # use std::error::Error;
@@ -1489,9 +1427,8 @@ impl<E> Report<E> {
/// }
///
/// impl Error for SuperErrorSideKick {
- /// fn provide<'a>(&'a self, req: &mut Demand<'a>) {
- /// req
- /// .provide_ref::<Backtrace>(&self.backtrace);
+ /// fn provide<'a>(&'a self, demand: &mut Demand<'a>) {
+ /// demand.provide_ref::<Backtrace>(&self.backtrace);
/// }
/// }
///
@@ -1548,7 +1485,7 @@ where
let backtrace = backtrace.or_else(|| {
self.error
.source()
- .map(|source| source.chain().find_map(|source| source.request_ref()))
+ .map(|source| source.sources().find_map(|source| source.request_ref()))
.flatten()
});
backtrace
@@ -1559,7 +1496,7 @@ where
fn fmt_singleline(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.error)?;
- let sources = self.error.source().into_iter().flat_map(<dyn Error>::chain);
+ let sources = self.error.source().into_iter().flat_map(<dyn Error>::sources);
for cause in sources {
write!(f, ": {cause}")?;
@@ -1580,73 +1517,7 @@ where
let multiple = cause.source().is_some();
- for (ind, error) in cause.chain().enumerate() {
- writeln!(f)?;
- let mut indented = Indented { inner: f };
- if multiple {
- write!(indented, "{ind: >4}: {error}")?;
- } else {
- write!(indented, " {error}")?;
- }
- }
- }
-
- if self.show_backtrace {
- let backtrace = self.backtrace();
-
- if let Some(backtrace) = backtrace {
- let backtrace = backtrace.to_string();
-
- f.write_str("\n\nStack backtrace:\n")?;
- f.write_str(backtrace.trim_end())?;
- }
- }
-
- Ok(())
- }
-}
-
-impl Report<Box<dyn Error>> {
- fn backtrace(&self) -> Option<&Backtrace> {
- // have to grab the backtrace on the first error directly since that error may not be
- // 'static
- let backtrace = self.error.request_ref();
- let backtrace = backtrace.or_else(|| {
- self.error
- .source()
- .map(|source| source.chain().find_map(|source| source.request_ref()))
- .flatten()
- });
- backtrace
- }
-
- /// Format the report as a single line.
- #[unstable(feature = "error_reporter", issue = "90172")]
- fn fmt_singleline(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- write!(f, "{}", self.error)?;
-
- let sources = self.error.source().into_iter().flat_map(<dyn Error>::chain);
-
- for cause in sources {
- write!(f, ": {cause}")?;
- }
-
- Ok(())
- }
-
- /// Format the report as multiple lines, with each error cause on its own line.
- #[unstable(feature = "error_reporter", issue = "90172")]
- fn fmt_multiline(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- let error = &self.error;
-
- write!(f, "{error}")?;
-
- if let Some(cause) = error.source() {
- write!(f, "\n\nCaused by:")?;
-
- let multiple = cause.source().is_some();
-
- for (ind, error) in cause.chain().enumerate() {
+ for (ind, error) in cause.sources().enumerate() {
writeln!(f)?;
let mut indented = Indented { inner: f };
if multiple {
@@ -1683,17 +1554,6 @@ where
}
#[unstable(feature = "error_reporter", issue = "90172")]
-impl<'a, E> From<E> for Report<Box<dyn Error + 'a>>
-where
- E: Error + 'a,
-{
- fn from(error: E) -> Self {
- let error = box error;
- Report { error, show_backtrace: false, pretty: false }
- }
-}
-
-#[unstable(feature = "error_reporter", issue = "90172")]
impl<E> fmt::Display for Report<E>
where
E: Error,
@@ -1703,13 +1563,6 @@ where
}
}
-#[unstable(feature = "error_reporter", issue = "90172")]
-impl fmt::Display for Report<Box<dyn Error>> {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- if self.pretty { self.fmt_multiline(f) } else { self.fmt_singleline(f) }
- }
-}
-
// This type intentionally outputs the same format for `Display` and `Debug`for
// situations where you unwrap a `Report` or return it from main.
#[unstable(feature = "error_reporter", issue = "90172")]