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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
//! This is a Rust macro that implements for comprehensions similar to
//! Scala's.  This allows  to  chain calls  to  `map`, `flat_map`  and
//! `filter` in a very clean and concise manner.
//!
//! # Example:
//!
//! ```rust
//! # #[macro_use] extern crate map_for;
//! # fn main() {
//! let l = map_for!{
//!    move;
//!    x <- 0..10;
//!    y = x/2;
//!    if (y%2) == 0;
//!    z <- 0..1;
//!    => y+z };
//! # }
//! ```
//!
//! Will be expanded to:
//!
//! ```rust
//! let l = (0..10).map (move |x| { let y = x / 2; (x, y) })
//!    .filter (move |params| { let (x, y) = *params; (y%2) == 0 })
//!    .flat_map (move |params| {
//!       let (x, y) = params;
//!       (0..1).map (move |z| { y + z }) });
//! ```
//!

/// This trait creates a `flat_map` method for `Option` (equivalent to
/// `Option::and_then`) so that it can be used in the `map_for` macro.
///
/// # Example:
///
/// ``` rust
/// # #[macro_use] extern crate map_for;
/// # fn main() {
/// use map_for::FlatMap;
/// let c = map_for!{
///    a <- Some (1);
///    b <- Some (2);
///    => a+b };
/// assert_eq!(c, Some (3));
/// # }
/// ```
pub trait FlatMap<Item> {
   type Item;
   fn flat_map<U, F> (self, f: F) -> Option<U>
      where F: FnOnce (Self::Item) -> Option<U>;
}
impl<Item> FlatMap<Item> for Option<Item> {
   type Item = Item;
   fn flat_map<U, F> (self, f: F) -> Option<U>
      where F: FnOnce (Self::Item) -> Option<U>
   { self.and_then (f) }
}

/// This trait creates a `filter` method for `Option` so that it can be
/// filtered on when used in the `map_for` macro.
///
/// # Example:
///
/// ``` rust
/// # #[macro_use] extern crate map_for;
/// # fn main() {
/// use map_for::{ Filter, FlatMap };
/// let c = map_for!{
///    a <- Some (1);
///    if (a%2) == 0;
///    b <- Some (2);
///    => { a + b } };
/// assert_eq!(c, None);
/// # }
/// ```
pub trait Filter<Item> {
   type Item;
   fn filter<P> (self, predicate: P) -> Option<Item>
      where P: FnOnce (&Self::Item) -> bool;
}
impl<Item> Filter<Item> for Option<Item> {
   type Item = Item;
   fn filter<P> (self, predicate: P) -> Option<Item>
      where P: FnOnce (&Self::Item) -> bool
   { self.and_then (|item| if predicate (&item) { Some (item) } else { None }) }
}

