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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
//! This module holds [`NoCommentIter`](::nocommentiter::NoCommentIter), the
//! central datastructure for the folding functionality of nvimpam.
//!
//! It returns enumerated Lines, but skips Comments (lines starting with `$` or
//! `#`). All skip functions, used by
//! [`add_folds`](::folds::FoldList::add_folds), work on a
//! [`NoCommentIter`](::nocommentiter::NoCommentIter).
use std::default::Default;

use card::{
  ges::GesType,
  keyword::Keyword,
  line::{CondResult, Line as CardLine},
  Card,
};
use lines::{KeywordLine, ParsedLine};
use skipresult::SkipResult;

// Used in skip functions. Returns the next `ParsedLine` from the iterator. If
// theres no next line, return a `SkipResult` containing the line number of
// `prevline` and nothing else.
macro_rules! next_or_return_previdx {
  ($self:ident, $previdx:expr) => {
    match $self.next() {
      None => {
        return SkipResult {
          skip_end: $previdx,
          ..Default::default()
        }
      }
      Some(t) => t,
    };
  };
}

// Used in skip_ges to get the next line. If it's None, we're at the end of
// the file and only return what we found before. Also used in `advance_some!`
macro_rules! next_or_return_some_previdx {
  ($self:ident, $previdx:expr) => {
    match $self.next() {
      None => {
        return Some(SkipResult {
          skip_end: $previdx,
          ..Default::default()
        })
      }
      Some(t) => t,
    };
  };
}

// In the same veins as above, get the next line from the iterator, or return
// None from the function.
macro_rules! next_or_return_none {
  ($self:ident) => {
    match $self.next() {
      None => return None,
      Some(t) => t,
    };
  };
}

// A common pattern for nocommentiter: Save Some(nextline) in prevline,
// and advance the iterator. Save in nextline, or return a SkipResult built
// from prevline's line number
macro_rules! advance {
  ($self:ident, $previdx:ident, $nextline:ident) => {
    $previdx = Some($nextline.number);
    $nextline = next_or_return_previdx!($self, $previdx);
  };
}

// Same as advance above, just that the `SkipResult` is wrapped in `Some`. Used
// in skip_ges.
macro_rules! advance_some {
  ($self:ident, $previdx:ident, $nextline:ident) => {
    $previdx = Some($nextline.number);
    $nextline = next_or_return_some_previdx!($self, $previdx);
  };
}

/// Designates that the comments have been removed.
pub trait CommentLess {
  fn remove_comments(self) -> NoCommentIter<Self>
  where
    Self: Sized;
}

/// The struct simply holds a type instance. Skipping comments is done in the
/// Iterator implementation.
pub struct NoCommentIter<I> {
  pub it: I,
}

impl<'a, I> Iterator for NoCommentIter<I>
where
  I: Iterator<Item = ParsedLine<'a>>,
{
  type Item = ParsedLine<'a>;

  fn next(&mut self) -> Option<Self::Item> {
    while let Some(pl) = self.it.next() {
      if pl.keyword != Some(&Keyword::Comment) {
        return Some(pl);
      }
    }
    None
  }
}

impl<'a, I> CommentLess for I
where
  I: Iterator<Item = ParsedLine<'a>>,
{
  fn remove_comments(self) -> NoCommentIter<I> {
    NoCommentIter { it: self }
  }
}

