micron-parser 0.2.0

Library that reads and parses micron documents into a structure suitable for presenting it as e.g. html documents.
Documentation
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
use itertools::Itertools;
use logos::Lexer;

use crate::{
    lexer::{FieldToken, TagToken, Token},
    parsing::model::{Field, FieldKind, Link},
};

#[derive(Debug, Clone, PartialEq)]
pub(crate) enum Event {
    ControlHeader(String),
    BoldStart,
    BoldEnd,
    UnderlineStart,
    UnderlineEnd,
    ItalicStart,
    ItalicEnd,
    Align(Alignment),
    LiteralStart,
    LiteralEnd,
    ForegroundColorSet(String),
    ForegroundColorUnset,
    BackgroundColorSet(String),
    BackgroundColorUnset,
    Link(Link),
    Field(Field),
    SectionStart { level: u8 },
    SectionReset,
    Line(Option<String>),
    Newline,
    Text(String),
    Comment(String),
    UnknownTag(String),
}

fn parse_link(tokens: Vec<TagToken>) -> Link {
    let mut label = None;
    let mut url = String::new();

    let mut t_sep = 0;
    let mut parts = vec![];
    let mut fields = vec![];
    for t in tokens {
        match t {
            TagToken::PipeSeparator => (),
            TagToken::Part(p) => {
                // format of links is such that the number of '`' dictates which fields are where:
                // 0 => only one part; it is the url
                // 1 => two parts: [0] is the label, [1] is the url
                // 2 => three parts: [0] is label, [1] is url, rest is fields
                if t_sep < 2 {
                    parts.push(p)
                } else {
                    fields.push(p);
                }
            }
            TagToken::TagSeparator => t_sep += 1,
        }
    }

    if !parts.is_empty() {
        // url is always present, and always the last part
        url = parts.pop().unwrap();
        label = parts.pop();
    }

    Link { label, url, fields }
}

fn parse_field(token: FieldToken) -> Field {
    let name: String;
    let value: String;

    let filter_tag_part = |tag_tokens: Vec<TagToken>| {
        tag_tokens
            .into_iter()
            .filter_map(|t| {
                if let TagToken::Part(p) = t {
                    Some(p)
                } else {
                    None
                }
            })
            .rev() // reverse so order it is easily pop()-able
            .collect::<Vec<_>>()
    };

    let kind = match token {
        FieldToken::Checkbox(tag_tokens) => {
            let mut parts = filter_tag_part(tag_tokens);
            name = parts.pop().unwrap_or_default();
            value = parts.pop().unwrap_or_default();
            let pre_checked = parts.contains(&"*".to_string());
            FieldKind::Checkbox { pre_checked }
        }
        FieldToken::Radio(tag_tokens) => {
            let mut parts = filter_tag_part(tag_tokens);
            name = parts.pop().unwrap_or_default();
            value = parts.pop().unwrap_or_default();
            let pre_checked = parts.contains(&"*".to_string());
            FieldKind::Radio { pre_checked }
        }
        FieldToken::Input(tag_tokens) => {
            // An Input field may be contain options ( <!23| ),
            // which can be detected by the presence of the pipe char.
            let has_options = tag_tokens
                .iter()
                .any(|i| matches!(i, &TagToken::PipeSeparator));
            let mut parts = filter_tag_part(tag_tokens);
            // filter_tag_part reverses, which means the order of parts is:
            // (if options): value, name, options
            // (no options): value, name
            let options = if has_options {
                Some(parts.pop().unwrap_or_default())
            } else {
                None
            };
            name = parts.pop().unwrap_or_default();
            value = parts.pop().unwrap_or_default();
            let (hidden, size) = if let Some(options) = options {
                let mut hidden = false;
                let mut size_buf = String::new();
                options.chars().for_each(|c| {
                    if c == '!' {
                        hidden = true;
                    } else if c.is_ascii_digit() {
                        size_buf.push(c);
                    }
                });
                let size = size_buf.parse::<u8>().ok();
                (hidden, size)
            } else {
                (false, None)
            };
            FieldKind::Input { hidden, size }
        }
    };

    Field { kind, name, value }
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) enum Alignment {
    Default,
    Left,
    Center,
    Right,
}

