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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
use {EXIT_ERROR, EXIT_SUCCESS};
use error::IsFatalError;
use env::{ArgumentsEnvironment, LastStatusEnvironment, ReportErrorEnvironment, VariableEnvironment};
use eval::WordEval;
use future::{Async, EnvFuture, Poll};
use spawn::{ExitResult, SpawnRef, VecSequence, VecSequenceWithLast};
use std::fmt;
use std::iter::Peekable;
use std::mem;
use std::vec;

/// Spawns a `for` loop with all the fields when `words` are evaluated, or with
/// the environment's currently set arguments if no `words` are specified.
///
/// For each element in the environment's arguments, `name` will be assigned
/// with its value and `body` will be executed.
pub fn for_loop<T, I, S, E: ?Sized>(name: T, words: Option<I>, body: Vec<S>, env: &E)
    -> For<I::IntoIter, S, E>
    where I: IntoIterator,
          I::Item: WordEval<E>,
          S: SpawnRef<E>,
          E: ArgumentsEnvironment + VariableEnvironment,
          E::VarName: From<T>,
          E::Var: From<E::Arg>,
{
    let kind = match words {
        Some(ws) => {
            let words = ws.into_iter();
            let (lo, hi) = words.size_hint();

            Kind::Word {
                values: Vec::with_capacity(hi.unwrap_or(lo)),
                current: None,
                words: words,
                name: Some(name.into()),
                body: body,
            }
        },
        None => Kind::Loop(for_args(name, body, env)),
    };

    For {
        kind: kind,
    }
}

/// Spawns a `for` loop with the environment's currently set arguments.
///
/// For each element in the environment's arguments, `name` will be assigned
/// with its value and `body` will be executed.
pub fn for_args<T, S, E: ?Sized>(name: T, body: Vec<S>, env: &E)
    -> ForArgs<vec::IntoIter<E::Var>, S, E>
    where S: SpawnRef<E>,
          E: ArgumentsEnvironment + VariableEnvironment,
          E::VarName: From<T>,
          E::Var: From<E::Arg>,
{
    let args = env.args()
        .into_iter()
        .cloned()
        .map(E::Var::from)
        .collect::<Vec<_>>();

    for_with_args(name, args, body)
}

/// Spawns a `for` loop with the specified arguments.
///
/// For each element in `args`, `name` will be assigned with its value and
/// `body` will be executed.
pub fn for_with_args<T, I, S, E: ?Sized>(name: T, args: I, body: Vec<S>)
    -> ForArgs<I::IntoIter, S, E>
    where I: IntoIterator<Item = E::Var>,
          S: SpawnRef<E>,
          E: VariableEnvironment,
          E::VarName: From<T>,
{
    ForArgs {
        name: Some(name.into()),
        args: args.into_iter().peekable(),
        body: body,
        state: None,
    }
}

#[derive(Debug)]
enum Kind<V, I, F, N, S, L> {
    Word {
        values: Vec<V>,
        current: Option<F>,
        words: I,
        name: Option<N>,
        body: Vec<S>,
    },
    Loop(L),
}

type ForKind<V, I, F, N, S, E> = Kind<V, I, F, N, S, ForArgs<vec::IntoIter<V>, S, E>>;

/// A future representing the execution of a `for` loop command.
#[must_use = "futures do nothing unless polled"]
pub struct For<I, S, E: ?Sized>
    where I: Iterator,
          I::Item: WordEval<E>,
          S: SpawnRef<E>,
          E: VariableEnvironment,
{
    #[cfg_attr(feature = "clippy", allow(type_complexity))]
    kind: ForKind<E::Var, I, <I::Item as WordEval<E>>::EvalFuture, E::VarName, S, E>,
}

impl<I, W, S, E: ?Sized> fmt::Debug for For<I, S, E>
    where I: Iterator<Item = W> + fmt::Debug,
          W: WordEval<E> + fmt::Debug,
          W::EvalFuture: fmt::Debug,
          S: SpawnRef<E> + fmt::Debug,
          S::EnvFuture: fmt::Debug,
          S::Future: fmt::Debug,
          E: VariableEnvironment,
          E::Var: fmt::Debug,
          E::VarName: fmt::Debug,
{
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.debug_struct("For")
            .field("kind", &self.kind)
            .finish()
    }
}