impl<'a, I> NoCommentIter<I>
where
  I: Iterator<Item = ParsedLine<'a>>,
{
  /// Advance the iterator until meeting the first line with a keyword. If the
  /// file ends before that, return `None`.
  pub fn skip_to_next_keyword<'b>(&'b mut self) -> Option<KeywordLine<'a>> {
    let mut line = None;

    while line.is_none() {
      line = next_or_return_none!(self).try_into_keywordline();
    }

    line
  }

  /// Advance the iterator until the first line after a General Entity
  /// Selection (GES).
  ///
  /// Returns `None` if skipline neither ends the GES, nor is
  /// contained in it. We did not try to advance the iterator in this case.
  /// Returns `Some(Default::default())` if `skipline` ends the GES, and the
  /// file ends after that.
  pub fn skip_ges<'b>(
    &'b mut self,
    ges: GesType,
    skipline: &ParsedLine<'a>,
  ) -> Option<SkipResult<'a>> {
    let mut previdx: Option<usize> = None;
    let mut nextline: ParsedLine<'a>;

    let contained = ges.contains(skipline.text);
    let ends = ges.ended_by(skipline.text);

    if ends {
      nextline = next_or_return_some_previdx!(self, previdx);
      Some(SkipResult {
        nextline: Some(nextline),
        skip_end: Some(skipline.number),
      })
    } else if !ends && !contained {
      None
    } else {
      nextline = next_or_return_some_previdx!(self, Some(skipline.number));

      while ges.contains(nextline.text) {
        advance_some!(self, previdx, nextline);
      }

      if ges.ended_by(nextline.text) {
        advance_some!(self, previdx, nextline);
      }

      Some(SkipResult {
        nextline: Some(nextline),
        skip_end: previdx,
      })
    }
  }

  /// A wrapper around [`skip_card`](NoCommentIter::skip_card) and
  /// [`skip_card_gather`](NoCommentIter::skip_card_gather), dispatching by
  /// value of [`Card.ownfold`](::card::Card::ownfold)
  pub fn skip_fold<'b>(
    &'b mut self,
    skipline: KeywordLine<'a>,
  ) -> SkipResult<'a> {
    let card: &Card = skipline.keyword.into();

    if card.ownfold {
      self.skip_card(skipline, card)
    } else {
      self.skip_card_gather(skipline, card)
    }
  }

  /// Let [`NoCommentIter`](NoCommentIter) skip the given
  /// [`Card`](::card::Card), but only skip this 1 card. This only really makes
  /// sense when the last line the iterator returned is the line with the
  /// keyword starting that card, which is passed as `skipline`.
  ///
  /// If you want to skip all cards of a given type, use
  /// [`skip_card_gather`](NoCommentIter::skip_card_gather)
  pub fn skip_card<'b>(
    &'b mut self,
    skipline: KeywordLine<'a>,
    card: &Card,
  ) -> SkipResult<'a> {
    let mut conds: Vec<CondResult> = vec![]; // the vec to hold the conditionals
    let mut cardlines = card.lines.iter();
    let cardline = cardlines.next().unwrap_or_else(|| unreachable!());

    if let CardLine::Provides(_s, ref c) = cardline {
      conds.push(c.evaluate(skipline.text));
    }

    let mut previdx: Option<usize> = None;
    let mut nextline = next_or_return_previdx!(self, previdx);

    for cardline in cardlines {
      if nextline.keyword.is_some() {
        break;
      }

      match *cardline {
        CardLine::Provides(_s, ref c) => {
          conds.push(c.evaluate(&nextline.text));
          advance!(self, previdx, nextline);
        }
        CardLine::Ges(ref g) => {
          if let Some(sr) = self.skip_ges(*g, &nextline) {
            match sr.nextline {
              None => return sr,
              Some(pl) => {
                previdx = sr.skip_end;
                nextline = pl;
              }
            };
          }
        }
        CardLine::Cells(_s) => {
          advance!(self, previdx, nextline);
        }
        CardLine::Optional(_s, i) => {
          if conds.get(i as usize) == Some(&CondResult::Bool(true)) {
            advance!(self, previdx, nextline);
          } else {
            continue;
          }
        }
        CardLine::Repeat(_s, i) => {
          let num = match conds.get(i as usize) {
            Some(CondResult::Number(Some(u))) if *u > 0 => u,
            _ => continue,
          };

          // We need one more loop than *num because we need to get the next
          // line for the next outer iteration
          for _ in 0..*num {
            advance!(self, previdx, nextline);

            if nextline.keyword.is_some() {
              break;
            }
          }
        }
        CardLine::Block(_l, s) => loop {
          while !nextline.text.as_ref().starts_with(s) {
            advance!(self, previdx, nextline);

            if nextline.keyword.is_some() {
              break;
            }
          }
          advance!(self, previdx, nextline);
        },
        CardLine::OptionalBlock(s1, s2) => {
          if !nextline.text.as_ref().starts_with(s1) {
            continue;
          }
          while !nextline.text.as_ref().starts_with(s2) {
            advance!(self, previdx, nextline);

            if nextline.keyword.is_some() {
              break;
            }
          }
        }
      }
    }
    SkipResult {
      nextline: Some(nextline),
      skip_end: previdx.or_else(|| Some(skipline.number)),
    }
  }

  /// Let [`NoCommentIter`](NoCommentIter) skip all given
  /// [`Card`](::card::Card)s, until the next card starts. The basic assumption
  /// is that the last line the iterator returned is a the first line of a card
  /// of the given type, which is passed as `skipline`.
  pub fn skip_card_gather<'b>(
    &'b mut self,
    skipline: KeywordLine<'a>,
    card: &Card,
  ) -> SkipResult<'a> {
    let mut res = self.skip_card(skipline, card);

    #[cfg_attr(rustfmt, rustfmt_skip)]
    loop {
      if let Some(ParsedLine{keyword: Some(k),number,text}) = res.nextline {
        if *k == card.keyword {
          res = self.skip_card(KeywordLine{keyword: k,number: number, text}, card);
          continue;
        }
      }
      return res;
    }
  }
}

