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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
//! Resolve a `Closure` repeatedly while a condition is met.

use async_hash::Hash;
use std::collections::HashSet;
use std::fmt;

use async_trait::async_trait;
use destream::{de, en};
use futures::try_join;
use log::{debug, warn};
use safecast::{Match, TryCastFrom, TryCastInto};
use sha2::digest::{Digest, Output};

use tc_error::*;
use tcgeneric::{Id, Instance, PathSegment, TCPathBuf};

use crate::closure::Closure;
use crate::route::Public;
use crate::scalar::{Number, Scalar, Scope, Value};
use crate::state::{State, ToState};
use crate::txn::Txn;

use super::Refer;

/// A while loop.
#[derive(Clone, Eq, PartialEq)]
pub struct While {
    cond: Scalar,
    closure: Scalar,
    state: Scalar,
}

#[async_trait]
impl Refer for While {
    fn dereference_self(self, path: &TCPathBuf) -> Self {
        Self {
            cond: self.cond.dereference_self(path),
            closure: self.closure.dereference_self(path),
            state: self.state.dereference_self(path),
        }
    }

    fn is_conditional(&self) -> bool {
        self.closure.is_conditional()
    }

    fn is_inter_service_write(&self, cluster_path: &[PathSegment]) -> bool {
        self.cond.is_inter_service_write(cluster_path)
            || self.closure.is_inter_service_write(cluster_path)
            || self.state.is_inter_service_write(cluster_path)
    }

    fn reference_self(self, path: &TCPathBuf) -> Self {
        Self {
            cond: self.cond.reference_self(path),
            closure: self.closure.reference_self(path),
            state: self.state.reference_self(path),
        }
    }

    fn requires(&self, deps: &mut HashSet<Id>) {
        self.cond.requires(deps);
        self.closure.requires(deps);
        self.state.requires(deps);
    }

    async fn resolve<'a, T: ToState + Instance + Public>(
        self,
        context: &'a Scope<'a, T>,
        txn: &'a Txn,
    ) -> TCResult<State> {
        debug!("While::resolve {}", self);

        if self.cond.is_conditional() {
            return Err(TCError::bad_request(
                "While does not allow nested conditional",
                self.cond,
            ));
        } else if self.state.is_conditional() {
            return Err(TCError::bad_request(
                "While does not allow nested conditional",
                self.state,
            ));
        }

        let (cond, closure, mut state) = try_join!(
            self.cond.resolve(context, txn),
            self.closure.resolve(context, txn),
            self.state.resolve(context, txn)
        )?;

        let cond = Closure::try_cast_from(cond, |s| {
            TCError::bad_request("while loop condition should be an Op or Closure, found", s)
        })?;

        let closure = Closure::try_cast_from(closure, |s| {
            TCError::bad_request("while loop requires an Op or Closure, found", s)
        })?;

        debug!("While condition definition is {}", cond);

        loop {
            let mut cond = cond.clone();
            let still_going = loop {
                match cond.clone().call(txn, state.clone()).await? {
                    State::Scalar(Scalar::Value(Value::Number(Number::Bool(still_going)))) => {
                        break still_going.into()
                    }
                    State::Closure(closure) => {
                        warn!("While condition returned a nested {}", closure);
                        cond = closure;
                    }
                    State::Scalar(Scalar::Op(op_def)) => {
                        warn!("While condition returned a nested {}", op_def);
                        cond = op_def.into()
                    }
                    other => {
                        return Err(TCError::bad_request(
                            "invalid condition for While loop",
                            other,
                        ))
                    }
                }
            };

            if still_going {
                state = closure.clone().call(txn, state).await?;

                if state.is_conditional() {
                    return Err(TCError::bad_request(
                        "conditional State is not allowed in a While loop",
                        state,
                    ));
                }

                debug!("While loop state is {}", state);
            } else {
                break Ok(state);
            }
        }
    }
}

impl<'a, D: Digest> Hash<D> for &'a While {
    fn hash(self) -> Output<D> {
        Hash::<D>::hash((&self.cond, &self.closure, &self.state))
    }
}

impl TryCastFrom<Scalar> for While {
    fn can_cast_from(scalar: &Scalar) -> bool {
        scalar.matches::<(Scalar, Scalar, Scalar)>()
    }

    fn opt_cast_from(scalar: Scalar) -> Option<Self> {
        if scalar.matches::<(Scalar, Scalar, Scalar)>() {
            scalar.opt_cast_into().map(|(cond, closure, state)| Self {
                cond,
                closure,
                state,
            })
        } else {
            None
        }
    }
}

#[async_trait]
impl de::FromStream for While {
    type Context = ();

    async fn from_stream<D: de::Decoder>(context: (), decoder: &mut D) -> Result<Self, D::Error> {
        let while_loop = Scalar::from_stream(context, decoder).await?;
        Self::try_cast_from(while_loop, |s| de::Error::invalid_value(s, "a While loop"))
    }
}

impl<'en> en::IntoStream<'en> for While {
    fn into_stream<E: en::Encoder<'en>>(self, encoder: E) -> Result<E::Ok, E::Error> {
        (self.cond, self.closure, self.state).into_stream(encoder)
    }
}

impl<'en> en::ToStream<'en> for While {
    fn to_stream<E: en::Encoder<'en>>(&'en self, encoder: E) -> Result<E::Ok, E::Error> {
        en::IntoStream::into_stream((&self.cond, &self.closure, &self.state), encoder)
    }
}

impl fmt::Debug for While {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "while {:?} call {:?} with state {:?}",
            self.cond, self.closure, self.state
        )
    }
}

impl fmt::Display for While {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "while {} call {} with state {}",
            self.cond, self.closure, self.state
        )
    }
}