impl<I, W, S, E: ?Sized> EnvFuture<E> for For<I, S, E>
    where I: Iterator<Item = W>,
          W: WordEval<E>,
          W::EvalResult: Into<E::Var>,
          S: SpawnRef<E>,
          S::Error: From<W::Error> + IsFatalError,
          E: LastStatusEnvironment + ReportErrorEnvironment + VariableEnvironment,
          E::VarName: Clone,
{
    type Item = ExitResult<S::Future>;
    type Error = S::Error;

    fn poll(&mut self, env: &mut E) -> Poll<Self::Item, Self::Error> {
        loop {
            let next_kind = match self.kind {
                Kind::Word {
                    ref mut values,
                    ref mut current,
                    ref mut words,
                    ref mut name,
                    ref mut body,
                } => {
                    loop {
                        if let Some(ref mut f) = *current {
                            match f.poll(env) {
                                Ok(Async::Ready(f)) => values.extend(f.into_iter().map(Into::into)),
                                Ok(Async::NotReady) => return Ok(Async::NotReady),
                                Err(e) => {
                                    env.set_last_status(EXIT_ERROR);
                                    return Err(e.into())
                                },
                            };
                        }

                        match words.next() {
                            Some(w) => *current = Some(w.eval(env)),
                            None => break,
                        }
                    }

                    let name = name.take().expect("polled twice");
                    let args = mem::replace(values, Vec::new());
                    let body = mem::replace(body, Vec::new());

                    Kind::Loop(for_with_args(name, args, body))
                },

                Kind::Loop(ref mut l) => return l.poll(env),
            };

            self.kind = next_kind;
        }
    }

    fn cancel(&mut self, env: &mut E) {
        match self.kind {
            Kind::Word { ref mut current, .. } => { current.as_mut().map(|f| f.cancel(env)); },
            Kind::Loop(ref mut l) => l.cancel(env),
        }
    }
}

/// A future representing the execution of a `for` loop command.
#[must_use = "futures do nothing unless polled"]
pub struct ForArgs<I, S, E: ?Sized>
    where I: Iterator,
          S: SpawnRef<E>,
          E: VariableEnvironment,
{
    name: Option<E::VarName>,
    args: Peekable<I>,
    body: Vec<S>,
    state: Option<State<S, E>>,
}

impl<I, S, E: ?Sized> fmt::Debug for ForArgs<I, S, E>
    where I: Iterator + fmt::Debug,
          I::Item: fmt::Debug,
          S: SpawnRef<E> + fmt::Debug,
          S::EnvFuture: fmt::Debug,
          S::Future: fmt::Debug,
          E: VariableEnvironment,
          E::VarName: fmt::Debug
{
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.debug_struct("ForArgs")
            .field("name", &self.name)
            .field("args", &self.args)
            .field("body", &self.body)
            .field("state", &self.state)
            .finish()
    }
}

enum State<S, E: ?Sized> where S: SpawnRef<E> {
    Init(VecSequence<S, E>),
    Last(VecSequenceWithLast<S, E>),
}

impl<S, E: ?Sized> fmt::Debug for State<S, E>
    where S: SpawnRef<E> + fmt::Debug,
          S::EnvFuture: fmt::Debug,
          S::Future: fmt::Debug,
{
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            State::Init(ref init) => {
                fmt.debug_tuple("State::Init")
                    .field(init)
                    .finish()
            },
            State::Last(ref last) => {
                fmt.debug_tuple("State::Last")
                    .field(last)
                    .finish()
            },
        }
    }
}

impl<I, S, E: ?Sized> EnvFuture<E> for ForArgs<I, S, E>
    where I: Iterator<Item = E::Var>,
          S: SpawnRef<E>,
          S::Error: IsFatalError,
          E: LastStatusEnvironment + ReportErrorEnvironment + VariableEnvironment,
          E::VarName: Clone,
{
    type Item = ExitResult<S::Future>;
    type Error = S::Error;

    fn poll(&mut self, env: &mut E) -> Poll<Self::Item, Self::Error> {
        loop {
            let status = match self.state {
                Some(State::Init(ref mut vs)) => {
                    let (body, status) = try_ready!(vs.poll(env));
                    self.body = body;
                    env.set_last_status(status);
                    status
                },

                Some(State::Last(ref mut last)) => {
                    let (body, result) = try_ready!(last.poll(env));
                    self.body = body;
                    return Ok(Async::Ready(result));
                },

                None => EXIT_SUCCESS,
            };

            let next_val = match self.args.next() {
                Some(n) => n,
                None => return Ok(Async::Ready(ExitResult::Ready(status))),
            };

            let has_more = self.args.peek().is_some();

            let name = if has_more {
                self.name.clone()
            } else {
                self.name.take()
            };

            let name = name.expect("polled twice");
            env.set_var(name, next_val);

            let body = mem::replace(&mut self.body, Vec::new());
            let next_state = if has_more {
                State::Init(VecSequence::new(body))
            } else {
                State::Last(VecSequenceWithLast::new(body))
            };

            self.state = Some(next_state);
        }
    }

    fn cancel(&mut self, env: &mut E) {
        self.state.as_mut().map(|state| match *state {
            State::Init(ref mut f) => f.cancel(env),
            State::Last(ref mut f) => f.cancel(env),
        });
    }
}