Skip to content

Commit

Permalink
Replace CoerceSized trait with DispatchFromDyn
Browse files Browse the repository at this point in the history
Rename `CoerceSized` to `DispatchFromDyn`, and reverse the direction so that, for example, you write

```
impl<T: Unsize<U>, U> DispatchFromDyn<*const U> for *const T {}
```

instead of

```
impl<T: Unsize<U>, U> DispatchFromDyn<*const T> for *const U {}
```

this way the trait is really just a subset of `CoerceUnsized`.

The checks in object_safety.rs are updated for the new trait, and some documentation and method names in there are updated for the new trait name — e.g. `receiver_is_coercible` is now called `receiver_is_dispatchable`. Since the trait now works in the opposite direction, some code had to updated here for that too.

I did not update the error messages for invalid `CoerceSized` (now `DispatchFromDyn`) implementations, except to find/replace `CoerceSized` with `DispatchFromDyn`. Will ask for suggestions in the PR thread.
  • Loading branch information
mikeyhew committed Nov 1, 2018
1 parent c29641e commit f12c250
Show file tree
Hide file tree
Showing 17 changed files with 164 additions and 190 deletions.
6 changes: 3 additions & 3 deletions src/liballoc/boxed.rs
Expand Up @@ -77,7 +77,7 @@ use core::iter::FusedIterator;
use core::marker::{Unpin, Unsize};
use core::mem;
use core::pin::Pin;
use core::ops::{CoerceUnsized, CoerceSized, Deref, DerefMut, Generator, GeneratorState};
use core::ops::{CoerceUnsized, DispatchFromDyn, Deref, DerefMut, Generator, GeneratorState};
use core::ptr::{self, NonNull, Unique};
use core::task::{LocalWaker, Poll};

