Skip to content

Commit 5c710b5

Browse files
committed
Auto merge of #24793 - aturon:io-error-any, r=alexcrichton
This commit brings the `Error` trait in line with the [Error interoperation RFC](rust-lang/rfcs#201) by adding downcasting, which has long been intended. This change means that for any `Error` trait objects that are `'static`, you can downcast to concrete error types. To make this work, it is necessary for `Error` to inherit from `Reflect` (which is currently used to mark concrete types as "permitted for reflection, aka downcasting"). This is a breaking change: it means that impls like ```rust impl<T> Error for MyErrorType<T> { ... } ``` must change to ```rust impl<T: Reflect> Error for MyErrorType<T> { ... } ``` This commit furthermore marks `Reflect` as stable, since we are already essentially committed to it via `Any`. Note that in the future, if we determine that the parametricity aspects of `Reflect` are not needed, we can deprecate the trait and provide a blanket implementation for it for *all* types (rather than by using OIBIT), which would allow all mentions of `Reflect` to be dropped over time. So there is not a strong commitment here. [breaking-change] r? @alexcrichton
2 parents c634ec2 + a576262 commit 5c710b5

File tree

7 files changed

+146
-19
lines changed

7 files changed

+146
-19
lines changed

src/liballoc/boxed.rs

+8-3
Original file line numberDiff line numberDiff line change
@@ -240,6 +240,7 @@ impl<T: ?Sized + Hash> Hash for Box<T> {
240240
impl Box<Any> {
241241
#[inline]
242242
#[stable(feature = "rust1", since = "1.0.0")]
243+
/// Attempt to downcast the box to a concrete type.
243244
pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<Any>> {
244245
if self.is::<T>() {
245246
unsafe {
@@ -257,11 +258,15 @@ impl Box<Any> {
257258
}
258259
}
259260

260-
impl Box<Any+Send> {
261+
impl Box<Any + Send> {
261262
#[inline]
262263
#[stable(feature = "rust1", since = "1.0.0")]
263-
pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<Any>> {
264-
<Box<Any>>::downcast(self)
264+
/// Attempt to downcast the box to a concrete type.
265+
pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<Any + Send>> {
266+
<Box<Any>>::downcast(self).map_err(|s| unsafe {
267+
// reapply the Send marker
268+
mem::transmute::<Box<Any>, Box<Any + Send>>(s)
269+
})
265270
}
266271
}
267272

src/libcore/any.rs

+2-4
Original file line numberDiff line numberDiff line change
@@ -97,9 +97,7 @@ pub trait Any: Reflect + 'static {
9797
fn get_type_id(&self) -> TypeId;
9898
}
9999

100-
impl<T> Any for T
101-
where T: Reflect + 'static
102-
{
100+
impl<T: Reflect + 'static> Any for T {
103101
fn get_type_id(&self) -> TypeId { TypeId::of::<T>() }
104102
}
105103

@@ -222,7 +220,7 @@ impl TypeId {
222220
/// Returns the `TypeId` of the type this generic function has been
223221
/// instantiated with
224222
#[stable(feature = "rust1", since = "1.0.0")]
225-
pub fn of<T: ?Sized + Any>() -> TypeId {
223+
pub fn of<T: ?Sized + Reflect + 'static>() -> TypeId {
226224
TypeId {
227225
t: unsafe { intrinsics::type_id::<T>() },
228226
}

src/libcore/marker.rs

+2
Original file line numberDiff line numberDiff line change
@@ -416,6 +416,8 @@ mod impls {
416416
#[rustc_reflect_like]
417417
#[unstable(feature = "core", reason = "requires RFC and more experience")]
418418
#[allow(deprecated)]
419+
#[rustc_on_unimplemented = "`{Self}` does not implement `Any`; \
420+
ensure all type parameters are bounded by `Any`"]
419421
pub trait Reflect {}
420422

421423
impl Reflect for .. { }

src/libstd/error.rs

+125-5
Original file line numberDiff line numberDiff line change
@@ -47,19 +47,22 @@
4747
// coherence challenge (e.g., specialization, neg impls, etc) we can
4848
// reconsider what crate these items belong in.
4949

50-
use boxed::Box;
50+
use any::TypeId;
51+
use boxed::{self, Box};
5152
use convert::From;
5253
use fmt::{self, Debug, Display};
53-
use marker::{Send, Sync};
54+
use marker::{Send, Sync, Reflect};
55+
use mem::transmute;
5456
use num;
55-
use option::Option;
56-
use option::Option::None;
57+
use option::Option::{self, Some, None};
58+
use result::Result::{self, Ok, Err};
59+
use raw::TraitObject;
5760
use str;
5861
use string::{self, String};
5962

6063
/// Base functionality for all errors in Rust.
6164
#[stable(feature = "rust1", since = "1.0.0")]
62-
pub trait Error: Debug + Display {
65+
pub trait Error: Debug + Display + Reflect {
6366
/// A short description of the error.
6467
///
6568
/// The description should not contain newlines or sentence-ending
@@ -71,6 +74,14 @@ pub trait Error: Debug + Display {
7174
/// The lower-level cause of this error, if any.
7275
#[stable(feature = "rust1", since = "1.0.0")]
7376
fn cause(&self) -> Option<&Error> { None }
77+
78+
/// Get the `TypeId` of `self`
79+
#[doc(hidden)]
80+
#[unstable(feature = "core",
81+
reason = "unclear whether to commit to this public implementation detail")]
82+
fn type_id(&self) -> TypeId where Self: 'static {
83+
TypeId::of::<Self>()
84+
}
7485
}
7586

7687
#[stable(feature = "rust1", since = "1.0.0")]
@@ -154,3 +165,112 @@ impl Error for string::FromUtf16Error {
154165
}
155166
}
156167

168+
// copied from any.rs
169+
impl Error + 'static {
170+
/// Returns true if the boxed type is the same as `T`
171+
#[unstable(feature = "error_downcast", reason = "recently added")]
172+
#[inline]
173+
pub fn is<T: Error + 'static>(&self) -> bool {
174+
// Get TypeId of the type this function is instantiated with
175+
let t = TypeId::of::<T>();
176+
177+
// Get TypeId of the type in the trait object
178+
let boxed = self.type_id();
179+
180+
// Compare both TypeIds on equality
181+
t == boxed
182+
}
183+
184+
/// Returns some reference to the boxed value if it is of type `T`, or
185+
/// `None` if it isn't.
186+
#[unstable(feature = "error_downcast", reason = "recently added")]
187+
#[inline]
188+
pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
189+
if self.is::<T>() {
190+
unsafe {
191+
// Get the raw representation of the trait object
192+
let to: TraitObject = transmute(self);
193+
194+
// Extract the data pointer
195+
Some(transmute(to.data))
196+
}
197+
} else {
198+
None
199+
}
200+
}
201+
202+
/// Returns some mutable reference to the boxed value if it is of type `T`, or
203+
/// `None` if it isn't.
204+
#[unstable(feature = "error_downcast", reason = "recently added")]
205+
#[inline]
206+
pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
207+
if self.is::<T>() {
208+
unsafe {
209+
// Get the raw representation of the trait object
210+
let to: TraitObject = transmute(self);
211+
212+
// Extract the data pointer
213+
Some(transmute(to.data))
214+
}
215+
} else {
216+
None
217+
}
218+
}
219+
}
220+
221+
impl Error + 'static + Send {
222+
/// Forwards to the method defined on the type `Any`.
223+
#[unstable(feature = "error_downcast", reason = "recently added")]
224+
#[inline]
225+
pub fn is<T: Error + 'static>(&self) -> bool {
226+
<Error + 'static>::is::<T>(self)
227+
}
228+
229+
/// Forwards to the method defined on the type `Any`.
230+
#[unstable(feature = "error_downcast", reason = "recently added")]
231+
#[inline]
232+
pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
233+
<Error + 'static>::downcast_ref::<T>(self)
234+
}
235+
236+
/// Forwards to the method defined on the type `Any`.
237+
#[unstable(feature = "error_downcast", reason = "recently added")]
238+
#[inline]
239+
pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
240+
<Error + 'static>::downcast_mut::<T>(self)
241+
}
242+
}
243+
244+
impl Error {
245+
#[inline]
246+
#[unstable(feature = "error_downcast", reason = "recently added")]
247+
/// Attempt to downcast the box to a concrete type.
248+
pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<Error>> {
249+
if self.is::<T>() {
250+
unsafe {
251+
// Get the raw representation of the trait object
252+
let raw = boxed::into_raw(self);
253+
let to: TraitObject =
254+
transmute::<*mut Error, TraitObject>(raw);
255+
256+
// Extract the data pointer
257+
Ok(Box::from_raw(to.data as *mut T))
258+
}
259+
} else {
260+
Err(self)
261+
}
262+
}
263+
}
264+
265+
impl Error + Send {
266+
#[inline]
267+
#[unstable(feature = "error_downcast", reason = "recently added")]
268+
/// Attempt to downcast the box to a concrete type.
269+
pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<Error + Send>> {
270+
let err: Box<Error> = self;
271+
<Error>::downcast(err).map_err(|s| unsafe {
272+
// reapply the Send marker
273+
transmute::<Box<Error>, Box<Error + Send>>(s)
274+
})
275+
}
276+
}

