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
use {EXIT_ERROR, EXIT_SUCCESS, Spawn};
use error::IsFatalError;
use env::{LastStatusEnvironment, ReportErrorEnvironment, StringWrapper};
use eval::{Pattern, TildeExpansion, WordEval, WordEvalConfig};
use future::{Async, EnvFuture, Poll};
use glob::MatchOptions;
use spawn::{ExitResult, Sequence, sequence};
use std::fmt;
use std::mem;

/// A grouping of patterns and body commands.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct PatternBodyPair<W, C> {
    /// Pattern alternatives to match against.
    pub patterns: W,
    /// The body commands to execute if the pattern matches.
    pub body: C,
}

/// Spawns a `Case` commands from a word to match number of case arms.
///
/// First the provided `word` will be evaluated and compared to each
/// pattern of each case arm. The first arm which contains a pattern that
/// matches the `word` will have its (and only its) body evaluated.
///
/// If no arms are matched, the `case` command will exit successfully.
pub fn case<IA, IW, IS, E: ?Sized>(word: IW::Item, arms: IA) -> Case<IA::IntoIter, IW, IS, E>
    where IA: IntoIterator<Item = PatternBodyPair<IW, IS>>,
          IW: IntoIterator,
          IW::Item: WordEval<E>,
          IS: IntoIterator,
          IS::Item: Spawn<E>,
{
    Case {
        state: State::Init(Some(word), Some(arms.into_iter())),
    }
}

/// A future representing the execution of a `case` command.
#[must_use = "futures do nothing unless polled"]
pub struct Case<IA, IW, IS, E: ?Sized>
    where IW: IntoIterator,
          IW::Item: WordEval<E>,
          IS: IntoIterator,
          IS::Item: Spawn<E>,
{
    state: State<IA, IW, IS, E>,
}

impl<W, S, IA, IW, IS, E: ?Sized> fmt::Debug for Case<IA, IW, IS, E>
    where IA: fmt::Debug,
          IW: IntoIterator<Item = W> + fmt::Debug,
          IW::IntoIter: fmt::Debug,
          W: WordEval<E> + fmt::Debug,
          W::EvalResult: fmt::Debug,
          W::EvalFuture: fmt::Debug,
          IS: IntoIterator<Item = S> + fmt::Debug,
          IS::IntoIter: fmt::Debug,
          S: Spawn<E> + fmt::Debug,
          S::EnvFuture: fmt::Debug,
          S::Future: fmt::Debug,
{
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.debug_struct("Case")
            .field("state", &self.state)
            .finish()
    }
}

enum State<IA, IW, IS, E: ?Sized>
    where IW: IntoIterator,
          IW::Item: WordEval<E>,
          IS: IntoIterator,
          IS::Item: Spawn<E>,
{
    Init(Option<IW::Item>, Option<IA>),
    Word(<IW::Item as WordEval<E>>::EvalFuture, Option<IA>),
    Cases(Arm<IW::IntoIter, IS, E>, IA),
    Body(Sequence<IS::IntoIter, E>),
}

impl<W, S, IA, IW, IS, E: ?Sized> fmt::Debug for State<IA, IW, IS, E>
    where IA: fmt::Debug,
          IW: IntoIterator<Item = W> + fmt::Debug,
          IW::IntoIter: fmt::Debug,
          W: WordEval<E> + fmt::Debug,
          W::EvalResult: fmt::Debug,
          W::EvalFuture: fmt::Debug,
          IS: IntoIterator<Item = S> + fmt::Debug,
          IS::IntoIter: fmt::Debug,
          S: Spawn<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 word, ref arms) => {
                fmt.debug_tuple("State::Init")
                    .field(word)
                    .field(arms)
                    .finish()
            },
            State::Word(ref word, ref arms) => {
                fmt.debug_tuple("State::Word")
                    .field(word)
                    .field(arms)
                    .finish()
            },
            State::Cases(ref current, ref arms) => {
                fmt.debug_tuple("State::Cases")
                    .field(current)
                    .field(arms)
                    .finish()
            },
            State::Body(ref b) => {
                fmt.debug_tuple("State::Body")
                    .field(b)
                    .finish()
            },
        }
    }
}

macro_rules! next_arm {
    ($word:expr, $arms:expr) => {{
        match $arms.next() {
            None => return Ok(Async::Ready(ExitResult::Ready(EXIT_SUCCESS))),
            Some(pair) => Arm {
                word: $word,
                current: None,
                pats: pair.patterns.into_iter(),
                body: Some(pair.body)
            },
        }
    }}
}