/// Scala-like  for  comprehension  similar   to  those  described  in
/// https://stackoverflow.com/questions/3754089/scala-for-comprehension#3754568
/// The  main difference  is that  since  rust does  not have  partial
/// functions, we  do not  support general  patterns in  the left-hand
/// sides, but only  single identifiers and list  of identifiers (that
/// will match a tuple).
///
/// The  macro will  work  for  any type  that  implements the  `map`,
/// `flat_map` and `filter` functions.
///
/// # Examples
///
/// ## Basic usage
///
/// Mappings are defined  using the `<-` operator and  the final value
/// is declared with the `=>` operator:
///
/// ``` rust
/// # #[macro_use] extern crate map_for;
/// # fn main() {
/// let l = map_for!{
///    x <- 0..4;
///    y <- 0..x;
///    => y
///    // y will take the following values depending on x:
///    // x == 0 -> empty
///    // x == 1 -> 0
///    // x == 2 -> 0, 1
///    // x == 3 -> 0, 1, 2
/// }.collect::<Vec<_>>();
/// assert_eq!(l, vec![ 0, 0, 1, 0, 1, 2 ]);
/// # }
/// ```
///
/// ## Moving or borrowing
///
/// By default, the generated  closures will borrow their environment.
/// If you'd prefer  the environment to be moved  inside the closures,
/// you can specify  `move;` as the first statement  (the semicolon is
/// here to  make it clear that  this will be applied  globally to all
/// the closures generated by the macro).
///
/// ```rust
/// # #[macro_use] extern crate map_for;
/// # fn main() {
/// let l = map_for!{
///    move;    // Only for illustration, not strictly necessary here
///    x <- 0..4;
///    => x
/// }.collect::<Vec<_>>();
/// assert_eq!(l, vec![ 0, 1, 2, 3 ]);
/// # }
/// ```
///
/// ## Regular binding
///
/// Regular bindings (i.e.  direct bindings that don't  require a call
/// to `map` or `flat_map`) can  be inserted between mappings by using
/// the `=` operator:
///
/// ``` rust
/// # #[macro_use] extern crate map_for;
/// # fn main() {
/// let l = map_for!{
///    move;
///    x <- 0..4;
///    y = 2*x;     // This is directly translated into `let y = 2*x;`
///                 // without going through a mapping function.
///    z <- 0..1;
///    => y+z
/// }.collect::<Vec<_>>();
/// assert_eq!(l, vec![ 0, 2, 4, 6 ]);
/// # }
/// ```
///
/// ## Tuple deconstruction
///
/// A  limited form  of pattern-matching  is available  to deconstruct
/// single-level tuples:
///
/// ``` rust
/// # #[macro_use] extern crate map_for;
/// # fn main() {
/// use map_for::FlatMap;   // Required to use an `Option`
/// let e = map_for!{
///    (a, b) <- Some ((1, 2));
///    (c, d) = (3, 4);
///    => a+b+c+d };
/// assert_eq!(e, Some (10));
/// # }
/// ```
///
/// ## Filtering
///
/// Mappings can be filtered using an `if` statement:
///
/// ``` rust
/// # #[macro_use] extern crate map_for;
/// # fn main() {
/// let l = map_for!{
///    x <- 0..10;
///    if (x%2) == 0;
///    => x }.collect::<Vec<_>>();
/// assert_eq!(l, vec![ 0, 2, 4, 6, 8 ]);
/// # }
/// ```
///
/// ## Custom types
///
/// Except  for filtering,  `map_for`  will work  with  any type  that
/// defines  `map`  and  `flat_map`  either  directly  or  because  it
/// implements a trait that defines those fuctions. Moreover filtering
/// will work with any type that also defines a `filter` function:
///
/// ``` rust
/// # #[macro_use] extern crate map_for;
/// #[derive (Debug, PartialEq)]
/// enum MyMonad {
///    Empty,
///    Value (i32),
/// }
/// impl MyMonad {
///    fn flat_map<F> (self, f: F) -> Self
///       where F: FnOnce (i32) -> Self
///    {
///       use MyMonad::*;
///       match self {
///          Empty => Empty,
///          Value (x) => f (x),
///       }
///    }
///
///    fn map<F> (self, f: F) -> Self
///       where F: FnOnce (i32) -> i32
///    {
///       use MyMonad::*;
///       match self {
///          Empty => Empty,
///          Value (x) => Value (f (x)),
///       }
///    }
///
///    fn filter<P> (self, p: P) -> Self
///       where P: FnOnce (i32) -> bool
///    {    // Only required to enable the `if` statement in `map_for`
///       use MyMonad::*;
///       match self {
///          Value (x) if p (x) => self,
///          _ => Empty,
///       }
///    }
/// }
/// # fn main() {
/// use MyMonad::*;
/// let c = map_for!{
///    a <- Value (1);
///    if (a == 1);
///    b <- Value (2);
///    => a+b };
/// assert_eq!(c, Value (3));
/// # }
/// ```
#[macro_export]
macro_rules! map_for {
   // Process tuple patterns. Note that this must come first due to
   // rust issue #27832.
   (@process ($($move:tt)*) ($($n:ident),+) <- $e:expr; => $e0:expr) => (
      $e.map ($($move)* |params| {
         #[allow(unused_variables)] let ($($n),+) = params;
         $e0 }));
   (@process ($($move:tt)*) ($($n:ident),+) <- $e:expr; if $g:expr; $($tail:tt)+) => (
      map_for! {
         @process ($($move)*)
         ($($n),+) <- $e.filter ($($move)* |params| {
            #[allow(unused_variables)] let ($($n),+) = *params;
            $g });
         $($tail)+ });
   (@process ($($move:tt)*) ($($n:ident),+) <- $e:expr; ($($n0:ident),+) <- $e0:expr; $($tail:tt)+) => (
      $e.flat_map ($($move)* |params| {
         #[allow(unused_variables)] let ($($n),+) = params;
         map_for!{ @process ($($move)*) ($($n0),+) <- $e0; $($tail)+ } }));
   (@process ($($move:tt)*) ($($n:ident),+) <- $e:expr; ($($n0:ident),+) = $e0:expr; $($tail:tt)+) => (
      map_for!{
         @process ($($move)*)
         ($($n),+, $($n0),+) <- map_for!{
            @process ($($move)*)
            ($($n),+) <- $e; => {
               let ($($n0),+) = $e0; ($($n),+, $($n0),+) } };
         $($tail)+ });
   (@process ($($move:tt)*) ($($n:ident),+) <- $e:expr; $n0:ident <- $e0:expr; $($tail:tt)+) => (
      $e.flat_map ($($move)* |params| {
         #[allow(unused_variables)] let ($($n),+) = params;
         map_for!{ @process ($($move)*) $n0 <- $e0; $($tail)+ } }));
   (@process ($($move:tt)*) ($($n:ident),+) <- $e:expr; $n0:ident = $e0:expr; $($tail:tt)+) => (
      map_for!{
         @process ($($move)*)
         ($($n),+, $n0) <- map_for!{
            @process ($($move)*)
            ($($n),+) <- $e; => {
               let $n0 = $e0; ($($n),+, $n0) } };
         $($tail)+ });

   // Process single-identifier patterns.
   (@process ($($move:tt)*) $n:ident <- $e:expr; => $e0:expr) => ($e.map ($($move)* |$n| { $e0 }));
   (@process ($($move:tt)*) $n:ident <- $e:expr; if $g:expr; $($tail:tt)+) => (
      map_for! { @process ($($move)*) $n <- $e.filter ($($move)* |$n| { $g }); $($tail)+ });
   (@process ($($move:tt)*) $n:ident <- $e:expr; ($($n0:ident),+) <- $e0:expr; $($tail:tt)+) => (
      $e.flat_map ($($move)* |$n| { map_for!{ @process ($($move)*) ($($n0),+) <- $e0; $($tail)+ } }));
   (@process ($($move:tt)*) $n:ident <- $e:expr; ($($n0:ident),+) = $e0:expr; $($tail:tt)+) => (
      map_for!{
         @process ($($move)*)
         ($n, $($n0),+) <- map_for!{
            @process ($($move)*)
            $n <- $e; => {
               let ($($n0),+) = $e0; ($n, $($n0),+) } };
         $($tail)+ });
   (@process ($($move:tt)*) $n:ident <- $e:expr; $n0:ident <- $e0:expr; $($tail:tt)+) => (
      $e.flat_map ($($move)* |$n| { map_for!{ @process ($($move)*) $n0 <- $e0; $($tail)+ } }));
   (@process ($($move:tt)*) $n:ident <- $e:expr; $n0:ident = $e0:expr; $($tail:tt)+) => (
      map_for!{
         @process ($($move)*)
         ($n, $n0) <- map_for!{
            @process ($($move)*)
            $n <- $e; => {
               let $n0 = $e0; ($n, $n0) } };
         $($tail)+ });

   // Start
   (move; $($tail:tt)+) => (map_for!(@process (move) $($tail)+));
   ($($tail:tt)+)      => (map_for!(@process () $($tail)+));
}

