creusot-std 0.15.0

Standard library of Creusot: provides specification macros, contracts for Rust standard library and logic helpers
Documentation
//! Shared mutation with a ghost token
//!
//! This allows a form of interior mutability, using [ghost](mod@crate::ghost) code to keep
//! track of the logical value.

use crate::{
    ghost::{NotObjective, Perm, perm::PermTarget},
    prelude::*,
};
use core::cell::UnsafeCell;

/// Cell with ghost permissions
///
/// When writing/reading the cell, you need to explicitly pass a [`Perm`] object.
///
/// # Safety
///
/// When using Creusot to verify the code, all methods should be safe to call. Indeed,
/// Creusot ensures that every operation on the inner value uses the right [`Perm`] object
/// created by [`PCell::new`], ensuring safety in a manner similar to
/// [ghost_cell](https://docs.rs/ghost-cell/latest/ghost_cell/).
#[trusted(positive(T))]
#[opaque]
#[repr(transparent)]
pub struct PCell<T: ?Sized>(UnsafeCell<T>);

impl<T: ?Sized> PermTarget for PCell<T> {
    type Value = T;
    /// A `Perm<PCell<_>>` must not be objective, because its accesses are
    /// not atomic.
    type Objectiveness = NotObjective;
}

#[trusted]
unsafe impl<T: ?Sized> Send for PCell<T> {}
#[trusted]
unsafe impl<T: ?Sized> Sync for PCell<T> {}

impl<T: ?Sized> Invariant for Perm<PCell<T>> {
    #[logic(open, prophetic, inline)]
    #[creusot::trusted_trivial_if_param_trivial]
    fn invariant(self) -> bool {
        pearlite! { inv(self.val_unsized()) }
    }
}

impl<T: ?Sized> PCell<T> {
    /// Creates a new `PCell` containing the given value.
    #[trusted]
    #[check(terminates)]
    #[ensures(result.0 == *result.1.ward())]
    #[ensures(result.1.val() == value)]
    pub fn new(value: T) -> (Self, Ghost<Perm<PCell<T>>>)
    where
        T: Sized,
    {
        let this = Self(UnsafeCell::new(value));
        let perm = Ghost::conjure();
        (this, perm)
    }

    /// Sets the contained value.
    ///
    /// # Safety
    ///
    /// You must ensure that no other borrows to the inner value of `self` exists when calling
    /// this function.
    ///
    /// Creusot will check that all calls to this function are indeed safe: see the
    /// [type documentation](PCell#safety).
    #[trusted]
    #[check(terminates)]
    #[requires(self == perm.ward())]
    #[ensures(val == (^perm).val())]
    #[ensures(resolve(perm.val()))]
    #[ensures(self == (^perm).ward())]
    pub unsafe fn set(&self, perm: Ghost<&mut Perm<PCell<T>>>, val: T)
    where
        T: Sized,
    {
        let _ = perm;
        unsafe {
            *self.0.get() = val;
        }
    }

    /// Replaces the contained value with `val`, and returns the old contained value.
    ///
    /// # Safety
    ///
    /// You must ensure that no other borrows to the inner value of `self` exists when calling
    /// this function.
    ///
    /// Creusot will check that all calls to this function are indeed safe: see the
    /// [type documentation](PCell#safety).
    #[trusted]
    #[check(terminates)]
    #[requires(self == perm.ward())]
    #[ensures(val == (^perm).val())]
    #[ensures(result == perm.val())]
    #[ensures(self == (^perm).ward())]
    pub unsafe fn replace(&self, perm: Ghost<&mut Perm<PCell<T>>>, val: T) -> T
    where
        T: Sized,
    {
        let _ = perm;
        unsafe { core::ptr::replace(self.0.get(), val) }
    }

    /// Unwraps the value, consuming the cell.
    #[trusted]
    #[check(terminates)]
    #[requires(self == *perm.ward())]
    #[ensures(result == perm.val())]
    pub fn into_inner(self, perm: Ghost<Perm<PCell<T>>>) -> T
    where
        T: Sized,
    {
        let _ = perm;
        self.0.into_inner()
    }

