Module rustc_trait_selection::traits::object_safety
source · Expand description
“Object safety” refers to the ability for a trait to be converted to an object. In general, traits may only be converted to an object if all of their methods meet certain criteria. In particular, they must:
- have a suitable receiver from which we can extract a vtable and coerce to a “thin” version that doesn’t contain the vtable;
- not reference the erased type
Self
except for in this receiver; - not have generic type parameters.
Structs§
Enums§
- Reasons a method might not be object-safe.
Functions§
- This code checks that
receiver_is_dispatchable
is correctly implemented. - This is somewhat subtle. In general, we want to forbid references to
Self
in the argument and return types, since the value ofSelf
is erased. However, there is one exception: it is ok to referenceSelf
in order to access an associated type of the current trait, since we retain the value of those associated types in the object type itself. - Returns the object safety violations that affect HIR ty lowering.
- We say a method is vtable safe if it can be invoked on a trait object. Note that object-safe traits can have some non-vtable-safe methods, so long as they require
Self: Sized
or otherwise ensure that they cannot be used whenSelf = Trait
. - Returns
Some(_)
if this item makes the containing trait not object safe. - Creates the object type for the current trait. For example, if the current trait is
Deref
, then this will bedyn Deref<Target = Self::Target> + 'static
. - Performs a type instantiation to produce the version of
receiver_ty
whenSelf = self_ty
. For example, forreceiver_ty = Rc<Self>
andself_ty = Foo
, returnsRc<Foo>
. - Checks the method’s receiver (the
self
argument) can be dispatched on whenSelf
is a trait object. We require thatDispatchableFromDyn
be implemented for the receiver type in the following way: - Returns
Some(_)
if this method cannot be called on a trait object; this does not necessarily imply that the enclosing trait is not object safe, because the method might have a where clauseSelf:Sized
.