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
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
use std::mem;
use std::path::Path;
use std::io;
use std::fs;

use pulldown_cmark as md;
use md::CowStr;

use crate::music::{Time, Notation, Chromatic};


pub type BStr = Box<str>;

#[derive(Default, Clone, Copy, PartialEq, Eq, Debug)]
pub struct Transpose {
    pub delta: Chromatic,
    pub notation: Option<Notation>,
}

impl Transpose {
    pub fn new(delta: Chromatic, notation: Option<Notation>) -> Transpose {
        Transpose { delta, notation }
    }

    pub fn is_some(&self) -> bool {
        self.delta != 0.into() || self.notation.is_some()
    }

    pub fn get_notation(&self, default: Notation) -> Notation {
        self.notation.unwrap_or(default)
    }
}

#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Event {
    Song(BStr),
    Subtitle(BStr),

    Clef { time: Option<Time>, notation: Option<Notation> },
    Transpose { chord_set: u32, transpose: Transpose },

    Verse { label: BStr, chorus: bool },
    Span { chord: BStr, lyrics: BStr, newline: bool },

    Bullet(BStr),
    Rule,
}


trait StringExt {
    fn take(&mut self) -> BStr;
}

impl StringExt for String {
    fn take(&mut self) -> BStr {
        let res = self.clone().into();
        self.clear();
        res
    }
}


#[derive(Clone, Copy, Eq, PartialEq, Debug)]
enum Element {
    Header(i32),
    TextLyrics,
    TextChord,
    Bullet,
}

#[derive(Default, Serialize, Debug)]
pub struct ParsingDebug {
    pub evts_md: Vec<BStr>,
    pub evts_bard: Vec<BStr>,
}

impl ParsingDebug {
    pub fn append(&mut self, mut other: ParsingDebug) {
        self.evts_md.append(&mut other.evts_md);
        self.evts_bard.append(&mut other.evts_bard);
    }
}

pub struct Events<I> {
    md: I,

    elem: Element,
    buffer1: String,
    buffer2: String,
    ol_level: u32,
    ol_item: Option<i32>,
    bq_level: u32,
    verse_open: bool,
    newline: bool,
    line_start: bool,

    stashed: Option<Event>,

    debug: Option<ParsingDebug>,
}

impl<'a, I: Iterator<Item = md::Event<'a>>> Events<I> {
    fn new(md: I, collect_debug: bool) -> Events<I> {
        let debug = if collect_debug {
            Some(ParsingDebug::default())
        } else {
            None
        };

        Events {
            md,
            elem: Element::TextLyrics,
            buffer1: String::new(),
            buffer2: String::new(),
            ol_level: 0,
            ol_item: None,
            bq_level: 0,
            verse_open: false,
            newline: true,
            line_start: true,
            stashed: None,
            debug,
        }
    }

    pub fn take_debug(&mut self) -> Option<ParsingDebug> {
        self.debug.take()
    }

    fn start_tag(&mut self, tag: md::Tag) -> Option<Event> {
        use self::md::Tag::*;

        match tag {
            Paragraph => None,
            Rule => Some(Event::Rule),
            Header(num) => {
                self.elem = Element::Header(num.min(3));
                self.buffer1.clear();
                self.verse_end();
                None
            },
            BlockQuote => {
                self.bq_level += 1;
                self.verse_end();
                None
                // Note: A verse start is not dispatched right away,
                // there might be a list following.
            },
            CodeBlock(_s) => None,
            List(Some(num)) => {
                self.ol_level += 1;
                if self.ol_level == 1 {
                    // Here we subtract one because Item event will add one
                    self.ol_item = Some(num as i32 - 1);
                }
                self.verse_end();
                None
                // Note: A verse start is not dispatched right away,
                // there might be a blockquoute following.
            },
            List(None) => {
                if self.elem == Element::TextLyrics { self.elem = Element::Bullet; }
                None
            },
            Item => {
                if let Some(i) = self.ol_item.as_mut() {
                    *i += 1;
                }
                None
            },
            FootnoteDefinition(_s) => None,
            HtmlBlock => None,
            Emphasis => { self.line_start = false; None },
            Strong => { self.line_start = false; None },
            Strikethrough => { self.line_start = false; None },
            Code => {
                if self.elem == Element::TextLyrics {
                    // Start a chord, dispatch previously collected span, if any
                    self.elem = Element::TextChord;
                    self.verse_or_span()
                } else {
                    None
                }
            },
            Link(_link_type, _url, _title) => { self.line_start = false; None },
            Image(_link_type, _url, _title) => { self.line_start = false; None },

            Table(_) | TableHead | TableRow | TableCell => unreachable!(),
        }
    }

