use crate::{ghost::invariant::Tokens, prelude::*};
use ::std::thread::{self, JoinHandle, ScopedJoinHandle};
pub trait JoinHandleExt<T> {
#[logic(prophetic)]
fn valid_result(self, x: T) -> bool;
#[ensures(self.valid_result(result))]
fn join_unwrap(self) -> T;
}
impl<T> JoinHandleExt<T> for JoinHandle<T> {
#[logic(opaque, prophetic)]
fn valid_result(self, _x: T) -> bool {
dead
}
#[ensures(self.valid_result(result))]
#[trusted]
fn join_unwrap(self) -> T {
self.join().unwrap()
}
}
impl<T> JoinHandleExt<T> for ScopedJoinHandle<'_, T> {
#[logic(opaque, prophetic)]
fn valid_result(self, _x: T) -> bool {
dead
}
#[ensures(self.valid_result(result))]
#[trusted]
fn join_unwrap(self) -> T {
self.join().unwrap()
}
}
extern_spec! {
impl<T> JoinHandle<T> {
#[ensures(true)] fn is_finished(&self) -> bool;
}
impl<T> ScopedJoinHandle<'_, T> {
#[ensures(true)] fn is_finished(&self) -> bool;
}
}
#[requires(forall<t: Ghost<Tokens>> (forall<ns> t.contains(ns)) ==> f.precondition((t,)))]
#[ensures(exists<t: Ghost<Tokens>> (forall<ns> t.contains(ns)) && forall<r> result.valid_result(r) ==> f.postcondition_once((t,), r))]
#[trusted]
pub fn spawn<F, T>(f: F) -> JoinHandle<T>
where
F: FnOnce(Ghost<Tokens>) -> T + Send + 'static,
T: Send + 'static,
{
::std::thread::spawn(|| f(Tokens::new()))
}
pub struct Scope<'scope, 'env: 'scope> {
inner: &'scope thread::Scope<'scope, 'env>,
}
impl<'scope, 'env: 'scope> Scope<'scope, 'env> {
#[requires(forall<t: Ghost<Tokens>> (forall<ns> t.contains(ns)) ==> f.precondition((t,)))]
#[ensures(exists<t: Ghost<Tokens>> (forall<ns> t.contains(ns)) && forall<r> result.valid_result(r) ==> f.postcondition_once((t,), r))]
#[trusted]
pub fn spawn<F, T>(&mut self, f: F) -> ScopedJoinHandle<'scope, T>
where
F: FnOnce(Ghost<Tokens>) -> T + Send + 'scope,
T: Send + 'scope,
{
self.inner.spawn(|| f(Tokens::new()))
}
}
#[requires(forall<s> inv(s) ==> f.precondition((s,)))]
#[ensures(exists<s> inv(s) && f.postcondition_once((s,),result))]
#[trusted]
pub fn scope<'env, F, T>(f: F) -> T
where
F: for<'scope> FnOnce(&mut Scope<'scope, 'env>) -> T,
{
::std::thread::scope(|s| f(&mut Scope { inner: s }))
}