Skip to main content

micron_parser/parsing/
parser.rs

1use std::mem::{self};
2
3use itertools::Itertools;
4use logos::Logos;
5
6use crate::{
7    events::{self, Event, token_to_event},
8    lexer::Token,
9    model::{Block, EmptyLine, Line},
10    parsing::model::{
11        Alignment, Document, Field, InlineNode, Link, Ruler, Section, Style, StyleSet,
12    },
13};
14
15#[derive(Debug, Clone, PartialEq)]
16pub struct ParseError {
17    invalid_slice: String,
18}
19
20#[derive(Debug)]
21pub struct Parser {
22    sections: Vec<Result<Section, ParseError>>,
23    current_section: Option<Section>,
24    current_block: Option<Block>,
25    current_style: StyleSet,
26    current_alignment: Alignment,
27    in_header: bool,
28    saved_style: StyleSet,
29}
30
31impl Default for Parser {
32    fn default() -> Self {
33        Parser::new()
34    }
35}
36
37impl Parser {
38    pub fn new() -> Self {
39        Self {
40            sections: vec![],
41            current_section: None,
42            current_block: None,
43            current_style: StyleSet::default(),
44            current_alignment: Alignment::default(),
45            in_header: false,
46            saved_style: StyleSet::default(),
47        }
48    }
49
50    fn set_style(&mut self, style: Style) {
51        self.current_style.set(style);
52    }
53
54    fn unset_style(&mut self, style: Style) {
55        self.current_style.unset(&style);
56    }
57
58    /// Set a new alignment for the current header/line, as alignments apply to entire lines.
59    fn set_alignment(&mut self, alignment: Alignment) {
60        self.current_alignment = alignment;
61        if self.in_header
62            && let Some(section) = self.current_section.as_mut()
63        {
64            section.set_header_alignment(alignment);
65        } else {
66            if let Some(block) = self.current_block.as_mut() {
67                match block {
68                    Block::Line(paragraph) => paragraph.alignment = alignment,
69                    Block::EmptyLine(_) | Block::Ruler(_) => (),
70                }
71            }
72        }
73    }
74
75    fn enter_header(&mut self) {
76        if !self.in_header {
77            // When we enter a header, a new style scope is created
78            self.in_header = true;
79            self.saved_style = mem::take(&mut self.current_style);
80        }
81    }
82
83    fn exit_header(&mut self) {
84        if self.in_header {
85            // we just exited a header; restore style scope
86            self.in_header = false;
87            self.current_style = mem::take(&mut self.saved_style);
88        }
89    }
90
91    fn start_section(&mut self, level: u8) {
92        if level > 0 {
93            self.enter_header();
94        }
95
96        self.finish_block();
97
98        if let Some(section) = self.current_section.take() {
99            self.sections.push(Ok(section));
100        }
101        self.current_section = Some(Section {
102            level,
103            ..Default::default()
104        });
105    }
106
107    pub(crate) fn finish_block(&mut self) {
108        if let Some(block) = self.current_block.take() {
109            if self.current_section.is_none() {
110                self.start_section(0);
111            }
112            if let Some(section) = self.current_section.as_mut() {
113                section.blocks.push(block);
114            }
115        }
116    }
117
118    fn start_paragraph(&mut self) {
119        self.finish_block();
120        self.current_block = Some(Block::Line(Line {
121            alignment: self.current_alignment,
122            ..Default::default()
123        }));
124    }
125
126    fn add_inline_node(&mut self, node: InlineNode) {
127        if self.in_header
128            && let Some(section) = self.current_section.as_mut()
129        {
130            section.add_to_header(node);
131        } else {
132            if let Some(block) = self.current_block.as_mut() {
133                match block {
134                    Block::Line(line) => line.add_node(node),
135                    Block::EmptyLine(_) | Block::Ruler(_) => {
136                        self.start_paragraph();
137                        self.add_inline_node(node);
138                    }
139                }
140            } else {
141                self.start_paragraph();
142                self.add_inline_node(node);
143            }
144        }
145    }
146
147    fn add_text(&mut self, text: String) {
148        let node = InlineNode::Text {
149            style: self.current_style.clone(),
150            text,
151        };
152        self.add_inline_node(node);
153    }
154
155    fn add_emptyline(&mut self) {
156        let empty_line = EmptyLine {
157            style: self.current_style.clone(),
158        };
159        self.finish_block();
160        self.current_block = Some(Block::EmptyLine(empty_line));
161    }
162
163    /// Adds a newline. This means finishing any in-progress blocks,
164    fn add_newline(&mut self) {
165        if self.in_header {
166            self.exit_header();
167        } else {
168            self.add_inline_node(InlineNode::Newline {
169                style: self.current_style.clone(),
170            });
171            self.finish_block();
172        }
173    }
174
175    fn add_link(&mut self, link: Link) {
176        let node = InlineNode::Link {
177            style: self.current_style.clone(),
178            link,
179        };
180        self.add_inline_node(node);
181    }
182
183    fn add_field(&mut self, field: Field) {
184        let node = InlineNode::Field {
185            style: self.current_style.clone(),
186            field,
187        };
188        self.add_inline_node(node);
189    }
190
191    fn add_ruler(&mut self, symbol: Option<String>) {
192        let line = Ruler {
193            symbol,
194            style: self.current_style.clone(),
195        };
196        self.finish_block();
197        self.current_block = Some(Block::Ruler(line));
198    }
199
200    pub fn finalize(mut self) -> Vec<Result<Section, ParseError>> {
201        self.finish_block();
202        if let Some(section) = self.current_section.take() {
203            self.sections.push(Ok(section));
204        }
205        self.sections
206    }
207
208    /// Parse the provided micron markup
209    pub fn parse(mut self, micron_markup: &str) -> Result<Document, Vec<ParseError>> {
210        let lexer = Token::lexer(micron_markup);
211        let events = token_to_event(lexer);
212        let mut previous_event: Option<Event>;
213        let mut current_event: Option<Event> = None;
214        for e in events {
215            previous_event = current_event.clone();
216            current_event = Some(e.clone());
217            match e {
218                Event::ControlHeader(_) => (),
219                Event::BoldStart => self.set_style(Style::Bold),
220                Event::BoldEnd => self.unset_style(Style::Bold),
221                Event::UnderlineStart => self.set_style(Style::Underline),
222                Event::UnderlineEnd => self.unset_style(Style::Underline),
223                Event::ItalicStart => self.set_style(Style::Italic),
224                Event::ItalicEnd => self.unset_style(Style::Italic),
225                Event::Align(alignment) => match alignment {
226                    events::Alignment::Default => self.set_alignment(Alignment::Default),
227                    events::Alignment::Left => self.set_alignment(Alignment::Left),
228                    events::Alignment::Center => self.set_alignment(Alignment::Center),
229                    events::Alignment::Right => self.set_alignment(Alignment::Right),
230                },
231                Event::LiteralStart => (),
232                Event::LiteralEnd => (),
233                Event::ForegroundColorSet(c) => self.set_style(Style::ForegroundColor(c)),
234                Event::ForegroundColorUnset => {
235                    self.unset_style(Style::ForegroundColor("".to_string()))
236                }
237                Event::BackgroundColorSet(c) => self.set_style(Style::BackgroundColor(c)),
238                Event::BackgroundColorUnset => {
239                    self.unset_style(Style::BackgroundColor("".to_string()))
240                }
241                Event::Link(link) => self.add_link(link),
242                Event::Field(field) => self.add_field(field),
243                Event::SectionStart { level } => self.start_section(level),
244                Event::SectionReset => self.start_section(0),
245                Event::Line(c) => self.add_ruler(c),
246                Event::Newline => {
247                    if previous_event == Some(Event::Newline) {
248                        self.add_emptyline();
249                    } else if previous_event == Some(Event::SectionReset) {
250                        // a single line section end does not provoke a newline node
251                    } else {
252                        self.add_newline();
253                    }
254                }
255                Event::Text(s) => self.add_text(s),
256                Event::Comment(_) => (),
257                Event::UnknownTag(_) => (),
258            }
259        }
260        self.finish_block();
261        let results = self.finalize();
262        let (sections, errors): (Vec<Section>, Vec<ParseError>) =
263            results.into_iter().partition_result();
264        if errors.is_empty() {
265            Ok(Document { sections })
266        } else {
267            Err(errors)
268        }
269    }
270}
271
272#[cfg(test)]
273mod tests {
274    use claims::{assert_ok, assert_some};
275
276    use crate::model::{Block, Line};
277
278    use super::*;
279
280    #[test]
281    fn can_parse_bold_italic_underline2() {
282        let mu = include_str!("../../tests/cases/bold_italic_underline2.mu");
283        let doc = assert_ok!(Parser::new().parse(mu));
284
285        let mut iter = dbg!(&doc).sections.iter();
286
287        assert_eq!(
288            iter.next(),
289            Some(&Section {
290                level: 0,
291                header: None,
292                blocks: vec![Block::Line(Line {
293                    nodes: vec![
294                        InlineNode::Text {
295                            style: StyleSet::default(),
296                            text: "This is a ".to_string()
297                        },
298                        InlineNode::Text {
299                            style: StyleSet(vec![Style::Bold, Style::Italic, Style::Underline,]),
300                            text: "bold, italicized, and underlined".to_string()
301                        },
302                        InlineNode::Text {
303                            style: StyleSet::default(),
304                            text: " example with a different formatting end.".to_string()
305                        },
306                        InlineNode::Newline {
307                            style: StyleSet::default(),
308                        },
309                    ],
310                    ..Default::default()
311                })],
312            })
313        );
314
315        assert_eq!(iter.next(), None,);
316        assert_eq!(1, doc.sections.len());
317    }
318
319    #[test]
320    fn can_parse_escape() {
321        let mu = include_str!("../../tests/cases/escape.mu");
322        let doc = assert_ok!(Parser::new().parse(mu));
323
324        let mut iter = dbg!(&doc).sections.iter();
325
326        assert_eq!(
327            iter.next(),
328            Some(&Section {
329                level: 0,
330                header: None,
331                blocks: vec![
332                    Block::Line(Line {
333                        nodes: vec![
334                            InlineNode::Text {
335                                style: StyleSet::default(),
336                                text: "This is an escaped `!bold text`!".to_string()
337                            },
338                            InlineNode::Newline {
339                                style: StyleSet::default(),
340                            },
341                        ],
342                        ..Default::default()
343                    }),
344                    Block::Line(Line {
345                        nodes: vec![
346                            InlineNode::Text {
347                                style: StyleSet::default(),
348                                text: r#"Escaped escape: \"#.to_string()
349                            },
350                            InlineNode::Newline {
351                                style: StyleSet::default(),
352                            },
353                        ],
354                        ..Default::default()
355                    })
356                ],
357            })
358        );
359
360        assert_eq!(iter.next(), None,);
361        assert_eq!(1, doc.sections.len());
362        assert_eq!(2, doc.sections[0].blocks.len());
363    }
364
365    #[test]
366    fn can_parse_cursed_style_reset_style() {
367        let mu = include_str!("../../tests/cases/cursed/style_reset_style.mu");
368        let doc = assert_ok!(Parser::new().parse(mu));
369
370        let mut iter = dbg!(&doc).sections.iter();
371
372        assert_eq!(
373            iter.next(),
374            Some(&Section {
375                level: 0,
376                header: None,
377                blocks: vec![Block::Line(Line {
378                    nodes: vec![
379                        InlineNode::Text {
380                            style: StyleSet(vec![Style::Bold]),
381                            text: "Bold".to_string()
382                        },
383                        InlineNode::Text {
384                            style: StyleSet::default(),
385                            text: "NotBold".to_string()
386                        },
387                        InlineNode::Text {
388                            style: StyleSet(vec![Style::Bold]),
389                            text: "Bold".to_string()
390                        },
391                        InlineNode::Newline {
392                            style: StyleSet::default(),
393                        },
394                    ],
395                    ..Default::default()
396                })],
397            }),
398        );
399
400        assert_eq!(iter.next(), None,);
401        assert_eq!(1, doc.sections.len());
402        assert_eq!(1, doc.sections[0].blocks.len());
403    }
404
405    #[test]
406    fn can_parse_background() {
407        let mu = include_str!("../../tests/cases/background.mu");
408        let doc = assert_ok!(Parser::new().parse(mu));
409
410        let mut iter = dbg!(&doc).sections.iter();
411
412        assert_eq!(
413            iter.next(),
414            Some(&Section {
415                level: 0,
416                header: None,
417                blocks: vec![
418                    Block::Line(Line {
419                        nodes: vec![
420                            InlineNode::Text {
421                                style: StyleSet::default(),
422                                text: "We'll set ".to_string()
423                            },
424                            InlineNode::Text {
425                                style: StyleSet(vec![Style::BackgroundColor("bbb".to_string()),]),
426                                text: "background here, unset ".to_string()
427                            },
428                            InlineNode::Text {
429                                style: StyleSet::default(),
430                                text: " here.".to_string()
431                            },
432                            InlineNode::Newline {
433                                style: StyleSet::default()
434                            }
435                        ],
436                        ..Default::default()
437                    }),
438                    Block::Line(Line {
439                        nodes: vec![
440                            InlineNode::Text {
441                                style: StyleSet(vec![Style::BackgroundColor("e2e".to_string()),]),
442                                text: "This is a full width background.".to_string()
443                            },
444                            InlineNode::Newline {
445                                style: StyleSet(vec![Style::BackgroundColor("e2e".to_string()),]),
446                            }
447                        ],
448                        ..Default::default()
449                    })
450                ],
451            })
452        );
453
454        assert_eq!(iter.next(), None,);
455        assert_eq!(1, doc.sections.len());
456        assert_eq!(2, doc.sections[0].blocks.len());
457    }
458
459    #[test]
460    fn can_parse_section() {
461        let mu = include_str!("../../tests/cases/section.mu");
462        let doc = assert_ok!(Parser::new().parse(mu));
463
464        let mut iter = dbg!(&doc).sections.iter();
465
466        assert_eq!(
467            iter.next(),
468            Some(&Section {
469                level: 1,
470                header: Some(Line {
471                    nodes: vec![InlineNode::Text {
472                        style: StyleSet::default(),
473                        text: "This is a section header".to_string()
474                    }],
475                    alignment: Alignment::default(),
476                }),
477                blocks: vec![
478                    Block::Line(Line {
479                        nodes: vec![
480                            InlineNode::Text {
481                                style: StyleSet::default(),
482                                text: "and this is some section text".to_string()
483                            },
484                            InlineNode::Newline {
485                                style: StyleSet::default(),
486                            },
487                        ],
488                        alignment: Alignment::default(),
489                    }),
490                    Block::Line(Line {
491                        nodes: vec![
492                            InlineNode::Text {
493                                style: StyleSet::default(),
494                                text: "this is a > mid sentence section tag, ignored".to_string()
495                            },
496                            InlineNode::Newline {
497                                style: StyleSet::default(),
498                            },
499                        ],
500                        alignment: Alignment::default(),
501                    }),
502                    Block::EmptyLine(EmptyLine::default()),
503                ],
504            }),
505        );
506        assert_eq!(
507            iter.next(),
508            Some(&Section {
509                level: 0,
510                header: None,
511                blocks: vec![
512                    Block::Line(Line {
513                        nodes: vec![
514                            InlineNode::Text {
515                                style: StyleSet::default(),
516                                text: "and this is some non sectioned text".to_string(),
517                            },
518                            InlineNode::Newline {
519                                style: StyleSet::default(),
520                            },
521                        ],
522                        alignment: Alignment::default(),
523                    }),
524                    Block::Line(Line {
525                        nodes: vec![
526                            InlineNode::Text {
527                                style: StyleSet::default(),
528                                text: "this is a < mid sentence section end tag, ignored"
529                                    .to_string(),
530                            },
531                            InlineNode::Newline {
532                                style: StyleSet::default(),
533                            },
534                        ],
535                        alignment: Alignment::default(),
536                    })
537                ],
538            })
539        );
540        assert_eq!(
541            iter.next(),
542            Some(&Section {
543                level: 0,
544                header: None,
545                blocks: vec![Block::Line(Line {
546                    nodes: vec![
547                        InlineNode::Text {
548                            style: StyleSet::default(),
549                            text: " but this end section tag is honored".to_string(),
550                        },
551                        InlineNode::Newline {
552                            style: StyleSet::default(),
553                        },
554                    ],
555                    alignment: Alignment::default(),
556                })],
557            })
558        );
559
560        assert_eq!(iter.next(), None,);
561        assert_eq!(3, doc.sections.len());
562        assert_eq!(3, doc.sections[0].blocks.len());
563    }
564
565    #[test]
566    fn can_parse_alignment() {
567        let mu = include_str!("../../tests/cases/alignment.mu");
568        let doc = assert_ok!(Parser::new().parse(mu));
569
570        let mut iter = dbg!(&doc).sections.iter();
571
572        assert_eq!(iter.len(), 1);
573        let item = iter.next();
574        let item = assert_some!(item);
575        assert_eq!(item.level, 0);
576        assert_eq!(item.header, None);
577
578        let mut blocks = item.blocks.iter();
579        assert_eq!(
580            blocks.next().unwrap(),
581            &Block::Line(Line {
582                nodes: vec![
583                    InlineNode::Text {
584                        style: StyleSet::default(),
585                        text: "Centered".to_string(),
586                    },
587                    InlineNode::Newline {
588                        style: StyleSet::default(),
589                    },
590                ],
591                alignment: Alignment::Center,
592            }),
593        );
594        assert_eq!(
595            blocks.next().unwrap(),
596            &Block::Line(Line {
597                nodes: vec![
598                    InlineNode::Text {
599                        style: StyleSet::default(),
600                        text: "Also Centered".to_string(),
601                    },
602                    InlineNode::Newline {
603                        style: StyleSet::default(),
604                    },
605                ],
606                alignment: Alignment::Center,
607            }),
608        );
609        assert_eq!(
610            blocks.next().unwrap(),
611            &Block::EmptyLine(EmptyLine {
612                style: StyleSet::default(),
613            }),
614        );
615        assert_eq!(
616            blocks.next().unwrap(),
617            &Block::Line(Line {
618                nodes: vec![
619                    InlineNode::Text {
620                        style: StyleSet::default(),
621                        text: "Default".to_string(),
622                    },
623                    InlineNode::Newline {
624                        style: StyleSet::default(),
625                    },
626                ],
627                alignment: Alignment::Default,
628            }),
629        );
630        assert_eq!(
631            blocks.next().unwrap(),
632            &Block::EmptyLine(EmptyLine {
633                style: StyleSet::default(),
634            }),
635        );
636        assert_eq!(
637            blocks.next().unwrap(),
638            &Block::Line(Line {
639                nodes: vec![
640                    InlineNode::Text {
641                        style: StyleSet::default(),
642                        text: "Right".to_string(),
643                    },
644                    InlineNode::Newline {
645                        style: StyleSet::default(),
646                    },
647                ],
648                alignment: Alignment::Right,
649            }),
650        );
651        assert_eq!(
652            blocks.next().unwrap(),
653            &Block::Line(Line {
654                nodes: vec![
655                    InlineNode::Text {
656                        style: StyleSet::default(),
657                        text: "Still right".to_string(),
658                    },
659                    InlineNode::Newline {
660                        style: StyleSet::default(),
661                    },
662                ],
663                alignment: Alignment::Right,
664            }),
665        );
666        assert_eq!(
667            blocks.next().unwrap(),
668            &Block::EmptyLine(EmptyLine {
669                style: StyleSet::default(),
670            }),
671        );
672        assert_eq!(
673            blocks.next().unwrap(),
674            &Block::Line(Line {
675                nodes: vec![
676                    InlineNode::Text {
677                        style: StyleSet::default(),
678                        text: "Centered".to_string(),
679                    },
680                    InlineNode::Newline {
681                        style: StyleSet::default(),
682                    },
683                ],
684                alignment: Alignment::Center,
685            }),
686        );
687        assert_eq!(
688            blocks.next().unwrap(),
689            &Block::Line(Line {
690                nodes: vec![
691                    InlineNode::Text {
692                        style: StyleSet::default(),
693                        text: "Still centered".to_string(),
694                    },
695                    InlineNode::Newline {
696                        style: StyleSet::default(),
697                    },
698                ],
699                alignment: Alignment::Center,
700            }),
701        );
702
703        assert_eq!(iter.next(), None,);
704        assert_eq!(1, doc.sections.len());
705        assert_eq!(10, doc.sections[0].blocks.len())
706    }
707
708    #[test]
709    fn can_parse_cursed_align_reset() {
710        let mu = include_str!("../../tests/cases/cursed/align_reset.mu");
711        let doc = assert_ok!(Parser::new().parse(mu));
712
713        let mut iter = dbg!(&doc).sections.iter();
714
715        assert_eq!(
716            iter.next(),
717            Some(&Section {
718                level: 0,
719                header: None,
720                blocks: vec![
721                    Block::Line(Line {
722                        nodes: vec![
723                            InlineNode::Text {
724                                style: StyleSet::default(),
725                                text: "Centered".to_string()
726                            },
727                            InlineNode::Newline {
728                                style: StyleSet::default(),
729                            },
730                        ],
731                        alignment: Alignment::Center,
732                    }),
733                    Block::Line(Line {
734                        nodes: vec![
735                            InlineNode::Text {
736                                style: StyleSet::default(),
737                                text: "Default".to_string()
738                            },
739                            InlineNode::Text {
740                                style: StyleSet::default(),
741                                text: " Align".to_string()
742                            },
743                            InlineNode::Newline {
744                                style: StyleSet::default(),
745                            },
746                        ],
747                        alignment: Alignment::Default,
748                    })
749                ]
750            })
751        );
752
753        assert_eq!(iter.next(), None,);
754    }
755
756    #[test]
757    fn can_parse_cursed_eol_color_unset() {
758        let mu = include_str!("../../tests/cases/cursed/eol_color_unset.mu");
759        let doc = assert_ok!(Parser::new().parse(mu));
760
761        let mut iter = dbg!(&doc).sections.iter();
762
763        assert_eq!(
764            iter.next(),
765            Some(&Section {
766                level: 0,
767                header: None,
768                blocks: vec![
769                    Block::Line(Line {
770                        nodes: vec![
771                            InlineNode::Text {
772                                style: StyleSet(vec![Style::BackgroundColor("00f".to_string()),]),
773                                text: "red".to_string()
774                            },
775                            InlineNode::Newline {
776                                style: StyleSet::default(),
777                            }
778                        ],
779                        alignment: Alignment::default(),
780                    }),
781                    Block::Line(Line {
782                        nodes: vec![
783                            InlineNode::Text {
784                                style: StyleSet::default(),
785                                text: "not red".to_string()
786                            },
787                            InlineNode::Newline {
788                                style: StyleSet::default(),
789                            }
790                        ],
791                        alignment: Alignment::default(),
792                    })
793                ]
794            })
795        );
796
797        assert_eq!(iter.next(), None,);
798    }
799
800    #[test]
801    fn can_parse_nomad_guide() {
802        let mu = include_str!("../../tests/cases/nomad_net_guide.mu");
803        let doc = assert_ok!(Parser::new().parse(mu));
804
805        let _iter = dbg!(&doc).sections.iter();
806
807        assert_eq!(30, doc.sections().len());
808    }
809}