    fn end_tag(&mut self, tag: md::Tag) -> Option<Event> {
        use self::md::Tag::*;

        match tag {
            Paragraph => {
                if self.elem == Element::TextLyrics {
                    self.line_end(true)
                } else {
                    None
                }
            },
            Rule => None,
            Header(num) => {
                self.elem = Element::TextLyrics;
                let text = self.buffer1.take();
                Some(match num {
                    1 => Event::Song(text),
                    2 => Event::Subtitle(text),
                    _ => self.verse_event(text, self.bq_level > 0),
                })
            },
            BlockQuote => {
                self.bq_level = self.bq_level.checked_sub(1).expect("Internal error: Invalid parser state");
                None
            },
            CodeBlock(_s) => None,
            List(Some(_num)) => {
                self.ol_level = self.ol_level.checked_sub(1).expect("Internal error: Invalid parser state");
                if self.ol_level == 0 {
                    self.ol_item = None;
                }
                None
            },
            List(None) => {
                if self.elem == Element::Bullet { self.elem = Element::TextLyrics; }
                None
            },
            Item => self.line_end(true),
            FootnoteDefinition(_s) => None,
            HtmlBlock => None,
            Emphasis => None,
            Strong => None,
            Strikethrough => None,
            Code => {
                if self.elem == Element::TextChord { self.elem = Element::TextLyrics; }
                None
            },
            Link(_link_type, _url, _title) => None,
            Image(_link_type, _url, _title) => None,

            Table(_) | TableHead | TableRow | TableCell => unreachable!(),
        }
    }

    fn get_span(&mut self) -> Option<Event> {
        if !self.buffer1.is_empty() || !self.buffer2.is_empty() {
            // We preserve buffer capacity here

            let lyrics = self.buffer1.clone().into();
            self.buffer1.clear();

            Some(Event::Span {
                chord: self.buffer2.take(),
                lyrics,
                newline: mem::replace(&mut self.newline, false),
            })
        } else {
            None
        }
    }

    fn verse_event(&mut self, label: BStr, chorus: bool) -> Event {
        self.verse_open = true;
        Event::Verse { label, chorus }
    }

    /// Ensures that a verse is always open before dispatching a span
    fn verse_or_span(&mut self) -> Option<Event> {
        if let Some(evt) = self.get_span() {
            if !self.verse_open {
                self.stashed = Some(evt);
                let label = self.ol_item.map(|i| format!("{}.", i).into()).unwrap_or(BStr::default());
                Some(self.verse_event(label, self.bq_level > 0))
            } else {
                Some(evt)
            }
        } else {
            None
        }
    }

    fn verse_end(&mut self) {
        self.verse_open = false;
        self.newline = true;
    }

    fn stash_text(&mut self, text: CowStr<'a>) -> Option<Event> {
        use Element::*;

        match self.elem {
            Header(_) | TextLyrics | Bullet => {
                self.buffer1.push_str(&text);
            },
            TextChord => {
                self.buffer2.push_str(&text);
            },
        }

        None
    }