#[cfg(test)]
mod tests {
  use card::{
    ges::GesType::GesNode,
    keyword::Keyword::{self, *},
  };
  use carddata::*;
  use lines::{KeywordLine, Lines, ParsedLine};
  use nocommentiter::{CommentLess, NoCommentIter};

  macro_rules! pline {
    ($number:expr, $text:expr, $keyword:expr) => {
      ParsedLine {
        number: $number,
        text: $text.as_ref(),
        keyword: $keyword,
      }
    };
  }

  macro_rules! kwline {
    ($number:expr, $text:expr, $keyword:expr) => {
      KeywordLine {
        number: $number,
        text: $text,
        keyword: $keyword,
      }
    };
  }

  macro_rules! make_lineiter {
    ($lines:ident, $keywords:ident, $li: ident, $str:expr) => {
      $lines = Lines::from_slice($str.as_ref());
      $keywords = $lines
        .iter()
        .map(Keyword::parse)
        .collect::<Vec<Option<Keyword>>>();
      $li = $keywords
        .iter()
        .zip($lines.iter())
        .enumerate()
        .map(ParsedLine::from)
        .remove_comments()
    };
  }

  macro_rules! make_test {
    ($name: ident, $strs: expr, $({$f:expr, $e:expr});+) => {
      #[test]
      fn $name() {
        let lines;
        let keywords;
        let mut li;
        make_lineiter!(lines, keywords, li, $strs);
        $( assert_eq!($f(&mut li), $e) );+
      }
    };
  }

  fn next_kw<'a, I>(l: &mut NoCommentIter<I>) -> Option<KeywordLine<'a>>
  where
    I: Iterator<Item = ParsedLine<'a>>,
  {
    l.skip_to_next_keyword()
  }

  fn next_nocom<'a, I>(l: &mut NoCommentIter<I>) -> Option<ParsedLine<'a>>
  where
    I: Iterator<Item = ParsedLine<'a>>,
  {
    l.next()
  }

  const COMMENTS: &'static str = "#This\n$is\n#an\n#example\nof\nsome\
                                  \nlines\n.";

  make_test!(
    works_with_slice,
    COMMENTS,
    { next_nocom, Some(pline!(4, "of", None)) };
    { next_nocom, Some(pline!(5, "some", None))}
  );

  const KEYWORD_LINES: &'static str = "#Comment\n   nokeyword\nNODE  / \
                                       \n#example\nNSMAS / \nsome\nlines\n.";

  make_test!(
    needs_no_keywords,
    KEYWORD_LINES,
    {|l: &mut NoCommentIter<_>| {
        let _ = l.next();
        let _ = l.next();
        let _ = l.next();
        let _ = l.next();
        l.skip_to_next_keyword()
      },
      None
    }
  );

  make_test!(
    finds_real_keywords,
    KEYWORD_LINES,
    { next_kw, Some(kwline!(2, b"NODE  / ", &Node)) };
    { next_kw, Some(kwline!(4, b"NSMAS / ", &Nsmas)) };
    { next_kw, None };
    { next_nocom, None }
  );

  const GES1: &'static str = "        PART 1234\
                              \n        OGRP 'hausbau'\
                              \n        DELGRP>NOD 'nix'\
                              \n        END\
                              \nNODE  / ";