impl<W, S, IA, IW, IS, E: ?Sized> EnvFuture<E> for Case<IA, IW, IS, E>
    where IA: Iterator<Item = PatternBodyPair<IW, IS>>,
          IW: IntoIterator<Item = W>,
          W: WordEval<E>,
          W::Error: IsFatalError,
          IS: IntoIterator<Item = S>,
          S: Spawn<E>,
          S::Error: From<W::Error> + IsFatalError,
          E: LastStatusEnvironment + ReportErrorEnvironment,
{
    type Item = ExitResult<S::Future>;
    type Error = S::Error;

    fn poll(&mut self, env: &mut E) -> Poll<Self::Item, Self::Error> {
        loop {
            let next_state = match self.state {
                State::Init(ref mut word, ref mut arms) => {
                    let cfg = WordEvalConfig {
                        tilde_expansion: TildeExpansion::First,
                        split_fields_further: false,
                    };

                    let word = word.take().expect("polled twice").eval_with_config(env, cfg);
                    State::Word(word, arms.take())
                },

                State::Word(ref mut word, ref mut arms) => {
                    let word = match word.poll(env) {
                        Ok(Async::Ready(word)) => word.join().into_owned(),
                        Ok(Async::NotReady) => return Ok(Async::NotReady),
                        Err(e) => {
                            env.set_last_status(EXIT_ERROR);
                            return Err(e.into());
                        },
                    };

                    let mut arms = arms.take().expect("polled twice");
                    let current = next_arm!(word, arms);

                    State::Cases(current, arms)
                },

                State::Cases(ref mut current, ref mut arms) => {
                    match try_ready!(current.poll(env)) {
                        (_, Some(body)) => State::Body(sequence(body)),

                        (word, None) => {
                            *current = next_arm!(word, arms);
                            continue;
                        },
                    }
                },

                State::Body(ref mut f) => return f.poll(env),
            };

            self.state = next_state;
        }
    }

    fn cancel(&mut self, env: &mut E) {
        match self.state {
            State::Init(_, _) => {},
            State::Word(ref mut word, _) => word.cancel(env),
            State::Cases(ref mut current, _) => current.cancel(env),
            State::Body(ref mut f) => f.cancel(env),
        }
    }
}

/// A future which represents the resolution of an arm in a `Case` command.
///
/// Each of the provided patterns will be evaluated evaluated one by one
/// and matched against the provided word. If any pattern matches, the arm's
/// body will be immediately yielded for the caller to execute. Else, if no
/// patterns match, then the future will resolve to nothing.
#[must_use = "futures do nothing unless polled"]
struct Arm<I, B, E: ?Sized>
    where I: Iterator,
          I::Item: WordEval<E>,
{
    word: String,
    current: Option<Pattern<<I::Item as WordEval<E>>::EvalFuture>>,
    pats: I,
    body: Option<B>,
}

impl<W, I, B, E: ?Sized> fmt::Debug for Arm<I, B, E>
    where I: Iterator<Item = W> + fmt::Debug,
          W: WordEval<E> + fmt::Debug,
          W::EvalFuture: fmt::Debug,
          B: fmt::Debug,
{
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.debug_struct("Arm")
            .field("word", &self.word)
            .field("current", &self.current)
            .field("pats", &self.pats)
            .field("body", &self.body)
            .finish()
    }
}

impl<W, I, B, E: ?Sized> EnvFuture<E> for Arm<I, B, E>
    where I: Iterator<Item = W>,
          W: WordEval<E>,
          W::Error: IsFatalError,
          E: ReportErrorEnvironment,
{
    type Item = (String, Option<B>);
    type Error = W::Error;

    fn poll(&mut self, env: &mut E) -> Poll<Self::Item, Self::Error> {
        loop {
            if self.current.is_none() {
                self.current = self.pats.next().map(|p| p.eval_as_pattern(env));
            }

            let pat = match self.current.as_mut() {
                Some(ref mut f) => match f.poll(env) {
                    Ok(Async::Ready(pat)) => Some(pat),
                    Ok(Async::NotReady) => return Ok(Async::NotReady),
                    Err(e) => {
                        if e.is_fatal() {
                            return Err(e);
                        } else {
                            env.report_error(&e);
                            None
                        }
                    },
                },

                None => {
                    let word = mem::replace(&mut self.word, String::new());
                    return Ok(Async::Ready((word, None)));
                },
            };

            self.current.take(); // Future has resolved, ensure we don't poll again

            if let Some(pat) = pat {
                let match_opts = MatchOptions {
                    case_sensitive: true,
                    require_literal_separator: false,
                    require_literal_leading_dot: false,
                };

                if pat.matches_with(&self.word, &match_opts) {
                    assert!(self.body.is_some(), "polled twice");
                    let word = mem::replace(&mut self.word, String::new());
                    return Ok(Async::Ready((word, self.body.take())));
                }
            }
        }
    }

    fn cancel(&mut self, env: &mut E) {
        self.current.as_mut().map(|f| f.cancel(env));
    }
}