    fn parse_dollar(&mut self) -> Option<Event> {
        if !self.line_start || !self.buffer2.is_empty() || self.buffer1.get(0..1) != Some("$") {
            return None;
        }

        let mut time: Option<Time> = None;
        let mut notation: Option<Notation> = None;

        for arg in self.buffer1[1..].split_ascii_whitespace() {
            if arg.chars().next().map(|c| c.is_ascii_digit()).unwrap_or(false) {
                // This looks like a time signtarue argument
                if time.is_some() {
                    return None;
                }

                match arg.find('/')
                    .map(|i| arg.split_at(i))
                    .map(|(a, b)| (a.parse(), b.get(1..).and_then(|b| b.parse().ok())))
                {
                    Some((Ok(a), Some(b))) => time = Some((a, b)),
                    _ => return None,
                }
            } else {
                // This looks like a notation argument
                if notation.is_some() {
                    return None;
                }

                match arg.parse() {
                    Ok(m) => notation = Some(m),
                    Err(_) => return None,
                }
            }
        }

        if time.is_some() || notation.is_some() {
            self.buffer1.clear();
            Some(Event::Clef { time, notation })
        } else {
            None
        }
    }

    fn parse_carret(&mut self) -> Option<Event> {
        if !self.line_start || !self.buffer2.is_empty() {
            return None;
        }

        let num_carrets = self.buffer1.chars().take_while(|c| *c == '^').count();

        if num_carrets == 0 || num_carrets > 2 {
            return None;
        }

        let mut delta: Option<Chromatic> = None;
        let mut notation: Option<Notation> = None;

        for arg in self.buffer1[num_carrets..].split_ascii_whitespace() {
            if arg.chars().next().map(|c| c == '-' || c == '+' || c.is_ascii_digit()).unwrap_or(false) {
                // This looks like a numerical pitch delta argument
                if delta.is_some() {
                    return None;
                }

                match arg.parse() {
                    Ok(d) => delta = Some(d),
                    Err(_) => return None,
                }
            } else {
                // This looks like a notation argument
                if notation.is_some() {
                    return None;
                }

                match arg.parse() {
                    Ok(m) => notation = Some(m),
                    Err(_) => return None,
                }
            }
        }

        if delta.is_some() || notation.is_some() {
            self.buffer1.clear();
            let transpose = Transpose::new(delta.unwrap_or(0.into()), notation);
            let chord_set = num_carrets as u32 - 1;
            Some(Event::Transpose { chord_set, transpose })
        } else {
            None
        }
    }

    fn line_end(&mut self, verse_end: bool) -> Option<Event> {
        use Element::*;

        let res = match self.elem {
            TextLyrics => {
                // Check if this line is a time, notation or transposition instruction
                if let Some(evt) = self.parse_dollar() {
                    Some(evt)
                } else if let Some(evt) = self.parse_carret() {
                    Some(evt)
                } else {
                    // Dispatch span, if any
                    self.verse_or_span()
                }
            },
            Bullet => Some(Event::Bullet(self.buffer1.take())),
            _ => None,
        };

        self.newline = true;
        self.line_start = true;

        if verse_end {
            self.verse_end();
        }

        res
    }

    fn next_inner(&mut self) -> Option<Event> {
        use self::md::Event as M;

        loop {
            if self.stashed.is_some() {
                return self.stashed.take()
            }

            let md_evt = match self.md.next() {
                Some(evt) => {
                    if let Some(debug) = self.debug.as_mut() {
                        let evt_s = format!("{:?}", evt).into();
                        debug.evts_md.push(evt_s);
                    }
                    evt
                },
                None => return None,
            };

            let evt = match md_evt {
                M::Start(t) => self.start_tag(t),
                M::End(t) => self.end_tag(t),
                M::Text(s) => self.stash_text(s),
                M::Html(_s) => None,
                M::InlineHtml(_s) => None,
                M::FootnoteReference(_s) => None,
                M::SoftBreak | M::HardBreak => self.line_end(false),
                M::TaskListMarker(_) => None,
            };

            if evt.is_some() {
                return evt;
            }
        }
    }
}

impl<'a, I: Iterator<Item = md::Event<'a>>> Iterator for Events<I> {
    type Item = Event;

