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
pub mod walkers;

use crate::{
    effect::{Effect, Future},
    protocol::Visitor,
    Flow,
};

/// A type that can be walked.
pub trait Walk<'ctx, M, E: Effect<'ctx>>: WalkerTypes + Sized {
    /// The walker for the type.
    type Walker: Walker<'ctx, E, Error = Self::Error, Output = Self::Output>;

    fn into_walker(self) -> Self::Walker;
}

pub trait WalkerTypes {
    type Error: Send;

    /// An arbitrary type the walker is left with after walking.
    ///
    /// Its recommended that this is `Self` if the walker is repeatable.
    type Output: Send;
}

/// Walker for a type.
///
/// The `'ctx` lifetime is some lifetime that is longer than `Self`.
/// Data from the value may borrow using `'ctx`.
///
/// The way to use a walker is as follows.
/// - Call [From::from()] with a value to be walked to make a walker.
/// - Call [Self::walk()] to walk the value. Data will be sent to the provided
///     visitor.
pub trait Walker<'ctx, E: Effect<'ctx>>: WalkerTypes + Send {
    /// Walk the value.
    ///
    /// The walker should send data to the `visitor` as it walks the value.
    fn walk<'a>(
        self,
        visitor: Visitor<'a, 'ctx>,
    ) -> Future<'a, 'ctx, Result<Self::Output, Self::Error>, E>
    where
        Self: 'a;
}

pub trait WalkerObjSafe<'ctx, E: Effect<'ctx>>: Send {
    fn walk<'a>(&'a mut self, visitor: Visitor<'a, 'ctx>) -> Future<'a, 'ctx, Flow, E>
    where
        Self: 'a;

    fn skip(&mut self);
}

pub type DynWalker<'a, 'ctx, E> = &'a mut (dyn WalkerObjSafe<'ctx, E> + Send + 'a);

enum DynWalkerState<W: WalkerTypes> {
    Skipped,
    Walking,
    Pending(W),
    Done(W::Output),
    Err(W::Error),
}

pub enum DynWalkerError<W: WalkerTypes> {
    NeverWalked(W),

    /// This can only happen if a panic happens furing the walk and is then caught before calling
    /// finish..
    WalkNeverFinished,

    Walker(W::Error),
}

pub struct DynWalkerAdapter<W: WalkerTypes> {
    state: DynWalkerState<W>,
}

impl<W: WalkerTypes> DynWalkerAdapter<W> {
    pub fn new(walker: W) -> Self {
        Self {
            state: DynWalkerState::Pending(walker),
        }
    }

    pub fn finish(self) -> Result<Option<W::Output>, DynWalkerError<W>> {
        match self.state {
            DynWalkerState::Skipped => Ok(None),
            DynWalkerState::Walking => Err(DynWalkerError::WalkNeverFinished),
            DynWalkerState::Pending(walker) => Err(DynWalkerError::NeverWalked(walker)),
            DynWalkerState::Done(value) => Ok(Some(value)),
            DynWalkerState::Err(err) => Err(DynWalkerError::Walker(err)),
        }
    }
}

impl<'ctx, W: Walker<'ctx, E>, E: Effect<'ctx>> WalkerObjSafe<'ctx, E> for DynWalkerAdapter<W> {
    fn walk<'a>(&'a mut self, visitor: Visitor<'a, 'ctx>) -> Future<'a, 'ctx, Flow, E>
    where
        Self: 'a,
    {
        E::wrap(async {
            if let DynWalkerState::Pending(walker) =
                core::mem::replace(&mut self.state, DynWalkerState::Walking)
            {
                // Walk the walker.
                match walker.walk(visitor).await {
                    Ok(value) => {
                        self.state = DynWalkerState::Done(value);
                        Flow::Continue
                    }
                    Err(err) => {
                        self.state = DynWalkerState::Err(err);

                        // Signal that control flow should stop as soon as possible as we
                        // are in an error state.
                        Flow::Break
                    }
                }
            } else {
                // Can't do anything if the walker has already been walked.
                Flow::Continue
            }
        })
    }

    fn skip(&mut self) {
        self.state = DynWalkerState::Skipped;
    }
}