use std::any::Any;
use std::cell::Cell;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use super::anybox::AnyEnv;
use super::bind::{BindFuture, surface, surface_first};
use super::bind_same::{SameEnv, SameEnvIndex};
use super::cause::from_exit;
use super::ctx::Ctx;
use super::effect::Effect;
use super::local::{HoldMask, IntoLocal};
use crate::capability::{Embed, HList};
use crate::concurrency::Concurrency;
use crate::failure::Never;
use crate::par::all;
pub struct Lift<E>(Cell<Option<E>>);
impl<E> Lift<E> {
pub fn new(e: E) -> Self {
Self(Cell::new(Some(e)))
}
}
pub trait LiftNever {
fn lift<E>(&self) -> E;
}
impl LiftNever for &Lift<Never> {
fn lift<E>(&self) -> E {
match self.0.take() {
Some(n) => match n {},
None => unreachable!("id_effect: `~` error lifted twice (macro bug)"),
}
}
}
pub trait LiftFrom<E2> {
fn lift<E: WidenFrom<E2>>(&self) -> E;
}
impl<E2> LiftFrom<E2> for Lift<E2> {
fn lift<E: WidenFrom<E2>>(&self) -> E {
match self.0.take() {
Some(e) => E::widen(e),
None => unreachable!("id_effect: `~` error lifted twice (macro bug)"),
}
}
}
#[diagnostic::on_unimplemented(
message = "the error `{E2}` of this `~` bind does not widen into the body's error `{Self}`",
label = "`{Self}` has no `From<{E2}>`",
note = "convert it at the bind: `~x.map_err(..)` (into an `Or<L, R>` body error, `.map_err(Or::Right)` for the right arm), `~x.catch(..)` to handle it (the only option in a `Never` body), or `impl From<{E2}> for {Self}`"
)]
pub trait WidenFrom<E2> {
fn widen(e: E2) -> Self;
}
#[diagnostic::do_not_recommend]
impl<E: From<E2>, E2> WidenFrom<E2> for E {
fn widen(e: E2) -> E {
E::from(e)
}
}
pub fn bind_local<R, X, A, E, Sub, Is>(
ctx: &Ctx<R>,
sub: X,
) -> impl Future<Output = Result<A, E>> + use<R, X, A, E, Sub, Is>
where
X: IntoLocal<A, E, Sub>,
R: Embed<Sub, Is> + Send + Sync + 'static,
Sub: Send + Sync + 'static,
A: 'static,
E: 'static,
{
let env: Arc<Sub> = match (Arc::clone(&ctx.env) as AnyEnv).downcast::<Sub>() {
Ok(same) => same,
Err(_) => Arc::new(Embed::<Sub, Is>::project(&*ctx.env)),
};
let run = sub
.into_local()
.run_in(Ctx::new(env, Arc::clone(&ctx.fiber)));
let run = HoldMask::new(run, Arc::clone(&ctx.fiber));
async move { surface(from_exit(run.await)) }
}
pub trait CapsChecked<const N: usize> {
type Out;
}
impl<T, const N: usize> CapsChecked<N> for T {
type Out = T;
}
#[diagnostic::on_unimplemented(
message = "`{Self}` cannot be a branch of a `~(..)` join in an effect over `{R}`",
label = "not an effect over a part of `{R}`",
note = "each branch of `~(a, b, ..)` is an `Effect` (or a `.same_env()` one); bind a `Result` with `?` or a future with `.await` before the join"
)]
pub trait JoinBranch<R, Is> {
type Output;
type Error;
fn into_branch(self) -> Effect<Self::Output, Self::Error, R>;
}
impl<B, E2, Sub, R, Is> JoinBranch<R, Is> for Effect<B, E2, Sub>
where
B: Send + 'static,
E2: Send + 'static,
Sub: HList + Send + Sync + 'static,
R: Embed<Sub, Is> + HList,
{
type Output = B;
type Error = E2;
fn into_branch(self) -> Effect<B, E2, R> {
self.narrow::<R, Is>()
}
}
impl<B, E2, R> JoinBranch<R, SameEnvIndex> for SameEnv<Effect<B, E2, R>> {
type Output = B;
type Error = E2;
fn into_branch(self) -> Effect<B, E2, R> {
self.into_inner()
}
}
pub fn branch<R, X, Is>(_ctx: &Ctx<R>, x: X) -> Effect<X::Output, X::Error, R>
where
X: JoinBranch<R, Is>,
{
x.into_branch()
}
#[diagnostic::on_unimplemented(
message = "`~(..)` joins 2 to 8 effects over the same environment and error",
label = "not a tuple of 2 to 8 effects",
note = "pass 2 to 8 effects; for more, nest a join or use `all`"
)]
pub trait JoinTuple<R> {
type Output;
type Error;
fn join(self) -> Effect<Self::Output, Self::Error, R>;
}
type Slot = Box<dyn Any + Send>;
fn unslot<A: 'static>(slot: Option<Slot>) -> A {
match slot.map(|s| s.downcast::<A>()) {
Some(Ok(a)) => *a,
_ => unreachable!("id_effect: `~(..)` join lost a branch value (kernel bug)"),
}
}
macro_rules! join_tuple {
($($a:ident $i:tt),+) => {
impl<E, R, $($a),+> JoinTuple<R> for ($(Effect<$a, E, R>,)+)
where
E: Send + 'static,
R: Send + Sync + 'static,
$($a: Send + 'static,)+
{
type Output = ($($a,)+);
type Error = E;
fn join(self) -> Effect<Self::Output, E, R> {
let branches: Vec<Effect<Slot, E, R>> =
vec![$(self.$i.map(|v| Box::new(v) as Slot)),+];
all(branches, Concurrency::Unbounded).map(|slots| {
let mut slots = slots.into_iter();
($(unslot::<$a>(slots.next()),)+)
})
}
}
};
}
join_tuple!(A0 0, A1 1);
join_tuple!(A0 0, A1 1, A2 2);
join_tuple!(A0 0, A1 1, A2 2, A3 3);
join_tuple!(A0 0, A1 1, A2 2, A3 3, A4 4);
join_tuple!(A0 0, A1 1, A2 2, A3 3, A4 4, A5 5);
join_tuple!(A0 0, A1 1, A2 2, A3 3, A4 4, A5 5, A6 6);
join_tuple!(A0 0, A1 1, A2 2, A3 3, A4 4, A5 5, A6 6, A7 7);
pub fn join_binds<R, T>(ctx: &Ctx<R>, branches: T) -> JoinFuture<T::Output, T::Error>
where
T: JoinTuple<R>,
T::Output: Send + 'static,
T::Error: Send + 'static,
R: Send + Sync + 'static,
{
JoinFuture(ctx.bind_same_env(branches.join()))
}
#[must_use = "futures do nothing unless polled"]
#[derive(Debug)]
pub struct JoinFuture<B, E>(BindFuture<B, E>);
impl<B: 'static, E: 'static> Future for JoinFuture<B, E> {
type Output = Result<B, E>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<B, E>> {
self.get_mut().0.poll_exit(cx).map(surface_first)
}
}
#[cfg(test)]
mod tests {
use std::future::Future;
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::task::{Context, Poll, Wake, Waker};
use std::time::{Duration, Instant};
use super::*;
use crate::capability::HNil;
use crate::failure::{Cause, Exit};
use crate::kernel::{LocalEffect, from_async, succeed, sync};
use crate::runtime::{BoxFuture, Executor, FiberContext, LocalBoxFuture, NotLocal};
struct NoExec;
struct Ignore;
#[allow(
clippy::manual_noop_waker,
reason = "the K-nb gate bans the std no-op waker anywhere under src/next"
)]
impl Wake for Ignore {
fn wake(self: Arc<Self>) {}
}
impl Executor for NoExec {
fn spawn(&self, _: BoxFuture<'static, ()>) {
unreachable!("bind_local unit tests spawn nothing")
}
fn spawn_local(&self, _: LocalBoxFuture<'static, ()>) -> Result<(), NotLocal> {
Err(NotLocal)
}
fn spawn_blocking(&self, _: Box<dyn FnOnce() + Send>) {
unreachable!("bind_local unit tests spawn nothing")
}
fn sleep(&self, _: Duration) -> BoxFuture<'static, ()> {
Box::pin(async {})
}
fn now(&self) -> Instant {
Instant::now()
}
}
fn interrupt_a_suspended_local_bind<X>(sub: X)
where
X: IntoLocal<u8, (), HNil> + 'static,
{
let fiber = FiberContext::new_root(Arc::new(NoExec));
let after = Arc::new(AtomicUsize::new(0));
let after2 = Arc::clone(&after);
let body: LocalEffect<u8, (), HNil> = LocalEffect::from_ctx(move |ctx| async move {
let v = bind_local::<HNil, X, u8, (), HNil, HNil>(&ctx, sub).await?;
after2.fetch_add(1, Ordering::SeqCst);
Ok(v)
});
let mut run = body.run_on(Arc::clone(&fiber));
let waker = Waker::from(Arc::new(Ignore));
let mut cx = Context::from_waker(&waker);
assert!(Pin::new(&mut run).poll(&mut cx).is_pending());
assert!(fiber.mask() > 0, "the suspended bind holds a mask level");
fiber.request_interrupt();
let Poll::Ready(exit) = Pin::new(&mut run).poll(&mut cx) else {
panic!("an interrupted bind completes")
};
assert!(
matches!(exit, Exit::Failure(Cause::Interrupt(id)) if id == fiber.id()),
"{exit:?}"
);
assert_eq!(after.load(Ordering::SeqCst), 0, "the body did not continue");
assert_eq!(fiber.mask(), 0, "no mask level leaked");
}
#[test]
fn an_interrupted_local_bind_of_a_local_effect_runs_its_finalizer() {
let finalized = Arc::new(AtomicBool::new(false));
let fin = Arc::clone(&finalized);
interrupt_a_suspended_local_bind(
LocalEffect::<u8, (), HNil>::from_future(|| async {
std::future::pending::<()>().await;
Ok(0)
})
.ensuring(LocalEffect::sync(move || fin.store(true, Ordering::SeqCst))),
);
assert!(finalized.load(Ordering::SeqCst), "sub-effect finalizer ran");
}
#[test]
fn an_interrupted_local_bind_of_a_send_effect_runs_its_finalizer() {
let finalized = Arc::new(AtomicBool::new(false));
let fin = Arc::clone(&finalized);
interrupt_a_suspended_local_bind(
succeed::<u8, (), HNil>(0)
.flat_map(|_| {
from_async(|| async {
std::future::pending::<()>().await;
Ok(0)
})
})
.ensuring(sync(move || fin.store(true, Ordering::SeqCst))),
);
assert!(finalized.load(Ordering::SeqCst), "sub-effect finalizer ran");
}
}