#[cfg(test)]
mod tests {
   use super::*;

   #[test]
   fn tuple() {
      let c = map_for!{
         (a, b) <- Some ((1, 2));
         => a + b };
      assert_eq!(c, Some (3));
      let e = map_for!{         // Issue #2
         (a, b) <- Some ((1, 2));
         (c, d) = (3, 4);
         => a+b+c+d };
      assert_eq!(e, Some (10));
   }

   #[test]
   fn option() {
      let c = map_for!{
         a <- Some (1);
         b <- Some (2);
         => { a + b } };
      assert_eq!(c, Some (3));
   }

   #[test]
   fn range() {
      let l = map_for!{
         x <- 0..4;
         y <- 0..x;
         => y
         // x == 0 -> empty
         // x == 1 -> 0
         // x == 2 -> 0, 1
         // x == 3 -> 0, 1, 2
      }.collect::<Vec<_>>();
      assert_eq!(l, vec![ 0, 0, 1, 0, 1, 2 ]);
   }

   #[test]
   fn capture() {
      let count = 3;
      let offset = 2;
      let l = map_for!{
         move;
         x <- 0..4;
         y <- 0..count;
         => x + y + offset
      }.collect::<Vec<_>>();
      assert_eq!(l, vec![ 2, 3, 4,
                          3, 4, 5,
                          4, 5, 6,
                          5, 6, 7 ]);
   }

