use std::any::{Any, TypeId, type_name};
use std::collections::HashMap;
use std::sync::{Arc, Mutex, PoisonError};
use crate::capability::{Concat, Embed, HCons, HList, HNil};
use crate::failure::Never;
use crate::kernel::{
AnyEnv, Effect, ExitKind, Instr, MaskOp, Node, die, downcast_env, from_async, succeed, suspend,
};
use crate::scope::Scope;
type BuildFn<Out, E, In> = dyn Fn(&MemoMap) -> Effect<Out, E, In> + Send + Sync;
#[must_use = "layers are lazy; build them with .build() or feed them to .provide_layer(..)"]
pub struct Layer<Out, E, In = HNil> {
node: Arc<BuildFn<Out, E, In>>,
}
impl<Out, E, In> Clone for Layer<Out, E, In> {
fn clone(&self) -> Self {
Self {
node: Arc::clone(&self.node),
}
}
}
impl<Out, E, In> std::fmt::Debug for Layer<Out, E, In> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Layer")
.field("out", &type_name::<Out>())
.field("in", &type_name::<In>())
.finish()
}
}
impl<Out, E> Layer<Out, E>
where
Out: HList,
E: Send + 'static,
{
pub fn succeed(out: Out) -> Self {
Self::from_build(move |_| succeed(out.clone()))
}
}
impl<Out, E, In> Layer<Out, E, In>
where
Out: HList,
E: Send + 'static,
In: HList,
{
pub fn effect(make: impl Fn() -> Effect<Out, E, In> + Send + Sync + 'static) -> Self {
Self::from_build(move |_| make())
}
pub fn from_effect(build: Effect<Out, E, In>) -> Self {
let slot = Mutex::new(Some(build));
Self::from_build(move |_| {
let taken = slot.lock().unwrap_or_else(PoisonError::into_inner).take();
taken.unwrap_or_else(|| {
die(format!(
"Layer::from_effect: the layer producing `{}` was already built once; use \
Layer::effect to build a layer more than once",
type_name::<Out>()
))
})
})
}
pub fn scoped(make: impl Fn(Scope) -> Effect<Out, E, In> + Send + Sync + 'static) -> Self {
Self::from_build(move |memo| make(memo.scope.clone()))
}
pub fn acquire_release(
acquire: impl Fn() -> Effect<Out, E, In> + Send + Sync + 'static,
release: impl Fn(Out, ExitKind) -> Effect<(), Never, HNil> + Send + Sync + 'static,
) -> Self {
let release = Arc::new(release);
Self::scoped(move |scope| {
let release = Arc::clone(&release);
acquire()
.flat_map(move |out: Out| {
let held = out.clone();
scope
.add_finalizer_exit(move |kind| release(held, kind))
.map(move |()| out)
})
.uninterruptible()
})
}
pub fn fresh(self) -> Self {
Layer::from_build(move |memo| self.build_in(&memo.fresh()))
}
fn from_build(build: impl Fn(&MemoMap) -> Effect<Out, E, In> + Send + Sync + 'static) -> Self {
Self {
node: Arc::new(build),
}
}
pub fn build(&self) -> Effect<Out, E, In> {
let scope = Scope::new();
let body = self.build_scoped(&scope);
Effect::from_instr(Instr::WithFiber(Box::new(move |_, fiber| {
let m = fiber.mask();
Instr::Mask(
Box::new(Instr::Fold(
Box::new(Instr::Mask(Box::new(body.into_instr()), MaskOp::Set(m))),
Box::new(move |exit| match exit {
Ok(out) => Instr::Pure(Ok(out)),
Err(cause) => {
let kind = ExitKind::of_cause(&cause);
let close = under(scope.close(kind), |_: &In| HNil).into_instr();
Instr::Fold(
Box::new(close),
Box::new(move |fin| {
Instr::Pure(Err(match fin {
Ok(_) => cause,
Err(fc) => crate::failure::Cause::then(cause, fc),
}))
}),
)
}
}),
)),
MaskOp::Inc,
)
})))
}
pub fn build_scoped(&self, scope: &Scope) -> Effect<Out, E, In> {
self.build_in(&MemoMap::with_scope(scope.clone()))
}
pub fn launch(self) -> Effect<Never, E, In> {
Effect::scoped(move |scope| {
self
.build_scoped(&scope)
.flat_map(|_| from_async(std::future::pending::<Result<Never, E>>))
})
}
fn build_in(&self, memo: &MemoMap) -> Effect<Out, E, In> {
let node = Arc::clone(&self.node);
let memo = memo.clone();
suspend(move || {
let key = memo_key(&node);
if let Some(out) = memo.get::<Out>(key) {
return succeed(out);
}
let construct = node(&memo);
construct.map(move |out: Out| {
memo.insert(key, Box::new(node), out.clone());
out
})
})
}
pub fn merge<O2, I2>(
self,
other: Layer<O2, E, I2>,
) -> Layer<<Out as Concat<O2>>::Out, E, <In as Concat<I2>>::Out>
where
O2: HList,
I2: HList,
Out: Concat<O2>,
In: Concat<I2>,
<Out as Concat<O2>>::Out: TypeIds,
<In as Concat<I2>>::Out: SplitAt<In, Right = I2>,
{
reject_duplicate_outputs::<<Out as Concat<O2>>::Out>("Layer::merge");
Layer::from_build(move |memo| {
let left = under(self.build_in(memo), |m: &<In as Concat<I2>>::Out| {
SplitAt::<In>::left(m)
});
let right = under(other.build_in(memo), |m: &<In as Concat<I2>>::Out| {
SplitAt::<In>::right(m)
});
left.flat_map(move |o1| right.map(move |o2| o1.concat(o2)))
})
}
pub fn provide_to<O2, I2, Is>(self, upper: Layer<O2, E, I2>) -> Layer<O2, E, In>
where
O2: HList,
I2: HList,
Out: Embed<I2, Is>,
{
Layer::from_build(move |memo| {
let up = upper.build_in(memo);
self
.build_in(memo)
.flat_map(move |out| up.provide_env(out).narrow::<In, HNil>())
})
}
pub fn provide_merge<O0, I0, Is>(
self,
base: Layer<O0, E, I0>,
) -> Layer<<O0 as Concat<Out>>::Out, E, I0>
where
O0: HList + Concat<Out> + Embed<In, Is>,
I0: HList,
<O0 as Concat<Out>>::Out: TypeIds,
{
reject_duplicate_outputs::<<O0 as Concat<Out>>::Out>("Layer::provide_merge");
Layer::from_build(move |memo| {
let upper = self.build_in(memo);
base.build_in(memo).flat_map(move |o0: O0| {
upper
.provide_env(o0.clone())
.narrow::<I0, HNil>()
.map(move |out| o0.concat(out))
})
})
}
}
impl<A, E, R> Effect<A, E, R>
where
A: Send + 'static,
E: Send + 'static,
R: HList,
{
pub fn provide_layer<Out, In, Is>(self, layer: Layer<Out, E, In>) -> Effect<A, E, In>
where
Out: HList + Embed<R, Is>,
In: HList,
{
Effect::scoped(move |scope| {
layer
.build_scoped(&scope)
.flat_map(move |out| self.provide_env(out).narrow::<In, HNil>())
})
}
}
#[derive(Clone, Default)]
struct MemoMap {
entries: Arc<Mutex<HashMap<usize, MemoEntry>>>,
scope: Scope,
}
struct MemoEntry {
_node: Box<dyn Any + Send + Sync>,
out: Box<dyn Any + Send + Sync>,
}
impl MemoMap {
fn with_scope(scope: Scope) -> Self {
Self {
entries: Arc::default(),
scope,
}
}
fn fresh(&self) -> Self {
Self::with_scope(self.scope.clone())
}
fn get<Out: HList>(&self, key: usize) -> Option<Out> {
let entries = self.entries.lock().unwrap_or_else(PoisonError::into_inner);
entries
.get(&key)
.and_then(|e| e.out.downcast_ref::<Out>())
.cloned()
}
fn insert<Out: HList>(&self, key: usize, node: Box<dyn Any + Send + Sync>, out: Out) {
let mut entries = self.entries.lock().unwrap_or_else(PoisonError::into_inner);
entries.entry(key).or_insert(MemoEntry {
_node: node,
out: Box::new(out),
});
}
}
fn memo_key<Out, E, In>(node: &Arc<BuildFn<Out, E, In>>) -> usize {
Arc::as_ptr(node).cast::<()>() as usize
}
#[diagnostic::on_unimplemented(
message = "the environment `{Self}` does not start with `{Left}`",
label = "cannot split `{Self}` after `{Left}`"
)]
pub trait SplitAt<Left>: HList {
type Right: HList;
fn left(&self) -> Left;
fn right(&self) -> Self::Right;
}
impl<S: HList> SplitAt<HNil> for S {
type Right = S;
fn left(&self) -> HNil {
HNil
}
fn right(&self) -> S {
self.clone()
}
}
#[diagnostic::do_not_recommend]
impl<H, T, Rest> SplitAt<HCons<H, T>> for HCons<H, Rest>
where
H: Send + Sync + 'static,
T: HList,
Rest: SplitAt<T>,
{
type Right = Rest::Right;
fn left(&self) -> HCons<H, T> {
HCons(Arc::clone(&self.0), self.1.left())
}
fn right(&self) -> Self::Right {
self.1.right()
}
}
pub trait TypeIds: HList {
fn push_type_ids(out: &mut Vec<(TypeId, &'static str)>);
fn type_ids() -> Vec<(TypeId, &'static str)> {
let mut out = Vec::with_capacity(Self::LEN);
Self::push_type_ids(&mut out);
out
}
}
impl TypeIds for HNil {
fn push_type_ids(_: &mut Vec<(TypeId, &'static str)>) {}
}
impl<H: Send + Sync + 'static, T: TypeIds> TypeIds for HCons<H, T> {
fn push_type_ids(out: &mut Vec<(TypeId, &'static str)>) {
out.push((TypeId::of::<H>(), type_name::<H>()));
T::push_type_ids(out);
}
}
fn reject_duplicate_outputs<Out: TypeIds>(op: &str) {
let ids = Out::type_ids();
for (i, (id, name)) in ids.iter().enumerate() {
if ids[..i].iter().any(|(seen, _)| seen == id) {
panic!("capability `{name}` is produced by both sides of {op}; wrap one in a newtype");
}
}
}
fn under<A, E, Inner, Outer>(
eff: Effect<A, E, Inner>,
project: impl FnOnce(&Outer) -> Inner + Send + 'static,
) -> Effect<A, E, Outer>
where
A: Send + 'static,
E: Send + 'static,
Inner: HList,
Outer: HList,
{
match eff.node {
Node::Pure(r) => Effect::pure(r),
node => Effect::from_instr(Instr::Provide(
Box::new(Effect::<A, E, Inner> { node }.into_instr()),
Box::new(move |outer: &AnyEnv| Arc::new(project(downcast_env::<Outer>(outer))) as AnyEnv),
)),
}
}
#[cfg(test)]
mod tests {
use super::*;
struct A;
struct B;
#[test]
fn split_at_is_positional_with_repeats() {
let env = HCons::new(A, HCons::new(A, HCons::new(B, HNil)));
let l: HCons<A, HNil> = SplitAt::<HCons<A, HNil>>::left(&env);
let r: HCons<A, HCons<B, HNil>> = SplitAt::<HCons<A, HNil>>::right(&env);
assert!(Arc::ptr_eq(&l.0, &env.0));
assert!(Arc::ptr_eq(&r.0, &env.1.0));
}
#[test]
fn type_ids_in_order_and_duplicates_rejected() {
let ids = <HCons<A, HCons<B, HNil>>>::type_ids();
assert_eq!(ids.len(), 2);
assert_eq!(ids[0].0, TypeId::of::<A>());
reject_duplicate_outputs::<HCons<A, HCons<B, HNil>>>("t");
let dup =
std::panic::catch_unwind(|| reject_duplicate_outputs::<HCons<A, HCons<A, HNil>>>("t"));
assert!(dup.is_err());
}
#[test]
fn memo_map_keys_by_node_and_keeps_the_first_entry() {
let layer: Layer<HCons<A, HNil>, ()> = Layer::succeed(HCons::new(A, HNil));
let key = memo_key(&layer.node);
assert_eq!(
key,
memo_key(&layer.clone().node),
"clones share the identity"
);
let memo = MemoMap::default();
assert!(memo.get::<HCons<A, HNil>>(key).is_none());
let first = HCons::new(A, HNil);
memo.insert(key, Box::new(Arc::clone(&layer.node)), first.clone());
memo.insert(key, Box::new(Arc::clone(&layer.node)), HCons::new(A, HNil));
let got = memo.get::<HCons<A, HNil>>(key).expect("memoised");
assert!(Arc::ptr_eq(&got.0, &first.0));
}
}