    /// Immutably borrows the wrapped value.
    ///
    /// The permission also acts as a guard, preventing writes to the underlying value
    /// while it is borrowed.
    ///
    /// # Safety
    ///
    /// You must ensure that no mutable borrow to the inner value of `self` exists when calling
    /// this function.
    ///
    /// Creusot will check that all calls to this function are indeed safe: see the
    /// [type documentation](PCell#safety).
    #[trusted]
    #[check(terminates)]
    #[requires(self == perm.ward())]
    #[ensures(*result == *perm.val_unsized())]
    pub unsafe fn borrow<'a>(&'a self, perm: Ghost<&'a Perm<PCell<T>>>) -> &'a T {
        let _ = perm;
        unsafe { &*self.0.get() }
    }

    /// Mutably borrows the wrapped value.
    ///
    /// The permission also acts as a guard, preventing accesses to the underlying value
    /// while it is borrowed.
    ///
    /// # Safety
    ///
    /// You must ensure that no other borrows to the inner value of `self` exists when calling
    /// this function.
    ///
    /// Creusot will check that all calls to this function are indeed safe: see the
    /// [type documentation](PCell#safety).
    #[trusted]
    #[check(terminates)]
    #[requires(self == perm.ward())]
    #[ensures(self == (^perm).ward())]
    #[ensures(*result == *perm.val_unsized())]
    #[ensures(^result == *(^perm).val_unsized())]
    pub unsafe fn borrow_mut<'a>(&'a self, perm: Ghost<&'a mut Perm<PCell<T>>>) -> &'a mut T {
        let _ = perm;
        unsafe { &mut *self.0.get() }
    }

    /// Returns a copy of the contained value.
    ///
    /// # Safety
    ///
    /// You must ensure that no mutable borrow to the inner value of `self` exists when calling
    /// this function.
    ///
    /// Creusot will check that all calls to this function are indeed safe: see the
    /// [type documentation](PCell#safety).
    #[trusted]
    #[check(terminates)]
    #[requires(self == perm.ward())]
    #[ensures(result == perm.val())]
    pub unsafe fn get(&self, perm: Ghost<&Perm<PCell<T>>>) -> T
    where
        T: Copy + Sized,
    {
        let _ = perm;
        unsafe { *self.0.get() }
    }

    /// Returns a raw pointer to the underlying data in this cell.
    #[trusted]
    #[ensures(true)]
    pub fn as_ptr(&self) -> *mut T {
        self.0.get()
    }

    /// Returns a `&PCell<T>` from a `&mut T`
    #[trusted]
    #[check(terminates)]
    #[ensures(result.0 == result.1.ward())]
    #[ensures(^t == *(^result.1).val_unsized())]
    #[ensures(*t == *result.1.val_unsized())]
    pub fn from_mut(t: &mut T) -> (&PCell<T>, Ghost<&mut Perm<PCell<T>>>) {
        // SAFETY: `PCell` is layout-compatible with `Cell` and `T` because it is `repr(transparent)`.
        // SAFETY: `&mut` ensures unique access
        let cell: &PCell<T> = unsafe { &*(t as *mut T as *const Self) };
        let perm = Ghost::conjure();
        (cell, perm)
    }

    /// Takes the value of the cell, leaving `Default::default()` in its place.
    ///
    /// # Safety
    ///
    /// You must ensure that no other borrows to the inner value of `self` exists when calling
    /// this function.
    ///
    /// Creusot will check that all calls to this function are indeed safe: see the
    /// [type documentation](PCell#safety).
    #[requires(self == perm.ward())]
    #[ensures(self == (^perm).ward())]
    #[ensures(result == *perm.val_unsized())]
    #[ensures(T::default.postcondition((), *(^perm).val_unsized()))]
    pub unsafe fn take(&self, perm: Ghost<&mut Perm<PCell<T>>>) -> T
    where
        T: Default,
    {
        unsafe { self.replace(perm, T::default()) }
    }
}