There's ongoing work towards reducing monomorphizations automatically in MIR under "polymorphization." It's not immediately clear how much overlap there is, but it'd certainly be nice to have a guarantee of polymorphization.
This is at a high level an optimization that very code-size-concious containers can often do manually at cost of type safety, by the internals working over effectively *mut c_void
and only reattaching typing as necessary.
However, it's necessary to reattach typing more often than you'd like, as you need a DynMetadata<dyn Sized>
in order to get size information for ptr::copy
and de
/alloc
. This means it's impossible to have a properly erased impl with phantom type-system-only typing, because it needs to have the Sized
metadata to convert to &dyn Sized
.
I don't think it's necessary/possible for types to be generic over a ghost type. Rather, we'd have
struct Box<T>(…);
impl<dyn T: ?Sized> Deref for Box<T> { … }
impl<T: ?Sized> Drop for Box<T> { … }
that is, using guaranteed phantom polymorphism is a property of the impl
, not the struct
.
I also worry that while dyn
is appropriate here, using it will degrade the purpose of switching to requiring dyn
as it marking a difference between known generic types and trait object types.
I also worry that the cost of devirtualization through the polymorophic middle may counteract some of the benefit of phantom typing.
In general, though, I absolutely support at least the ability to have (&Opaque, Metadata<T>)
and polymorphize this but still maintain a typesafe impl and generic API. I personally would limit the automatic support to fully-erased-phantom-typed types to limit scope (requiring use of a trait to pass in a Metadata<T>
to reconstruct &dyn Trait
), but I can see the benefits of either approach; requiring the explicit elaboration of providing the pointee metadata allows the developer to control when/how it's provided, though.
Also, dyn const
, despite being a seeming contradiction, is a favorite of mine for how to describe custom unsized pointers.
Textual notes
But there are places where this inlining can not be done: traits and dyn
objects.
Yes but also no. If you call a &dyn _
function with a concrete type, that can be inlined. More generally, "devirtualization" is a surprisingly powerful optimization technique.
Inlining definitely can't happen while you still only have dyn _
, though.