  make_test!(
    can_skip_ges,
    GES1,
    {|l: &mut NoCommentIter<_>| {
        let nextline = l.next().unwrap();
        let tmp = l.skip_ges(GesNode, &nextline).unwrap();
        assert_eq!(tmp.nextline.unwrap(), pline!(4, b"NODE  / ", Some(&Node)));
        assert_eq!(tmp.skip_end, Some(3));
        l.next()
      }, None
    }
  );

  const GES2: &'static str = "        PART 1234\
                              \n        OGRP 'hausbau'\
                              \n        END\
                              \n        DELGRP>NOD 'nix'\
                              \n        MOD 10234\
                              \n        NOD 1 23 093402 82\
                              \n        END_MOD\
                              \n        DELELE 12\
                              \n        END";

  const GES2_NEXT: &[u8] = b"        DELGRP>NOD 'nix'";

  make_test!(
    can_skip_ges_repeatedly,
    GES2,
    {|l:  &mut NoCommentIter<_>| {
        let mut nextline = l.next().unwrap();
        let mut tmp = l.skip_ges(GesNode, &nextline).unwrap();
        assert_eq!(tmp.nextline.unwrap(), pline!(3, GES2_NEXT, None));
        assert_eq!(tmp.skip_end, Some(2));

        nextline = l.next().unwrap();
        tmp = l.skip_ges(GesNode, &nextline).unwrap();
        assert_eq!(tmp.nextline, None);
        assert_eq!(tmp.skip_end, Some(8));
        l.next()
      }, None
    }
  );

  const GES3: &'static str = "        PART 1234\
                              \n        OGRP 'hausbau'\
                              \nNODE  /         END\
                              \n        DELGRP>NOD 'nix'\
                              \n        MOD 10234\
                              \n        NOD 1 23 093402 82\
                              \n        END_MOD\
                              \nWhatever\
                              \n        END";

  const GES3_FIRST: &'static str = "NODE  /         END";
  const GES3_SECOND: &'static str = "Whatever";
  const GES3_LAST: &'static str = "        END";

  make_test!(
    ends_ges_without_end,
    GES3,
    {|l: &mut NoCommentIter<_>| {
        let mut nextline = l.next().unwrap();
        let mut tmp = l.skip_ges(GesNode, &nextline).unwrap();
        assert_eq!(tmp.nextline.unwrap(), pline!(2, GES3_FIRST, Some(&Node)));
        assert_eq!(tmp.skip_end, Some(1));

        nextline = l.next().unwrap();
        tmp = l.skip_ges(GesNode, &nextline).unwrap();
        assert_eq!(tmp.nextline.unwrap(), pline!(7, GES3_SECOND, None));
        assert_eq!(tmp.skip_end, Some(6));
        l.next()
      }, Some(pline!(8, GES3_LAST, None))
    }
  );

  const GES4: &'static str = "wupdiwup\nNODE  / ";
  const GES4_LAST: &'static str = "NODE  / ";

  make_test!(
    can_skip_empty_ges,
    GES4,
    {|l: &mut NoCommentIter<_>| {
        let nextline = l.next().unwrap();
        let tmp = l.skip_ges(GesNode, &nextline);
        assert!(tmp.is_none());
        l.next().unwrap()
      }, pline!(1, GES4_LAST, Some(&Node))
    }
  );

  const GES5: &'static str = "        PART 1234\
                              \n#Comment here\
                              \n        OGRP 'hausbau'\
                              \n        DELGRP>NOD 'nix'\
                              \n        END\
                              \n$Another comment\
                              \nNODE  / ";

  const GES5_NEXTL: &'static str = "NODE  / ";

  make_test!(
    ges_works_with_comments,
    GES5,
    {|l: &mut NoCommentIter<_>| {
        let nextline = l.next().unwrap();
        let tmp = l.skip_ges(GesNode, &nextline).unwrap();
        assert_eq!(tmp.nextline.unwrap(), pline!(6, GES5_NEXTL, Some(&Node)));
        assert_eq!(tmp.skip_end, Some(4));
        l.next()
      }, None
    }
 );

  const GES6: &'static str = "        PART 1234\
                              \n#Comment here\
                              \n$Another comment\
                              \n#NODE  / ";

