[Idea] Pointer to Field

It’s iff the field is !Unpin that it becomes a problem.

If you project to Pin<Field> and later move that field in Drop::drop, you’ve broken the Pin safety inariants if Field: !Unpin.

More importantly, we have to assume the safe user will move in Drop::drop until they promise otherwise by fulfilling an unsafe contract (i.e. unsafe impl or calling an unsafe fn with said contract).

Even if that field is Copy? Would the wrapper that I proposed work?

Technically, Copy does not require Unpin. I don’t see how you could be Copy without being Unpin in spirit, however.

So is it fine to move out of a field of a type T where T: !Unpin and Field: Unpin? I think no, by your post earlier

I miswrote. Pin is a thin guarantee: it only applies to the directly pointed type and not to its fields. It can’t, given you have an unprotected &mut self at Drop::drop.

1 Like

Ok, that makes sense, so projecting to fields is fine as long as we also re-wrap the fields in Pin (which the current implementation does). Thanks!

So, an updated design that allow a type to declare its own fields as safe to pin-project. playground with some impls and showcase. Note that there are two remaining issues:

  • Not all types with fields are Sized. A good implementation would enable this for the other types as well. For the moment this may require specialization or an intrinsic, not a problem in stdlib though.
  • For the safe variant, we have an implementation choice. The unsafe trait version makes it very easy to implement the safe project by just calling the unsafe projections. However, a projection which relies on some lower pointer type to implement that project (e.g. Ref and RefMut) does not require any unsafe code for its own implementation. Instead, all of its impl could be completely safe. Thus, it may be more useful to drop the unsafe trait in favor of trait, and require the very simple function call from the impl itself instead of a default implementation.
/// Trait automatically implemented by `Foo::Field`
trait Field {
    type Parent: ?Sized;
    type FieldType: ?Sized;

    fn field() -> FieldDescriptor<Self::Parent, Self::FieldType>;
}

pub struct FieldDescriptor<Parent: ?Sized, FieldType: ?Sized> {
    offset: usize,
    __: PhantomData<(Box<Parent>, Box<FieldType>)>,
}


/// Projects a pointer into a field with unsafe pre-conditions.
trait UnsafeProject<F: Field>: Sized {
    type Projection;
    
    unsafe fn project(self, field: F) -> Self::Projection;
}

/// Can project a pointer into a field.
// TODO: we have a choice here, enable to default-impl *or* mark the trait `unsafe`.
unsafe trait Project<F: Field>: UnsafeProject<F> {
    fn safe_project(self, field: F) -> Self::Projection {
        // Safety: ensured from implementing this trait.
        unsafe { UnsafeProject::project(self, field) }
    }
}

/// Mark a field as safe to pin-project.
///
/// This is implemented by the type that contains the field.
unsafe trait PinnedField<F: Field<Parent=Self>> { }

/// *All* fields of 'unpin' types are safe to project to.
///
/// This relies on the `stdlib` being the only party to be able to provide an `impl` of `Field`.
unsafe impl<T, F> PinnedField<F> for T
    where T: Unpin, F: Field<Parent=T>
{ }
1 Like

It is safe to project to fields for Pin types, even if the field is !Unpin as long as we keep the Pin wrapping. So the current design is fine.

No. That is a misconception and you may have misunderstood the above comments explaining that. Suppose Foo { bar: Bar }. The type Foo may move the field bar in Drop::drop due to this method being supplied with a &mut Foo. As soon as you observe a Pin<&mut Bar> however, you get the guarantee that the value is not moved until its the own Drop is called. The Drop::drop of the struct Foo however runs first. Any move within it would be contrary to the guarantees that were given to Bar. Thus, the type Foo needs to opt-into the pin projection to its bar field.

The comment of thin-guarantee is aimed at providing this claim: Pin to Foo does not give Pin to Bar by inference. And the question about Copy: Unpin in the new thread opened recently was also trying to resolve if Drop is the only hinderance. Since Copy implies !Drop, any Copy type may provide safe projects to its fields.

3 Likes

I see, that makes sense. In that case reverting to the type based interface does make sense.

The only change that I would make is this, so that it is clear that FIELD won’t change at run-time and it may be easier to optimize.

trait Field {
    type Parent: ?Sized;
    type FieldType: ?Sized;
    const FIELD: FieldDescriptor<Self::Parent, Self::FieldType>;
}
2 Likes