    fn next(&mut self) -> Option<Event> {
        self.next_inner()
            .map(|evt| {
                if let Some(debug) = self.debug.as_mut() {
                    let evt_s = format!("{:?}", evt).into();
                    debug.evts_bard.push(evt_s);
                }
                evt
            })
    }
}

pub struct MDFile {
    content: String,
    collect_debug: bool,
}

impl MDFile {
    pub fn new<P: AsRef<Path>>(path: P, collect_debug: bool) -> io::Result<MDFile> {
        let content = fs::read_to_string(&path) ?;

        Ok(MDFile {
            content,
            collect_debug,
        })
    }

    pub fn from_str(s: &str, collect_debug: bool) -> MDFile {
        MDFile {
            content: s.into(),
            collect_debug,
        }
    }

    pub fn parse<'a>(&'a self) -> Events<impl Iterator<Item = md::Event>> {
        // TODO: link callback

        Events::new(md::Parser::new(&self.content), self.collect_debug)
    }
}



#[cfg(test)]
mod tests {
    use std::cmp::Ordering;

    use super::*;

    /// Event reimplemented with str refs instead of boxed strings for easier testing
    #[derive(PartialEq, Eq, Debug)]
    pub enum E<'a> {
        Song(&'a str),
        Subtitle(&'a str),

        Clef { time: Option<Time>, notation: Option<Notation> },
        Transpose { chord_set: u32, transpose: Transpose },

        Verse { label: &'a str, chorus: bool },
        Span { chord: &'a str, lyrics: &'a str, newline: bool },

        Bullet(&'a str),
        Rule,
    }

    impl<'a> From<&'a Event> for E<'a> {
        fn from(evt: &'a Event) -> Self {
            use Event::*;

            match evt {
                Song(s) => E::Song(s),
                Subtitle(s) => E::Subtitle(&s),
                Clef { time, notation } => E::Clef { time: *time, notation: *notation },
                Transpose { chord_set, transpose } => E::Transpose { chord_set: *chord_set, transpose: *transpose },
                Verse { label, chorus } => E::Verse { label: &label, chorus: *chorus },
                Span { chord, lyrics, newline } => E::Span { chord: &chord, lyrics: &lyrics, newline: *newline },
                Bullet(text) => E::Bullet(&text),
                Rule => E::Rule,
            }
        }
    }

    impl<'a> PartialEq<&'a Event> for E<'a> {
        fn eq(&self, evt: &&'a Event) -> bool {
            let evt = Self::from(*evt);
            *self == evt
        }
    }

    impl<'a> PartialEq<E<'a>> for &Event {
        fn eq(&self, e: &E<'a>) -> bool {
            let self_e = E::from(*self);
            self_e == *e
        }
    }

    fn parse_one(s: &str) -> Event {
        let md = MDFile::from_str(s, true);
        let mut evts = md.parse();
        let evt = evts.next();
        println!("{:#?}", evts.take_debug());
        evt.unwrap()
    }

    fn parse(s: &str, evts_expected: &[E<'static>]) {
        let md = MDFile::from_str(s, true);
        let mut evts_iter = md.parse();
        let evts: Vec<_> = (&mut evts_iter).collect();
        println!("{:#?}", evts_iter.take_debug());

        for (actual, expected) in evts.iter().zip(evts_expected.iter()) {
            assert_eq!(actual, *expected);
        }

        match evts.len().cmp(&evts_expected.len()) {
            Ordering::Less => panic!("Not all expected events received"),
            Ordering::Equal => { /* evt numbers match */ },
            Ordering::Greater => panic!("Received more events than expected"),
        }
    }

    #[test]
    fn title() {
        assert_eq!(&parse_one("# Title"), E::Song("Title"));
    }

    #[test]
    fn subtitle() {
        assert_eq!(&parse_one("## Subtitle"), E::Subtitle("Subtitle"));
    }

    #[test]
    fn clef() {
        assert_eq!(&parse_one("$ 4/4 western"), E::Clef { time:Some((4, 4)), notation: Some(Notation::English) });
        assert_eq!(&parse_one("$ english 4/4"), E::Clef { time:Some((4, 4)), notation: Some(Notation::English) });
        assert_eq!(&parse_one("$ 4/4"), E::Clef { time:Some((4, 4)), notation: None });
        assert_eq!(&parse_one("$ german"), E::Clef { time:None, notation: Some(Notation::German) });

        assert_eq!(&parse_one("$ blablabla"), E::Verse { label: "", chorus: false });
        assert_eq!(&parse_one("*$ 4/4 western*"), E::Verse { label: "", chorus: false });
        assert_eq!(&parse_one("**$ 4/4 western**"), E::Verse { label: "", chorus: false });
        assert_eq!(&parse_one("~$ 4/4 western~"), E::Verse { label: "", chorus: false });
    }

    // TODO: Transpose

    #[test]
    fn verse() {
        parse(r#"1. `C`lyrics `Am`lyrics...
2. `C`lyrics

> chorus

3. `C`lyrics
"#,
        &[
            E::Verse { label: "1.", chorus: false },
            E::Span { chord: "C", lyrics: "lyrics ", newline: true },
            E::Span { chord: "Am", lyrics: "lyrics...", newline: false },
            E::Verse { label: "2.", chorus: false },
            E::Span { chord: "C", lyrics: "lyrics", newline: true },
            E::Verse { label: "", chorus: true },
            E::Span { chord: "", lyrics: "chorus", newline: true },
            E::Verse { label: "3.", chorus: false },
            E::Span { chord: "C", lyrics: "lyrics", newline: true },
        ]);

        // Multiple choruses
        parse(r#"> 1. `C`chorus one
> 2. `F`chorus two"#,
        &[
            E::Verse { label: "1.", chorus: true },
            E::Span { chord: "C", lyrics: "chorus one", newline: true },
            E::Verse { label: "2.", chorus: true },
            E::Span { chord: "F", lyrics: "chorus two", newline: true },
        ]);

        // Custom verse label
        parse(r#"### My label
`C`lyrics
###### My label
`C`lyrics
> ### My label
`C`lyrics
"#,
        &[
            E::Verse { label: "My label", chorus: false },
            E::Span { chord: "C", lyrics: "lyrics", newline: true },
            E::Verse { label: "My label", chorus: false },
            E::Span { chord: "C", lyrics: "lyrics", newline: true },
            E::Verse { label: "My label", chorus: true },
            E::Span { chord: "C", lyrics: "lyrics", newline: true },
        ]);

        parse(r#"`D`lyrics

New verse
"#,
        &[
            E::Verse { label: "", chorus: false },
            E::Span { chord: "D", lyrics: "lyrics", newline: true },
            E::Verse { label: "", chorus: false },
            E::Span { chord: "", lyrics: "New verse", newline: true },
        ]);
    }

    #[test]
    fn bullet() {
        parse(r#"- item one
- item two
"#,
        &[
            E::Bullet("item one"),
            E::Bullet("item two"),
        ]);

        parse(r#"- item one

- item two

- item three
"#,
        &[
            E::Bullet("item one"),
            E::Bullet("item two"),
            E::Bullet("item three"),
        ]);

        parse(r#"1. `C`lyrics
- bullet item

`C` lyrics
"#,
        &[
            E::Verse { label: "1.", chorus: false },
            E::Span { chord: "C", lyrics: "lyrics", newline: true },
            E::Bullet("bullet item"),
            E::Verse { label: "", chorus: false },
            E::Span { chord: "C", lyrics: " lyrics", newline: true },
        ]);

        // This is an oddball case, markdown considers the second line
        // a ul item continuation, it's not feasible to make it start a verse.
        parse(r#"- bullet item
some would-be lyrics
"#,
        &[
            E::Bullet("bullet item"),
            E::Bullet("some would-be lyrics"),
        ]);
    }
}