use crate::{logic::Mapping, prelude::*};
pub trait Guard<T> {
#[logic(prophetic)]
fn guards(self, initial: T, current: T) -> bool;
}
pub trait GuardRef<T> {
#[logic(prophetic)]
fn guards_ref(self, x: T) -> bool;
}
impl<'a, G: GuardRef<T>, T> Guard<&'a mut T> for G {
#[logic(open, prophetic, inline)]
fn guards(self, initial: &'a mut T, current: &'a mut T) -> bool {
pearlite! { self.guards_ref(*current) && ^initial == ^current }
}
}
#[repr(transparent)]
#[intrinsic("guarded")]
pub struct Guarded<T, G: Guard<T>> {
pub inner: T,
_guard: Snapshot<G>,
_initial: Snapshot<T>,
}
impl<T, G: Guard<T>> Invariant for Guarded<T, G> {
#[logic(open, prophetic, inline)]
fn invariant(self) -> bool {
pearlite! { (*self._guard).guards(*self._initial, self.inner) }
}
}
impl<T, G: Guard<T>> Guarded<T, G> {
#[logic(open, inline)]
pub fn guard(self) -> G {
pearlite! { *self._guard }
}
}
impl<'a, T, G: GuardRef<T>> Guarded<&'a mut T, G> {
#[trusted]
#[requires(guard.guards_ref(*borrow))]
#[ensures(result.inner == borrow)]
#[ensures(result.guard() == *guard)]
#[ensures(guard.guards_ref(^borrow))]
#[check(ghost)]
pub fn new(borrow: &'a mut T, guard: Snapshot<G>) -> Self {
Self { inner: borrow, _guard: guard, _initial: snapshot!(borrow) }
}
}
impl<'a, T> Guarded<&'a mut T, Mapping<T, bool>> {
#[requires(guard.guards_ref(*borrow))]
#[ensures(result.inner == borrow)]
#[ensures(result.guard() == *guard)]
#[ensures(guard.guards_ref(^borrow))]
#[check(ghost)]
pub fn new_m(borrow: &'a mut T, guard: Snapshot<Mapping<T, bool>>) -> Self {
Self::new(borrow, guard)
}
}
impl<'a, T> Guarded<&'a mut Option<T>, IsSome> {
#[trusted]
#[check(ghost)]
#[ensures(*result.inner == Some(**borrow))]
#[ensures(^result.inner == Some(^borrow))]
pub fn some(borrow: Ghost<&'a mut T>) -> Ghost<Self> {
let _ = borrow;
Ghost::conjure()
}
}
impl<T> GuardRef<T> for Mapping<T, bool> {
#[logic(open, inline)]
fn guards_ref(self, x: T) -> bool {
pearlite! { self[x] }
}
}
pub struct IsSome;
impl<T> GuardRef<Option<T>> for IsSome {
#[logic(open, inline)]
fn guards_ref(self, x: Option<T>) -> bool {
pearlite! { x != None }
}
}