Expand Down Expand Up @@ -696,8 +696,8 @@ impl<'a, A, R> FnOnce<A> for Box<dyn FnBox<A, Output = R> + Send + 'a> {
#[unstable(feature = "coerce_unsized", issue = "27732")]
impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Box<U>> for Box<T> {}

#[unstable(feature = "coerce_sized", issue = "0")]
impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceSized<Box<T>> for Box<U> {}
#[unstable(feature = "dispatch_from_dyn", issue = "0")]
impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Box<U>> for Box<T> {}

#[stable(feature = "box_slice_clone", since = "1.3.0")]
impl<T: Clone> Clone for Box<[T]> {
Expand Down
2 changes: 1 addition & 1 deletion src/liballoc/lib.rs
Expand Up @@ -86,7 +86,7 @@
#![feature(box_syntax)]
#![feature(cfg_target_has_atomic)]
#![feature(coerce_unsized)]
#![feature(coerce_sized)]
#![feature(dispatch_from_dyn)]
#![feature(core_intrinsics)]
#![feature(custom_attribute)]
#![feature(dropck_eyepatch)]
Expand Down
10 changes: 5 additions & 5 deletions src/liballoc/rc.rs
Expand Up @@ -255,7 +255,7 @@ use core::marker;
use core::marker::{Unpin, Unsize, PhantomData};
use core::mem::{self, align_of_val, forget, size_of_val};
use core::ops::Deref;
use core::ops::{CoerceUnsized, CoerceSized};
use core::ops::{CoerceUnsized, DispatchFromDyn};
use core::pin::Pin;
use core::ptr::{self, NonNull};
use core::convert::From;
Expand Down Expand Up @@ -297,8 +297,8 @@ impl<T: ?Sized> !marker::Sync for Rc<T> {}
#[unstable(feature = "coerce_unsized", issue = "27732")]
impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Rc<U>> for Rc<T> {}

#[unstable(feature = "coerce_sized", issue = "0")]
impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceSized<Rc<T>> for Rc<U> {}
#[unstable(feature = "dispatch_from_dyn", issue = "0")]
impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Rc<U>> for Rc<T> {}

impl<T> Rc<T> {
/// Constructs a new `Rc<T>`.
Expand Down Expand Up @@ -1179,8 +1179,8 @@ impl<T: ?Sized> !marker::Sync for Weak<T> {}
#[unstable(feature = "coerce_unsized", issue = "27732")]
impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}

#[unstable(feature = "coerce_sized", issue = "0")]
impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceSized<Weak<T>> for Weak<U> {}
#[unstable(feature = "dispatch_from_dyn", issue = "0")]
impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Weak<U>> for Weak<T> {}

impl<T> Weak<T> {
/// Constructs a new `Weak<T>`, without allocating any memory.
Expand Down
10 changes: 5 additions & 5 deletions src/liballoc/sync.rs
Expand Up @@ -25,7 +25,7 @@ use core::cmp::Ordering;
use core::intrinsics::abort;
use core::mem::{self, align_of_val, size_of_val};
use core::ops::Deref;
use core::ops::{CoerceUnsized, CoerceSized};
use core::ops::{CoerceUnsized, DispatchFromDyn};
use core::pin::Pin;
use core::ptr::{self, NonNull};
use core::marker::{Unpin, Unsize, PhantomData};
Expand Down Expand Up @@ -214,8 +214,8 @@ unsafe impl<T: ?Sized + Sync + Send> Sync for Arc<T> {}
#[unstable(feature = "coerce_unsized", issue = "27732")]
impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Arc<U>> for Arc<T> {}

#[unstable(feature = "coerce_sized", issue = "0")]
impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceSized<Arc<T>> for Arc<U> {}
#[unstable(feature = "dispatch_from_dyn", issue = "0")]
impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Arc<U>> for Arc<T> {}

/// `Weak` is a version of [`Arc`] that holds a non-owning reference to the
/// managed value. The value is accessed by calling [`upgrade`] on the `Weak`
Expand Down Expand Up @@ -257,8 +257,8 @@ unsafe impl<T: ?Sized + Sync + Send> Sync for Weak<T> {}

#[unstable(feature = "coerce_unsized", issue = "27732")]
impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Weak<U>> for Weak<T> {}
#[unstable(feature = "coerce_sized", issue = "0")]
impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceSized<Weak<T>> for Weak<U> {}
#[unstable(feature = "dispatch_from_dyn", issue = "0")]
impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Weak<U>> for Weak<T> {}

#[stable(feature = "arc_weak", since = "1.4.0")]
impl<T: ?Sized + fmt::Debug> fmt::Debug for Weak<T> {
Expand Down
4 changes: 2 additions & 2 deletions src/libcore/nonzero.rs
Expand Up @@ -10,7 +10,7 @@

//! Exposes the NonZero lang item which provides optimization hints.

use ops::{CoerceUnsized, CoerceSized};
use ops::{CoerceUnsized, DispatchFromDyn};

/// A wrapper type for raw pointers and integers that will never be
/// NULL or 0 that might allow certain optimizations.
Expand All @@ -21,4 +21,4 @@ pub(crate) struct NonZero<T>(pub(crate) T);

impl<T: CoerceUnsized<U>, U> CoerceUnsized<NonZero<U>> for NonZero<T> {}

impl<T: CoerceUnsized<U>, U: CoerceSized<T>> CoerceSized<NonZero<T>> for NonZero<U> {}
impl<T: DispatchFromDyn<U>, U> DispatchFromDyn<NonZero<U>> for NonZero<T> {}
4 changes: 2 additions & 2 deletions src/libcore/ops/mod.rs
Expand Up @@ -202,5 +202,5 @@ pub use self::generator::{Generator, GeneratorState};
#[unstable(feature = "coerce_unsized", issue = "27732")]
pub use self::unsize::CoerceUnsized;

#[unstable(feature = "coerce_sized", issue = "0")]
pub use self::unsize::CoerceSized;
#[unstable(feature = "dispatch_from_dyn", issue = "0")]
pub use self::unsize::DispatchFromDyn;
48 changes: 24 additions & 24 deletions src/libcore/ops/unsize.rs
Expand Up @@ -79,32 +79,32 @@ impl<T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<*const U> for *mut T {}
impl<T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<*const U> for *const T {}


/// Pointers to unsized types that can be coerced to a pointer to a sized type,
/// as long as pointee is actually a value of that sized type. This is used for
/// object safety, to check that a method's receiver type can be coerced from the version
/// where `Self = dyn Trait` to the version where `Self = T`, the erased, sized type
/// of the underlying object.
/// This is used for object safety, to check that a method's receiver type can be dispatched on.
///
/// `CoerceSized` is implemented for:
/// - `&[T]` is `CoerceSized<&[T; N]>` for any `N`
/// - `&Trait` is `CoerceSized<&T>` for any `T: Trait`
/// - and similarly for `&mut T`, `*const T`, `*mut T`, `Box<T>`, `Rc<T>`, `Arc<T>`
#[unstable(feature = "coerce_sized", issue = "0")]
#[cfg_attr(not(stage0), lang = "coerce_sized")]
pub trait CoerceSized<T> where T: CoerceUnsized<Self> {
/// example impl:
///
/// ```
/// impl<T: ?Sized, U: ?Sized> DispatchFromDyn<Rc<U>> for Rc<T>
/// where
/// T: Unsize<U>,
/// {}
/// ```
#[unstable(feature = "dispatch_from_dyn", issue = "0")]
#[cfg_attr(not(stage0), lang = "dispatch_from_dyn")]
pub trait DispatchFromDyn<T> {
// Empty.
}

// &U -> &T
#[unstable(feature = "coerce_sized", issue = "0")]
impl<'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceSized<&'a T> for &'a U {}
// &mut U -> &mut T
#[unstable(feature = "coerce_sized", issue = "0")]
impl<'a, T: ?Sized+Unsize<U>, U: ?Sized> CoerceSized<&'a mut T> for &'a mut U {}
// *const U -> *const T
#[unstable(feature = "coerce_sized", issue = "0")]
impl<T: ?Sized+Unsize<U>, U: ?Sized> CoerceSized<*const T> for *const U {}
// *mut U -> *mut T
#[unstable(feature = "coerce_sized", issue = "0")]
impl<T: ?Sized+Unsize<U>, U: ?Sized> CoerceSized<*mut T> for *mut U {}
// &T -> &U
#[unstable(feature = "dispatch_from_dyn", issue = "0")]
impl<'a, T: ?Sized+Unsize<U>, U: ?Sized> DispatchFromDyn<&'a U> for &'a T {}
// &mut T -> &mut U
#[unstable(feature = "dispatch_from_dyn", issue = "0")]
impl<'a, T: ?Sized+Unsize<U>, U: ?Sized> DispatchFromDyn<&'a mut U> for &'a mut T {}
// *const T -> *const U
#[unstable(feature = "dispatch_from_dyn", issue = "0")]
impl<T: ?Sized+Unsize<U>, U: ?Sized> DispatchFromDyn<*const U> for *const T {}
// *mut T -> *mut U
#[unstable(feature = "dispatch_from_dyn", issue = "0")]
impl<T: ?Sized+Unsize<U>, U: ?Sized> DispatchFromDyn<*mut U> for *mut T {}

7 changes: 3 additions & 4 deletions src/libcore/pin.rs
Expand Up @@ -91,7 +91,7 @@

use fmt;
use marker::Sized;
use ops::{Deref, DerefMut, CoerceUnsized, CoerceSized};
use ops::{Deref, DerefMut, CoerceUnsized, DispatchFromDyn};

#[doc(inline)]
pub use marker::Unpin;
Expand Down Expand Up @@ -325,10 +325,9 @@ where
{}

#[unstable(feature = "pin", issue = "49150")]
impl<'a, P, U> CoerceSized<Pin<P>> for Pin<U>
impl<'a, P, U> DispatchFromDyn<Pin<U>> for Pin<P>
where
P: CoerceUnsized<U>,
U: CoerceSized<P>,
P: DispatchFromDyn<U>,
{}

#[unstable(feature = "pin", issue = "49150")]
Expand Down
8 changes: 4 additions & 4 deletions src/libcore/ptr.rs
Expand Up @@ -75,7 +75,7 @@

use convert::From;
use intrinsics;
use ops::{CoerceUnsized, CoerceSized};
use ops::{CoerceUnsized, DispatchFromDyn};
use fmt;
use hash;
use marker::{PhantomData, Unsize};
Expand Down Expand Up @@ -2796,7 +2796,7 @@ impl<T: ?Sized> Copy for Unique<T> { }
impl<T: ?Sized, U: ?Sized> CoerceUnsized<Unique<U>> for Unique<T> where T: Unsize<U> { }

#[unstable(feature = "ptr_internals", issue = "0")]
impl<T: ?Sized, U: ?Sized> CoerceSized<Unique<T>> for Unique<U> where T: Unsize<U> { }
impl<T: ?Sized, U: ?Sized> DispatchFromDyn<Unique<U>> for Unique<T> where T: Unsize<U> { }

#[unstable(feature = "ptr_internals", issue = "0")]
impl<T: ?Sized> fmt::Pointer for Unique<T> {
Expand Down Expand Up @@ -2954,8 +2954,8 @@ impl<T: ?Sized> Copy for NonNull<T> { }
#[unstable(feature = "coerce_unsized", issue = "27732")]
impl<T: ?Sized, U: ?Sized> CoerceUnsized<NonNull<U>> for NonNull<T> where T: Unsize<U> { }

#[unstable(feature = "coerce_sized", issue = "0")]
impl<T: ?Sized, U: ?Sized> CoerceSized<NonNull<T>> for NonNull<U> where T: Unsize<U> { }
#[unstable(feature = "dispatch_from_dyn", issue = "0")]
impl<T: ?Sized, U: ?Sized> DispatchFromDyn<NonNull<U>> for NonNull<T> where T: Unsize<U> { }

#[stable(feature = "nonnull", since = "1.25.0")]
impl<T: ?Sized> fmt::Debug for NonNull<T> {
Expand Down
2 changes: 1 addition & 1 deletion src/librustc/middle/lang_items.rs
Expand Up @@ -271,7 +271,7 @@ language_item_table! {
DropTraitLangItem, "drop", drop_trait, Target::Trait;

CoerceUnsizedTraitLangItem, "coerce_unsized", coerce_unsized_trait, Target::Trait;
CoerceSizedTraitLangItem, "coerce_sized", coerce_sized_trait, Target::Trait;
DispatchFromDynTraitLangItem,"dispatch_from_dyn", dispatch_from_dyn_trait, Target::Trait;

AddTraitLangItem, "add", add_trait, Target::Trait;
SubTraitLangItem, "sub", sub_trait, Target::Trait;
Expand Down
62 changes: 32 additions & 30 deletions src/librustc/traits/object_safety.rs
Expand Up @@ -319,41 +319,42 @@ impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
&sig.map_bound(|sig| sig.inputs()[0]),
);

// until `unsized_locals` is fully implemented, `self: Self` can't be coerced from
// `Self=dyn Trait` to `Self=T`. However, this is already considered object-safe. We allow
// it as a special case here.
// FIXME(mikeyhew) get rid of this `if` statement once `receiver_is_coercible` allows
// until `unsized_locals` is fully implemented, `self: Self` can't be dispatched on.
// However, this is already considered object-safe. We allow it as a special case here.
// FIXME(mikeyhew) get rid of this `if` statement once `receiver_is_dispatchable` allows
// `Receiver: Unsize<Receiver[Self => dyn Trait]>`
if receiver_ty != self.mk_self_type() {
if !self.receiver_is_coercible(method, receiver_ty) {
if !self.receiver_is_dispatchable(method, receiver_ty) {
return Some(MethodViolationCode::UncoercibleReceiver);
}
}

None
}

/// checks the method's receiver (the `self` argument) can be coerced from
/// a fat pointer, including the trait object vtable, to a thin pointer.
/// e.g. from `Rc<dyn Trait>` to `Rc<T>`, where `T` is the erased type of the underlying object.
/// More formally:
/// checks the method's receiver (the `self` argument) can be dispatched on when `Self` is a
/// trait object. We require that `DispatchableFromDyn` be implemented for the receiver type
/// in the following way:
/// - let `Receiver` be the type of the `self` argument, i.e `Self`, `&Self`, `Rc<Self>`
/// - require the following bound:
/// forall(T: Trait) {
/// Receiver[Self => dyn Trait]: CoerceSized<Receiver[Self => T]>
/// Receiver[Self => T]: DispatchFromDyn<Receiver[Self => dyn Trait]>
/// }
/// where `Foo[X => Y]` means "the same type as `Foo`, but with `X` replaced with `Y`"
/// (substitution notation).
///
/// some examples of receiver types and their required obligation
/// - `&'a mut self` requires `&'a mut dyn Trait: CoerceSized<&'a mut T>`
/// - `self: Rc<Self>` requires `Rc<dyn Trait>: CoerceSized<Rc<T>>`
/// - `&'a mut self` requires `&'a mut T: DispatchFromDyn<&'a mut dyn Trait>`
/// - `self: Rc<Self>` requires `Rc<T>: DispatchFromDyn<Rc<dyn Trait>>`
/// - `self: Pin<Box<Self>>` requires `Pin<Box<T>>: DispatchFromDyn<Pin<Box<dyn Trait>>>`
///
/// The only case where the receiver is not coercible, but is still a valid receiver
/// The only case where the receiver is not dispatchable, but is still a valid receiver
/// type (just not object-safe), is when there is more than one level of pointer indirection.
/// e.g. `self: &&Self`, `self: &Rc<Self>`, `self: Box<Box<Self>>`. In these cases, there
/// is no way, or at least no inexpensive way, to coerce the receiver, because the object that
/// needs to be coerced is behind a pointer.
/// is no way, or at least no inexpensive way, to coerce the receiver from the version where
/// `Self = dyn Trait` to the version where `Self = T`, where `T` is the unknown erased type
/// contained by the trait object, because the object that needs to be coerced is behind
/// a pointer.
///
/// In practice, there are issues with the above bound: `where` clauses that apply to `Self`
/// would have to apply to `T`, trait object types have a lot of parameters that need to
Expand All @@ -364,37 +365,38 @@ impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
///
/// forall (U: ?Sized) {
/// if (Self: Unsize<U>) {
/// Receiver[Self => U]: CoerceSized<Receiver>
/// Receiver: DispatchFromDyn<Receiver[Self => U]>
/// }
/// }
///
/// for `self: &'a mut Self`, this means `&'a mut U: CoerceSized<&'a mut Self>`
/// for `self: Rc<Self>`, this means `Rc<U>: CoerceSized<Rc<Self>>`
/// for `self: &'a mut Self`, this means `&'a mut Self: DispatchFromDyn<&'a mut U>`
/// for `self: Rc<Self>`, this means `Rc<Self>: DispatchFromDyn<Rc<U>>`
/// for `self: Pin<Box<Self>>, this means `Pin<Box<Self>>: DispatchFromDyn<Pin<Box<U>>>`
//
// FIXME(mikeyhew) when unsized receivers are implemented as part of unsized rvalues, add this
// fallback query: `Receiver: Unsize<Receiver[Self => U]>` to support receivers like
// `self: Wrapper<Self>`.
#[allow(dead_code)]
fn receiver_is_coercible(
fn receiver_is_dispatchable(
self,
method: &ty::AssociatedItem,
receiver_ty: Ty<'tcx>,
) -> bool {
debug!("receiver_is_coercible: method = {:?}, receiver_ty = {:?}", method, receiver_ty);
debug!("receiver_is_dispatchable: method = {:?}, receiver_ty = {:?}", method, receiver_ty);

let traits = (self.lang_items().unsize_trait(),
self.lang_items().coerce_sized_trait());
let (unsize_did, coerce_sized_did) = if let (Some(u), Some(cu)) = traits {
self.lang_items().dispatch_from_dyn_trait());
let (unsize_did, dispatch_from_dyn_did) = if let (Some(u), Some(cu)) = traits {
(u, cu)
} else {
debug!("receiver_is_coercible: Missing Unsize or CoerceSized traits");
debug!("receiver_is_dispatchable: Missing Unsize or DispatchFromDyn traits");
return false;
};

// use a bogus type parameter to mimick a forall(U) query using u32::MAX for now.
// FIXME(mikeyhew) this is a total hack, and we should replace it when real forall queries
// are implemented
let target_self_ty: Ty<'tcx> = self.mk_ty_param(
let unsized_self_ty: Ty<'tcx> = self.mk_ty_param(
::std::u32::MAX,
Name::intern("RustaceansAreAwesome").as_interned_str(),
);
Expand All @@ -405,7 +407,7 @@ impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {

let predicate = ty::TraitRef {
def_id: unsize_did,
substs: self.mk_substs_trait(self.mk_self_type(), &[target_self_ty.into()]),
substs: self.mk_substs_trait(self.mk_self_type(), &[unsized_self_ty.into()]),
}.to_predicate();

let caller_bounds: Vec<Predicate<'tcx>> = param_env.caller_bounds.iter().cloned()
Expand All @@ -419,19 +421,19 @@ impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {

let receiver_substs = Substs::for_item(self, method.def_id, |param, _| {
if param.index == 0 {
target_self_ty.into()
unsized_self_ty.into()
} else {
self.mk_param_from_def(param)
}
});
// the type `Receiver[Self => U]` in the query
let unsized_receiver_ty = receiver_ty.subst(self, receiver_substs);

// Receiver[Self => U]: CoerceSized<Receiver>
// Receiver: DispatchFromDyn<Receiver[Self => U]>
let obligation = {
let predicate = ty::TraitRef {
def_id: coerce_sized_did,
substs: self.mk_substs_trait(unsized_receiver_ty, &[receiver_ty.into()]),
def_id: dispatch_from_dyn_did,
substs: self.mk_substs_trait(receiver_ty, &[unsized_receiver_ty.into()]),
}.to_predicate();

Obligation::new(
Expand All @@ -442,7 +444,7 @@ impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> {
};

self.infer_ctxt().enter(|ref infcx| {
// the receiver is coercible iff the obligation holds
// the receiver is dispatchable iff the obligation holds
infcx.predicate_must_hold(&obligation)
})
}
Expand Down

0 comments on commit f12c250

Please sign in to comment.