Two things I had brewing the last few days. Firstly, this trait would allow us to improve some parts around treatment of pointers by introducing a very simple wrapper type, not unlike NonNull:

/// A pointer to an allocated memory region that has no aliases.
///
/// This acts similar to a reference but does not enforce the referenced 
/// region to be valid, while not allowing you to read.
#[repr(transparent)]
pub struct InitPtr<'a, T: ?Sized>(NonNull<T>, PhantomData<&'a ()>);

impl<T: ?Sized> InitPtr<'_, T> {
    /// Construct a new instance.
    ///
    /// The pointed-to region must be valid, mutably accessible and not
    /// aliased for the chosen lifetime. It need not be initialized.
    pub unsafe fn new(ptr: NonNull<T>) -> Self { InitPtr(ptr, PhantomData) }

    /// Replace the data at the pointed-to place.
    ///
    /// If previously initialized, the value is not dropped.
    pub fn write(&self, data: T) where T: Sized {
        /// SAFETY: opted-into by constructing the instance. 
        unsafe { pointer::write(self.0.get(), data) }
    }
}

Basically, it encapsulates the ability to safely perform llvm inbounds access to the type’s fields and to initalize the memory pointed to. Therefore we could give it a safe impl of Project with highly useful semantics, unlike a raw pointer, in which we nevertheless exploit the performance benefits etc. And whatever code is normally used to initialize a T can also safely initialize a InitPtr<T>. All of the unsafety is opted-into at the call to new.

What this would also improve is the current design of MaybeUninit. Currently, the only safe access is to a raw pointer. But that looses the information that the pointed-to region is definitely valid since it points inside the object itself. Returning a InitPtr instead (or additionally) would allow one to safely construct pointers to individual fields without ever having to resort to raw pointer dereferencing and the necessary unsafe block from that. The only point with actual unsafe code would be if one were to take out the initialized value afterwards, or convert to a reference but that is not on us.

There are two unresolved questsions here: Firstly, the type would not be able to traverse to fields of packed structs but neither could normal references atm. One similar trait to the PinnedField could allow opt-in for some members. Alternatively, an intermediate pointer type would initialize with pointer::write_unaligned instead and a new sub-trait of Field would assert the alignedness which would make references fine.

Secondly, the access is far from ergonomic for unions or types with tuple members, since each type and member would need to be referenced explicitely. An operator with new syntax could solve this that is reasonably close the field access, but one thing is missing. The base type which is projected does, under the design discussed above, not have to commit to a type for which to do the field lookup.

// `field` of which type?
some_ptr~field
  • How to find the instance for field given the pointer type.
    • Is it maybe fine to defer to simply Deref drilling to find the type which has such a field? If so, which Project instance should be chosen?
    • Should it be possible to implement Project for fields of more than one type? If not, must it be consistent with Deref?
    • Or make some new trait Pointer { type Pointee; } and use Pointee to resolve the field in that syntax.
  • Maybe we should restrict ourselves to field from the top-most pointed type, and not recursively search through auto-deref types. The reason is that many auto-deref results are not within the memory region of the original type and many pointer types are not capable of that (except &_).

I like the InitPtr idea. There are some easy-to-fix soundness issues with the suggested implementation, though:

This is unsound: if you take a &self you are no longer guaranteed to have no aliases. It should at the very least take a self: &'_ mut InitPtr<'a, T>.

