reference icon indicating copy to clipboard operation
reference copied to clipboard

Add rule to object safety?

Open ehuss opened this issue 5 years ago • 4 comments

There seems to be a rule missing from the object safety list: https://github.com/rust-lang/reference/blob/master/src/items/traits.md#object-safety

I'm not sure how to properly word the rule, but it something along that lines that "Supertraits cannot reference Self as a type parameter".

This restriction was introduced in https://github.com/rust-lang/rust/pull/22452.

Some examples:

trait Super<T: ?Sized> {}
trait WithSelf: Super<Self> {}
struct S;
impl<A> Super<A> for S {}
impl WithSelf for S {}
let obj: Box<dyn WithSelf> = Box::new(S);  // ERROR: `Self` in type parameter
// Slight variation using default type.
trait Super<T: ?Sized = Self> {}
trait WithSelf: Super {}
struct S;
impl Super for S {}
impl WithSelf for S {}
let obj: Box<dyn WithSelf> = Box::new(S);  // ERROR: `Self` in type parameter

Is it correct that this rule should be added to the list? If so, can someone write down the proper wording?

ehuss avatar Feb 10 '20 17:02 ehuss

cc @nikomatsakis

Centril avatar Feb 10 '20 18:02 Centril

This apparently doesn't only apply for supertraits that use Self as a type parameter, but also if the trait itself does (for example PartialEq appears to be non-object-safe as a result) because

trait PartialEq<Rhs = Self>

I suggest adding

  • A generic type parameter of this trait, or any of its supertraits, is not specified to be Self

together with an expanded example to show that this applies even when Self: ?Sized.

For reference, this is the compiler error describing the same rule:

5  | trait MyTrait: PartialEq {}
   |       -------  ^^^^^^^^^ ...because it uses `Self` as a type parameter
   |       |
   |       this trait cannot be made into an object...

Happy to make a PR where exact language can be agreed if this is desirable.

jmaargh avatar Dec 13 '23 01:12 jmaargh

I asked over at https://rust-lang.zulipchat.com/#narrow/stream/213817-t-lang/topic/object.20safety.20of.20Self.20in.20supertraits for some suggestions. Someone noted https://github.com/rust-lang/rust/issues/88904 as a strange edge case, but I am uncertain if that is just a bug.

What you have suggested above sounds good to me, and would be happy to take a PR.

ehuss avatar Feb 04 '24 21:02 ehuss

Happy to. Will be delayed until I get permission from my new job but I don't see that being a problem.

jmaargh avatar Feb 04 '24 23:02 jmaargh