src/libstd/io/buffered.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
use prelude::v1::*;
1414
use io::prelude::*;
1515

16+
use marker::Reflect;
1617
use cmp;
1718
use error;
1819
use fmt;
@@ -322,7 +323,7 @@ impl<W> From<IntoInnerError<W>> for Error {
322323
}
323324

324325
#[stable(feature = "rust1", since = "1.0.0")]
325-
impl<W: Send + fmt::Debug> error::Error for IntoInnerError<W> {
326+
impl<W: Reflect + Send + fmt::Debug> error::Error for IntoInnerError<W> {
326327
fn description(&self) -> &str {
327328
error::Error::description(self.error())
328329
}

src/libstd/sync/mpsc/mod.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -272,6 +272,7 @@ use error;
272272
use fmt;
273273
use mem;
274274
use cell::UnsafeCell;
275+
use marker::Reflect;
275276

276277
pub use self::select::{Select, Handle};
277278
use self::select::StartResult;
@@ -955,8 +956,7 @@ impl<T> fmt::Display for SendError<T> {
955956
}
956957

957958
#[stable(feature = "rust1", since = "1.0.0")]
958-
impl<T: Send> error::Error for SendError<T> {
959-
959+
impl<T: Send + Reflect> error::Error for SendError<T> {
960960
fn description(&self) -> &str {
961961
"sending on a closed channel"
962962
}
@@ -991,7 +991,7 @@ impl<T> fmt::Display for TrySendError<T> {
991991
}
992992

993993
#[stable(feature = "rust1", since = "1.0.0")]
994-
impl<T: Send> error::Error for TrySendError<T> {
994+
impl<T: Send + Reflect> error::Error for TrySendError<T> {
995995

996996
fn description(&self) -> &str {
997997
match *self {

src/libstd/sys/common/poison.rs

+4-3
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010

1111
use prelude::v1::*;
1212

13+
use marker::Reflect;
1314
use cell::UnsafeCell;
1415
use error::{Error};
1516
use fmt;
@@ -109,7 +110,7 @@ impl<T> fmt::Display for PoisonError<T> {
109110
}
110111
}
111112

112-
impl<T: Send> Error for PoisonError<T> {
113+
impl<T: Send + Reflect> Error for PoisonError<T> {
113114
fn description(&self) -> &str {
114115
"poisoned lock: another task failed inside"
115116
}
@@ -155,13 +156,13 @@ impl<T> fmt::Debug for TryLockError<T> {
155156
}
156157

157158
#[stable(feature = "rust1", since = "1.0.0")]
158-
impl<T: Send> fmt::Display for TryLockError<T> {
159+
impl<T: Send + Reflect> fmt::Display for TryLockError<T> {
159160
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
160161
self.description().fmt(f)
161162
}
162163
}
163164

164-
impl<T: Send> Error for TryLockError<T> {
165+
impl<T: Send + Reflect> Error for TryLockError<T> {
165166
fn description(&self) -> &str {
166167
match *self {
167168
TryLockError::Poisoned(ref p) => p.description(),

0 commit comments

Comments
 (0)