   #[test]
   fn regular_binding() {
      let l = map_for!{
         move;
         x <- 0..4;
         y = 2*x;
         z <- 0..1;
         => y+z
      }.collect::<Vec<_>>();
      assert_eq!(l, vec![ 0, 2, 4, 6 ]);
   }

   #[test]
   fn filtering() {
      let l = map_for!{
         x <- 0..10;
         if (x%2) == 0;
         => x }.collect::<Vec<_>>();
      assert_eq!(l, vec![ 0, 2, 4, 6, 8 ]);

      let l = map_for!{
         x <- 0..10;
         y = x/2;
         if (y%2) == 0;
         => y }.collect::<Vec<_>>();
      assert_eq!(l, vec![0, 0, 2, 2, 4, 4]);
   }

   #[test]
   fn filtering_options() {
      let c = map_for!{
         a <- Some (1);
         b <- Some (2);
         if (b%2) == 0;
         => { a + b } };
      assert_eq!(c, Some (3));
      let c = map_for!{
         a <- Some (1);
         if (a%2) == 0;
         b <- Some (2);
         => { a + b } };
      assert_eq!(c, None);
   }

   #[test]
   fn filtering_borrow() {
      struct Checker {}
      impl Checker {
         fn check (&self, txt: &str) -> bool { txt.len() > 1 }
      }
      let c = Checker{};

      struct MyIter(std::ops::Range<usize>);
      impl std::iter::Iterator for MyIter {
         type Item = Result<String, ()>;
         fn next (&mut self) -> Option<Self::Item> {
            self.0.next().map (|i| Ok (format!("{}", i))) }
      }

      let l = map_for!{
         result <- MyIter (5..15);
         text   <- result.into_iter();
         if c.check (text);
         => text }.collect::<Vec<_>>();
      assert_eq!(l, vec![ "10", "11", "12", "13", "14" ]);
   }

   #[test]
   fn mixed_modes() {           // Issue #1
      let e = map_for!{
         a <- Some (1);
         (b, c) <- Some ((2, 3));
         d <- Some (4);
         => a+b+c+d };
      assert_eq!(e, Some (10));
      let e = map_for!{
         a <- Some (1);
         (b, c) = (2, 3);
         d = 4;
         => a+b+c+d };
      assert_eq!(e, Some (10));
   }
}