  make_test!(
    ges_skips_comments_after_end,
    GES6,
    {|l: &mut NoCommentIter<_>| {
        let nextline = l.next().unwrap();
        let tmp = l.skip_ges(GesNode, &nextline).unwrap();
        assert_eq!(tmp.nextline, None);
        assert_eq!(tmp.skip_end, Some(0));
        l.next()
      }, None
    }
  );

  const CARD_MASS_INCOMPLETE: &'static str =
    "$ MASS Card\
    \n$#         IDNOD    IFRA   Blank            DISr            DISs            DISt\
    \nMASS  /        0       0                                                        \
    \n$#                                                                         TITLE\
    \nNAME MASS  / ->1                                                                \
    \n$# BLANK              Mx              My              Mz\
    \n$# BLANK              Ix              Iy              Iz                   Blank\
    \nNODE  /      \
    \n                                                        ";

  make_test!(
    skip_incomplete_cards,
    CARD_MASS_INCOMPLETE,
    {|l: &mut NoCommentIter<_>| {
        let firstline = l.next().unwrap();
        let tmp = l.skip_card(firstline.try_into_keywordline().unwrap(), &MASS);
        assert_eq!(
          tmp.nextline.unwrap(),
          pline!(7, &"NODE  /      ", Some(&Node))
        );
        tmp.skip_end
      }, Some(4)
    }
  );

  const LINES_GATHER: [&'static str; 20] = [
    /* 0 */
    "NODE  /        1              0.             0.5              0.",
    /* 1 */
    "NODE  /        1              0.             0.5              0.",
    /* 2 */
    "NODE  /        1              0.             0.5              0.",
    /* 3 */
    "NODE  /        1              0.             0.5              0.",
    /* 4 */
    "#Comment here",
    /* 5 */
    "SHELL /     3129       1       1    2967    2971    2970",
    /* 6 */
    "invalid line here",
    /* 7 */
    "SHELL /     3129       1       1    2967    2971    2970",
    /* 8 */
    "SHELL /     3129       1       1    2967    2971    2970",
    /* 9 */
    "#Comment",
    /* 10 */
    "#Comment",
    /* 11 */
    "SHELL /     3129       1       1    2967 2971    2970",
    /* 12 */
    "SHELL /     3129       1       1    2967    2971    2970",
    /* 13 */
    "$Comment",
    /* 14 */
    "SHELL /     3129       1       1    2967    2971    2970",
    /* 15 */
    "SHELL /     3129       1       1    2967    2971    2970",
    /* 16 */
    "$Comment",
    /* 17 */
    "#Comment",
    /* 18 */
    "NODE  /        1              0.             0.5              0.",
    /* 19 */
    "NODE  /        1              0.             0.5              0.",
  ];

  #[test]
  fn skips_gather_cards() {
    let keywords: Vec<_> = LINES_GATHER
      .iter()
      .map(|l| Keyword::parse(l.as_ref()))
      .collect();
    let mut li = LINES_GATHER
      .iter()
      .zip(keywords.iter())
      .enumerate()
      .map(|(n, (t, k))| ParsedLine {
        number: n,
        text: t.as_ref(),
        keyword: k.as_ref(),
      })
      .remove_comments();
    let firstline = li.next().unwrap();

    let mut tmp = li.skip_fold(firstline.try_into_keywordline().unwrap());
    let mut tmp_nextline = tmp.nextline.unwrap();
    assert_eq!(tmp_nextline, pline!(5, &LINES_GATHER[5], Some(&Shell)));
    assert_eq!(tmp.skip_end, Some(3));

    tmp = li.skip_fold(tmp_nextline.try_into_keywordline().unwrap());
    tmp_nextline = tmp.nextline.unwrap();
    assert_eq!(tmp_nextline, pline!(6, &LINES_GATHER[6], None));
    assert_eq!(tmp.skip_end, Some(5));

    let skipped = li.skip_to_next_keyword().unwrap();
    tmp = li.skip_fold(skipped.into());
    tmp_nextline = tmp.nextline.unwrap();
    assert_eq!(tmp_nextline, pline!(18, &LINES_GATHER[18], Some(&Node)));
    assert_eq!(tmp.skip_end, Some(15));

    tmp = li.skip_fold(tmp_nextline.try_into_keywordline().unwrap());
    assert_eq!(tmp.nextline, None);
    assert_eq!(tmp.skip_end, None);
  }

}