/// State machine that translates tokens into more explicit `Event`s.
/// For example, literal tokens are intepreted and any content is properly escaped, and
/// a style reset tag (``) will also generate a End/Unset events for currently open tags.
pub(crate) fn token_to_event(mut lexer: Lexer<Token>) -> impl Iterator<Item = Event> {
    let mut stack: Vec<Event> = vec![];
    let mut previous_token: Option<Token>;
    let mut current_token: Option<Token> = None;
    // TODO: replace bold, italic etc bools with an "active modifier" list, and
    // maybe have style reset emit End/Unset Events for relevant modifiers.
    let mut bold = false;
    let mut italic = false;
    let mut underline = false;
    let mut in_literal_mode = false;
    let mut fg_set = false;
    let mut bg_set = false;
    let mut alignment = Alignment::Default;
    let mut in_comment = false;
    let mut comment_stack = String::new();
    let mut in_line = false;
    let mut line_stack = String::new();
    let mut in_control_header = false;
    let mut control_header_stack = String::new();
    while let Some(tr) = lexer.next() {
        if let Ok(t) = tr {
            previous_token = current_token.clone();
            current_token = Some(t.clone());
            let is_sol = previous_token.is_none() || previous_token == Some(Token::Newline);

            if in_comment {
                if current_token == Some(Token::Newline) {
                    in_comment = false;
                    stack.push(Event::Comment(comment_stack.clone()));
                    stack.push(Event::Newline);
                    comment_stack = String::new();
                } else {
                    comment_stack += lexer.slice();
                }
            } else if in_line {
                if current_token == Some(Token::Newline) {
                    in_line = false;
                    stack.push(Event::Line(Some(line_stack.clone())));
                    stack.push(Event::Newline);
                    line_stack = String::new();
                } else {
                    line_stack += lexer.slice();
                }
            } else if in_control_header {
                if current_token == Some(Token::Newline) {
                    in_control_header = false;
                    stack.push(Event::ControlHeader(control_header_stack.clone()));
                    control_header_stack = String::new();
                } else {
                    control_header_stack += lexer.slice();
                }
            }
            // Even when in literal mode, a literal toggle must be able to end literal mode
            else if in_literal_mode && t == Token::LiteralToggle && is_sol {
                in_literal_mode = false;
                stack.push(Event::LiteralEnd);
            }
            // If it was in literal mode, everything is just text. Except newlines.
            else if (in_literal_mode) && t != Token::Newline {
                stack.push(Event::Text(lexer.slice().to_string()))
            } else {
                match t {
                    Token::ControlHeader => {
                        if is_sol {
                            in_control_header = true;
                        } else {
                            stack.push(Event::Text(lexer.slice().to_string()));
                        }
                    }
                    Token::BoldToggle => {
                        if bold {
                            stack.push(Event::BoldEnd)
                        } else {
                            stack.push(Event::BoldStart)
                        }
                        bold = !bold;
                    }
                    Token::UnderlineToggle => {
                        if underline {
                            stack.push(Event::UnderlineEnd)
                        } else {
                            stack.push(Event::UnderlineStart)
                        }
                        underline = !underline;
                    }
                    Token::ItalicToggle => {
                        if italic {
                            stack.push(Event::ItalicEnd)
                        } else {
                            stack.push(Event::ItalicStart)
                        }
                        italic = !italic;
                    }
                    Token::AlignDefault => {
                        let a = Alignment::Default;
                        if alignment != a {
                            alignment = a;
                            stack.push(Event::Align(a))
                        }
                    }
                    Token::AlignLeft => {
                        let a = Alignment::Left;
                        if alignment != a {
                            alignment = a;
                            stack.push(Event::Align(a))
                        }
                    }
                    Token::AlignCenter => {
                        let a = Alignment::Center;
                        if alignment != a {
                            alignment = a;
                            stack.push(Event::Align(a))
                        }
                    }
                    Token::AlignRight => {
                        let a = Alignment::Right;
                        if alignment != a {
                            alignment = a;
                            stack.push(Event::Align(a))
                        }
                    }
                    Token::StyleReset => {
                        if bold {
                            bold = false;
                            stack.push(Event::BoldEnd);
                        }
                        if italic {
                            italic = false;
                            stack.push(Event::ItalicEnd);
                        }
                        if underline {
                            underline = false;
                            stack.push(Event::UnderlineEnd);
                        }
                        if fg_set {
                            fg_set = false;
                            stack.push(Event::ForegroundColorUnset);
                        }
                        if bg_set {
                            bg_set = false;
                            stack.push(Event::BackgroundColorUnset);
                        }
                        if alignment != Alignment::Default {
                            alignment = Alignment::Default;
                            stack.push(Event::Align(Alignment::Default));
                        }
                    }
                    Token::LiteralToggle => {
                        if is_sol {
                            in_literal_mode = true;
                            stack.push(Event::LiteralStart);
                        } else {
                            // Since the lexer for literal toggle swallows the newline,
                            // if it isn't at the start of line (i.e. it was at the end of a line
                            // with text in front and thus invalid), emit a newline
                            stack.push(Event::Newline);
                        }
                    }
                    Token::ColorForegroundSet(s) => {
                        fg_set = true;
                        stack.push(Event::ForegroundColorSet(s))
                    }
                    Token::ColorForegroundUnset => {
                        if fg_set {
                            fg_set = false;
                            stack.push(Event::ForegroundColorUnset)
                        }
                    }
                    Token::ColorBackgroundSet(s) => {
                        bg_set = true;
                        stack.push(Event::BackgroundColorSet(s))
                    }
                    Token::ColorBackgroundUnset => {
                        if bg_set {
                            bg_set = false;
                            stack.push(Event::BackgroundColorUnset)
                        }
                    }
                    Token::Link(tag_tokens) => stack.push(Event::Link(parse_link(tag_tokens))),
                    Token::Field(field_token) => stack.push(Event::Field(parse_field(field_token))),
                    Token::SectionStart(level) => {
                        if is_sol {
                            stack.push(Event::SectionStart { level });
                        } else {
                            stack.push(Event::Text(lexer.slice().to_string()));
                        }
                    }
                    Token::SectionEnd => {
                        if is_sol {
                            stack.push(Event::SectionReset);
                        } else {
                            stack.push(Event::Text(lexer.slice().to_string()));
                        }
                    }
                    Token::Line => {
                        if is_sol {
                            in_line = true;
                        } else {
                            stack.push(Event::Text(lexer.slice().to_string()));
                        }
                    }
                    Token::Comment => {
                        if is_sol {
                            in_comment = true;
                        } else {
                            stack.push(Event::Text(lexer.slice().to_string()));
                        }
                    }
                    Token::Escape(c) => stack.push(Event::Text(c.to_string())),
                    Token::Newline => {
                        stack.push(Event::Newline);
                    }
                    Token::Text(s) => stack.push(Event::Text(s)),
                    Token::UnknownTag => stack.push(Event::UnknownTag(lexer.slice().to_string())),
                }
            }
        }
    }

    // finish any "dangling" comments/lines
    if in_comment {
        stack.push(Event::Comment("".to_string()));
    }
    if in_line {
        stack.push(Event::Line(None));
    }

    stack.into_iter().coalesce(|a, b| match (a, b) {
        (Event::Text(sa), Event::Text(sb)) => Ok(Event::Text(sa + &sb)),
        (a, b) => Err((a, b)),
    })
}

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

    #[test]
    fn can_eventify_cursed_style_reset_style() {
        let mu = include_str!("../tests/cases/cursed/style_reset_style.mu");
        let lex = Token::lexer(mu);
        let events = token_to_event(lex).collect::<Vec<_>>();

        let expected = vec![
            Event::BoldStart,
            Event::Text("Bold".to_string()),
            Event::BoldEnd,
            Event::Text("NotBold".to_string()),
            Event::BoldStart,
            Event::Text("Bold".to_string()),
            Event::BoldEnd,
            Event::Newline,
        ];
        assert_eq!(expected, events);
    }

    #[test]
    fn can_eventify_cursed_section_newlines() {
        let mu = include_str!("../tests/cases/cursed/section_newlines.mu");
        let lex = Token::lexer(mu);
        let events = token_to_event(lex).collect::<Vec<_>>();

        let expected = vec![
            Event::SectionStart { level: 1 },
            Event::Text("Outputting Formatted Text".to_string()),
            Event::Newline,
            Event::Newline,
            Event::Newline,
            Event::SectionStart { level: 15 },
            Event::Newline,
            Event::Line(Some("∿".to_string())),
            Event::Newline,
            Event::SectionReset,
            Event::Newline,
        ];
        assert_eq!(expected, events);
    }

    #[test]
    fn can_eventify_background() {
        let mu = include_str!("../tests/cases/background.mu");
        let lex = Token::lexer(mu);
        let events = token_to_event(lex).collect::<Vec<_>>();

        let expected = vec![
            Event::Text("We'll set ".to_string()),
            Event::BackgroundColorSet("bbb".to_string()),
            Event::Text("background here, unset ".to_string()),
            Event::BackgroundColorUnset,
            Event::Text(" here.".to_string()),
            Event::Newline,
            Event::BackgroundColorSet("e2e".to_string()),
            Event::Text("This is a full width background.".to_string()),
            Event::Newline,
        ];
        assert_eq!(expected, events);
    }

    #[test]
    fn can_eventify_section() {
        let mu = include_str!("../tests/cases/section.mu");
        let lex = Token::lexer(mu);
        let events = token_to_event(lex).collect::<Vec<_>>();

        let expected = vec![
            Event::SectionStart { level: 1 },
            Event::Text("This is a section header".to_string()),
            Event::Newline,
            Event::Text("and this is some section text".to_string()),
            Event::Newline,
            Event::Text("this is a > mid sentence section tag, ignored".to_string()),
            Event::Newline,
            Event::Newline,
            Event::SectionReset,
            Event::Newline,
            Event::Text("and this is some non sectioned text".to_string()),
            Event::Newline,
            Event::Text("this is a < mid sentence section end tag, ignored".to_string()),
            Event::Newline,
            Event::SectionReset,
            Event::Text(" but this end section tag is honored".to_string()),
            Event::Newline,
        ];
        assert_eq!(expected, events);
    }

    #[test]
    fn can_eventify_field_radio() {
        let mu = include_str!("../tests/cases/field_radio.mu");
        let lex = Token::lexer(mu);
        let events = token_to_event(lex).collect::<Vec<_>>();

        let expected = vec![
            Event::Text("Radio: ".to_string()),
            Event::Field(Field {
                kind: FieldKind::Radio { pre_checked: false },
                name: "color".to_string(),
                value: "Red".to_string(),
            }),
            Event::Text(" red".to_string()),
            Event::Newline,
            Event::Field(Field {
                kind: FieldKind::Radio { pre_checked: false },
                name: "color".to_string(),
                value: "Green".to_string(),
            }),
            Event::Text(" green".to_string()),
            Event::Newline,
            Event::Field(Field {
                kind: FieldKind::Radio { pre_checked: true },
                name: "color".to_string(),
                value: "Blue".to_string(),
            }),
            Event::Text(" blue".to_string()),
            Event::Newline,
        ];
        assert_eq!(expected, events);
    }

    #[test]
    fn can_eventify_cursed_fancy_radio() {
        let mu = include_str!("../tests/cases/cursed/fancy_radio.mu");
        let lex = Token::lexer(mu);
        let events = token_to_event(lex).collect::<Vec<_>>();

        let expected = vec![
            Event::BackgroundColorSet("900".to_string()),
            Event::Field(Field {
                kind: FieldKind::Radio { pre_checked: false },
                name: "color".to_string(),
                value: "Red".to_string(),
            }),
            Event::BackgroundColorUnset,
            Event::Text(" red".to_string()),
            Event::Newline,
            Event::Newline,
            Event::BackgroundColorSet("090".to_string()),
            Event::Field(Field {
                kind: FieldKind::Radio { pre_checked: false },
                name: "color".to_string(),
                value: "Green".to_string(),
            }),
            Event::BackgroundColorUnset,
            Event::Text(" green".to_string()),
            Event::Newline,
            Event::Newline,
            Event::BackgroundColorSet("009".to_string()),
            Event::Field(Field {
                kind: FieldKind::Radio { pre_checked: false },
                name: "color".to_string(),
                value: "Blue".to_string(),
            }),
            Event::BackgroundColorUnset,
            Event::Text(" blue".to_string()),
            Event::Newline,
        ];
        assert_eq!(expected, events);
    }

    #[test]
    fn can_eventify_links() {
        let mu = include_str!("../tests/cases/link.mu");
        let lex = Token::lexer(mu);
        let events = token_to_event(lex).collect::<Vec<_>>();

        let expected = vec![
            Event::Text("Unlabeled link ".to_string()),
            Event::Link(Link {
                label: None,
                url: "72914442a3689add83a09a767963f57c:/page/index.mu".to_string(),
                fields: vec![],
            }),
            Event::Text(" here.".to_string()),
            Event::Newline,
            Event::Text("Labeled link ".to_string()),
            Event::Link(Link {
                label: Some("link label".to_string()),
                url: "72914442a3689add83a09a767963f57c:/page/index.mu".to_string(),
                fields: vec![],
            }),
            Event::Newline,
            Event::Link(Link {
                label: Some("Submit all Fields".to_string()),
                url: ":/page/fields.mu".to_string(),
                fields: vec!["*".to_string()],
            }),
            Event::Newline,
            Event::Link(Link {
                label: Some("Submit some Fields".to_string()),
                url: ":/page/fields.mu".to_string(),
                fields: vec!["username".to_string(), "auth_token".to_string()],
            }),
            Event::Newline,
            Event::Link(Link {
                label: Some("Query the System".to_string()),
                url: ":/page/fields.mu".to_string(),
                fields: vec![
                    "username".to_string(),
                    "auth_token".to_string(),
                    "action=view".to_string(),
                    "amount=64".to_string(),
                ],
            }),
            Event::Newline,
        ];
        assert_eq!(expected, events);
    }

    /*
    #[test]
    fn can_eventify_nomad_guide() {
        let mu = include_str!("../tests/cases/nomad_net_guide.mu");
        let lex = Token::lexer(mu);

        let events = token_to_event(lex).collect::<Vec<_>>();
        assert_eq!(897, dbg!(events).len());
    }
    */
}