Now, there are two possible extensions to this signature, to prevent memory leaks:

  • taking self: &'a mut InitPtr<'a, T>.

  • or even better:

    impl<'a, T> InitPtr<'a, T>
    where
        T : ?Sized + 'a,
    {
        pub
        unsafe fn new (...) -> Self { ... }
    
        pub
        fn init (self: InitPtr<'a, T>, data: T) -> &'a mut T
        where
            T : Sized,
        {
            let non_null = self.0;
            /// SAFETY: opted-into by constructing the instance. 
            unsafe {
                non_null.as_ptr().write(data);
                non_null.as_mut()
            }
        }
    }
    

Finally, the struct definition was lacking a T : 'a bound, and there is another soundness issue: it has the wrong variance over T, (NonNull is covariant (because usually related to owning semantics)).

So, this is how I'd fix it:


#[repr(transparent)]
pub struct InitPtr<'a, T>
where
    T : ?Sized + 'a,
(
    NonNull<T>,
    PhantomData<&'a mut T>,
);
1 Like

Is there any movement on this topic (possibly in other forums I’m unaware of)? I’m extremely interested in this due to it’s implications with regards to the possibility of creating intrusive collections.

This is just and idea, not an full blown RFC, it looks like we have stagnated.

Do we think we should move this to a full blown RFC? If yes, I’ll start drafting it up. If we move this to an RFC then we may get the views of the rust team.

  • Yes
  • No

0 voters

I did vote for it but I’m a bit conflicted here. The idea seems promising, the implementation contained but which current problems of Rust does immediately solve and is it the best solution for those concrete problems?

For example it doesn’t solve ergonomic pointer offsetting on its own but only if combined with supplementary syntax. I would not declare ptr.project(Base::field) an ergonomic win over smaller syntax additions for it such as &raw (*ptr).field. And conversely, any other use case of pointer-to-field for other reasons than pointer traveral is not apparent to me.

So, what then? The best course I can think of would be to publish the initial set of impl and new types as a user library, maybe with a proc-macro to create the pointer-to-field. Write the RFC in parallel to give a precise statement of goals. In course of that we would discover which parts absolutely need compiler support and which don’t, possibly clarify soundness concerns, and importantly be able to offer testable usability of the abstraction. Additional safety for InitPtr for example would be an, imho, fantastic win in its own right and during writing the lib we would find out where the compiler needs to help with soundness.

Ping me on Github if you do, although I’m a bit busy rn.

2 Likes

I will make a decision sometime July 5th on whether to move forward with this based on the poll. Till then, we can mull it over and make arguments for and against moving it to RFC status.

That's a good point! Before drafting an RFC (which, by construction, seem to prefer themselves to their alternatives), maybe we should discuss here which alternative is best:

  • waiting for &[mut] raw to become a thing, and using the notation above,

    • should it behave as project_inbounds ? The whole &[mut] raw (*ptr).field notation would then require unsafe (seems fine to me (given the written dereference *ptr), but it's still something to take into consideration);
  • directly getting this "smaller" / less ambitious RFC.

Or alternative three:

  • Convincing those involved int the current raw RFC that the surface syntax for it should have a form that is compatible with other, future, forms of pointer traversal without reference. Sort of planning for the Deref equivalent beforehand may be useful.

As far as I have been involved the RFC for &[mut] raw evolved from a pure MIR level change to one that affects surface language over time. I've been a proponent of embracing, at least in the surface syntax, an explicit pointer-traversal-only form that can not be mistaken for a dereferencing read, see also this other post for details .

The open question for your first option seems like a good reason for extending traversal to user-defined types as well. If that is possible then may the stdlib could provide a pointer wrapper that provides safe wrapping projection without the inbounds llvm annotations (potentially by just casting to usize and arithmetic math internally, not 100% on the soundness details). That would then be orthogonal to the issues of an initial support of builtin raw pointers that is surely focussed on performance conerns due to its immediate use in the standard library for lack of alternatives (and UB avoidance, pointers created from live references must only be used to access the memory inbounds of the intial object if I understood correctly).

At the same time I'm aware that the whole raw pointer is under a bit of perceived time pressure due to obviously wanting to rectify soundness concerns quickly. However, all ways of receiving an inital valid pointer seem perfectly fine to me. It's only traversing that currently requires temporarily referring to an invalid place and subsequently implicitly creating a reference to that, and has strictly speaking UB. My hope would thus be that a good RFC for simple pointer traversal, restricted to only raw pointers initially, would be open enough to permit customizations with user pointer types and a field representation as an extension and we could then define that extension based on whatever outcome this here yields.

5 Likes

One benefit that I see over &[mut] raw is that it can be hard to tell when you are doing poiner arithmetic with &[mut] raw as opposed to a read, as @197g showed. For example, in another thread he linked, &raw foo.bar.qaz, this does not do pointer arithmetic, but it can be easy to miss that. Compared to this solution, where it is obvious when we are and are not using pointer arithmetic, because the arithmetic is done inside a method call. I think this is a nice benefit of this formulation.

Based on the results of the poll, there is a clear majority of Yes, so I will draft up an RFC. If you would like to help with the RFC, you can track its progress here in the pull request!

You can also track the progess of the proof of concept crate here

I will welcome pull requests to add/change/fix parts of the RFC and the ptr-to-field crate.

Thank you all for your contributions to this idea!