1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
//! An effectful computation with some effects handled

use super::{coproduct::Either, Context, Continue, Effectful, Event, Poll, Waker};

use std::fmt;
use std::marker::PhantomData;
use std::pin::Pin;

struct Handler<HC: Effectful> {
    computation: Pin<Box<HC>>,
    waker: Option<Waker<Continue<HC::Output>>>,
}

impl<HC> fmt::Debug for Handler<HC>
where
    HC: Effectful + fmt::Debug,
    HC::Output: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("Handler")
            .field("computation", &self.computation)
            .field("waker", &self.waker)
            .finish()
    }
}

impl<HC: Effectful> Handler<HC> {
    fn new(computation: HC) -> Self {
        Self {
            computation: Box::pin(computation),
            waker: None,
        }
    }
}

/// An effectful computation with some effects handled
pub struct Handled<C, H, HC, E, I>
where
    HC: Effectful,
{
    source: Option<C>,
    handler: H,
    handler_stack: Vec<Handler<HC>>,
    state: ActiveComputation,
    phantom: PhantomData<(E, I)>,
}

impl<C, H, HC, E, I> fmt::Debug for Handled<C, H, HC, E, I>
where
    C: fmt::Debug,
    H: fmt::Debug,
    HC: Effectful + fmt::Debug,
    HC::Output: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("Handled")
            .field("source", &self.source)
            .field("handler", &self.handler)
            .field("handler stack", &self.handler_stack)
            .field("state", &self.state)
            .finish()
    }
}

impl<C, H, HC: Effectful, E, I> Handled<C, H, HC, E, I> {
    pub(crate) fn new(source: C, handler: H) -> Self {
        Handled {
            source: Some(source),
            handler,
            handler_stack: vec![],
            state: ActiveComputation::Source,
            phantom: PhantomData,
        }
    }
}

#[derive(Debug)]
enum ActiveComputation {
    Source,
    Handler,
}

impl<C, Output, Effect, H, HC, HandledEffect, NewOutput, NewEffect, I> Effectful
    for Handled<C, H, HC, HandledEffect, I>
where
    C: Effectful<Output = Output, Effect = Effect>,
    H: FnMut(Event<Output, HandledEffect>) -> HC,
    HC: Effectful<Output = NewOutput, Effect = Either<Continue<NewOutput>, NewEffect>>,
    Effect: super::coproduct::Subset<HandledEffect, I, Remainder = NewEffect>,
{
    type Output = NewOutput;
    type Effect = NewEffect;

    // I'm not sure if this inline improves performance;
    // this method is much larger than I expected
    #[inline]
    fn poll(mut self: Pin<&mut Self>, cx: &Context) -> Poll<Self::Output, Self::Effect> {
        // TODO: verify soundness
        unsafe {
            let this = self.as_mut().get_unchecked_mut();
            loop {
                match &mut this.state {
                    ActiveComputation::Source => {
                        match Pin::new_unchecked(
                            this.source.as_mut().expect("poll after completion"),
                        )
                        .poll(cx)
                        {
                            Poll::Event(Event::Complete(v)) => {
                                this.source = None;
                                this.state = ActiveComputation::Handler;
                                // TODO: what if this.handler panics?
                                let comp = (this.handler)(Event::Complete(v));
                                this.handler_stack.push(Handler::new(comp));
                            }
                            Poll::Event(Event::Effect(e)) => match e.subset() {
                                Ok(e) => {
                                    this.state = ActiveComputation::Handler;
                                    // TODO: what if this.handler panics?
                                    let comp = (this.handler)(Event::Effect(e));
                                    this.handler_stack.push(Handler::new(comp));
                                }
                                Err(rem) => return Poll::effect(rem),
                            },
                            Poll::Pending => return Poll::Pending,
                        }
                    }
                    ActiveComputation::Handler => {
                        let handler = &mut this.handler_stack.last_mut().unwrap().computation;
                        match handler.as_mut().poll(cx) {
                            Poll::Event(Event::Complete(v)) => {
                                this.handler_stack.pop();

                                // the last handler
                                if this.handler_stack.is_empty() {
                                    return Poll::complete(v);
                                } else {
                                    (this.handler_stack.last_mut().unwrap().waker)
                                        .take()
                                        .unwrap()
                                        .wake(v);
                                }
                            }
                            Poll::Event(Event::Effect(Either::A(_, cx))) => {
                                // continue the original computation
                                this.state = ActiveComputation::Source;

                                this.handler_stack.last_mut().unwrap().waker = Some(cx.waker());
                            }
                            Poll::Event(Event::Effect(Either::B(e))) => return Poll::effect(e),
                            Poll::Pending => return Poll::Pending,
                        }
                    }
                }
            }
        }
    }
}