lex-core 0.8.2

Parser library for the lex format
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
613
614
615
616
617
618
//! List element
//!
//! A list is an ordered collection of items, each with its own text
//! and optional nested content. Lists can be used to structure
//! outlines, steps, or bullet points.
//!
//! Lists must have a minimum of 2 items.  And it's not ilegal to have mixed decorations in a list, as the parser will consider the first item's decoration to set the list type. The ordering doesn't have to be correct, as lists itself are ordered, they are just a marker, but tooling will order them under demand.
//!
//! Parsing Structure:
//!
//! Nested List (with content):
//! | Element | Prec. Blank | Head     | Blank | Content | Tail   |
//! |---------|-------------|----------|-------|---------|--------|
//! | List    | Optional    | ListLine | No    | Yes     | dedent |
//!
//! Flat List (no nested content):
//! | Element | Prec. Blank | Head     | Tail                |
//! |---------|-------------|----------|---------------------|
//! | List    | Yes         | ListLine | BlankLine or Dedent |
//!
//! Special Cases:
//! - Two Item Minimum: A list must have 2+ items, otherwise it's a paragraph
//! - Dialog Rule: Lines starting with "-" can be marked as dialog (paragraphs) rather than list items
//!
//! Examples:
//!    A flat list with the plain decoration:
//!         - Bread
//!         - Milk
//! They can be nested, and have other styles:
//!    1. Groceries
//!        - Bread
//!        - Milk
//!
//!Formalize Sequence Decoration Styles
//!        List items have two parts, their markers , that determines they are a list item, and their
//!  text content. These appear together in the source text (possible even without space to separate
//! them, perfectly legal), but they are different things, and the actual text for list items does
//!not include the marker.
//!         1. Presentation
//!           
//!          List items can be presented in various dimensions.
//!           - Decoration Styles:
//!             - Plain , a dash -
//!             - Numerical 3
//!             - Roman Numerals IV
//!             - Alphabetical b
//!           - Separators:
//!             - Periods , as in 3.
//!             - Parenthesis as in b)
//!             - Double parenthesis  as in (c)
//!           - Forms:
//!             - Forms only matter for deeper than 1 level items.
//!             - Short: only that level , as in 3.
//!             - Extender: full nested index , as in 1.3.5
//!
// !          Note that all of these can be mixed, for example: 1.b.iii is a valid sequence item as
//! in 1.b)v)
//!
//!
//!        2. Parsing Rules
//!
//!          The list decoration  style, separator and form are determined by the first list item in
//! that list's (same level). Nested lists can have multiple characteristics, and at each level the
//! first of it's items will determine the lists.
//!          Note that these are taken as the authors choice for presentation, they are in no way
//! used to validate or invalidate lists. A list with items in a nonsensical order and mixed
//! presentation is a perfectly valid lists. Tooling such as formatters or publishing tools will often
//! order items correctly on exports. This is a feature actually, as it's easier to same number all
//! items while editing, else on insertions and swaps you must reorder all subsequent items.
//!          The presentation characteristics are a list property, as they are set for the entire list,
//!  even if the source text did not do it consistently. And they are to be used on any ast -> string
//! representation to form the sequence marker (the full combination of all presentation traits).
//!         In list items we do keep the source marker version for recreation capacity, and
//! formatters and other tools are not to be expected to use them.
//!
//!
//! Learn More:
//! - Lists spec: specs/v1/elements/list.lex
//! - Labels (used by annotations in lists): specs/v1/elements/label.lex
//! - Parameters (used by annotations in lists): specs/v1/elements/parameter.lex

use super::super::range::{Position, Range};
use super::super::text_content::TextContent;
use super::super::traits::AstNode;
use super::super::traits::Container;
use super::super::traits::Visitor;
use super::super::traits::VisualStructure;
use super::annotation::Annotation;
use super::container::{GeneralContainer, ListContainer};
use super::content_item::ContentItem;
use super::typed_content::{ContentElement, ListContent};
use std::fmt;

/// A list contains multiple list items
#[derive(Debug, Clone, PartialEq)]
pub struct List {
    pub items: ListContainer,
    pub marker: Option<super::sequence_marker::SequenceMarker>,
    pub annotations: Vec<Annotation>,
    pub location: Range,
}

/// A list item has a marker, body text, and optional nested content
#[derive(Debug, Clone, PartialEq)]
pub struct ListItem {
    pub marker: TextContent,
    pub text: Vec<TextContent>,
    pub children: GeneralContainer,
    pub annotations: Vec<Annotation>,
    pub location: Range,
}

impl List {
    fn default_location() -> Range {
        Range::new(0..0, Position::new(0, 0), Position::new(0, 0))
    }
    pub fn new(items: Vec<ListItem>) -> Self {
        let typed_items = items
            .into_iter()
            .map(ListContent::ListItem)
            .collect::<Vec<_>>();
        Self {
            items: ListContainer::from_typed(typed_items),
            marker: None,
            annotations: Vec::new(),
            location: Self::default_location(),
        }
    }

    /// Preferred builder
    pub fn at(mut self, location: Range) -> Self {
        self.location = location;
        self
    }

    /// Annotations attached to this list as a whole.
    pub fn annotations(&self) -> &[Annotation] {
        &self.annotations
    }

    /// Mutable access to list annotations.
    pub fn annotations_mut(&mut self) -> &mut Vec<Annotation> {
        &mut self.annotations
    }

    /// Iterate over annotation blocks on the list element.
    pub fn iter_annotations(&self) -> std::slice::Iter<'_, Annotation> {
        self.annotations.iter()
    }

    /// Iterate over all content items nested inside list-level annotations.
    pub fn iter_annotation_contents(&self) -> impl Iterator<Item = &ContentItem> {
        self.annotations
            .iter()
            .flat_map(|annotation| annotation.children())
    }

    /// Lists currently have no standalone header; this always returns `None`.
    pub fn header_location(&self) -> Option<&Range> {
        None
    }

    /// Bounding range covering only the list items.
    pub fn body_location(&self) -> Option<Range> {
        Range::bounding_box(self.items.iter().map(|item| item.range()))
    }
}

impl AstNode for List {
    fn node_type(&self) -> &'static str {
        "List"
    }
    fn display_label(&self) -> String {
        format!("{} items", self.items.len())
    }
    fn range(&self) -> &Range {
        &self.location
    }

    fn accept(&self, visitor: &mut dyn Visitor) {
        visitor.visit_list(self);
        super::super::traits::visit_children(visitor, &self.items);
        visitor.leave_list(self);
    }
}

impl VisualStructure for List {
    fn collapses_with_children(&self) -> bool {
        true
    }
}

impl fmt::Display for List {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "List({} items)", self.items.len())
    }
}

impl ListItem {
    fn default_location() -> Range {
        Range::new(0..0, Position::new(0, 0), Position::new(0, 0))
    }
    pub fn new(marker: String, text: String) -> Self {
        Self::with_content(marker, text, Vec::new())
    }
    pub fn with_content(marker: String, text: String, children: Vec<ContentElement>) -> Self {
        Self::with_text_content(
            TextContent::from_string(marker, None),
            TextContent::from_string(text, None),
            children,
        )
    }
    /// Create a ListItem with TextContent that may have location information
    pub fn with_text_content(
        marker: TextContent,
        text_content: TextContent,
        children: Vec<ContentElement>,
    ) -> Self {
        Self {
            marker,
            text: vec![text_content],
            children: GeneralContainer::from_typed(children),
            annotations: Vec::new(),
            location: Self::default_location(),
        }
    }

    /// Preferred builder
    pub fn at(mut self, location: Range) -> Self {
        self.location = location;
        self
    }
    pub fn text(&self) -> &str {
        self.text[0].as_string()
    }

    pub fn marker(&self) -> &str {
        self.marker.as_string()
    }

    /// Annotations attached to this list item.
    pub fn annotations(&self) -> &[Annotation] {
        &self.annotations
    }

    /// Mutable access to list-item annotations.
    pub fn annotations_mut(&mut self) -> &mut Vec<Annotation> {
        &mut self.annotations
    }

    /// Iterate annotation blocks associated with this list item.
    pub fn iter_annotations(&self) -> std::slice::Iter<'_, Annotation> {
        self.annotations.iter()
    }

    /// Iterate all content items nested inside the list item's annotations.
    pub fn iter_annotation_contents(&self) -> impl Iterator<Item = &ContentItem> {
        self.annotations
            .iter()
            .flat_map(|annotation| annotation.children())
    }
}

impl AstNode for ListItem {
    fn node_type(&self) -> &'static str {
        "ListItem"
    }
    fn display_label(&self) -> String {
        let text = self.text().trim();
        if text.chars().count() > 50 {
            format!("{}…", text.chars().take(50).collect::<String>())
        } else {
            text.to_string()
        }
    }
    fn range(&self) -> &Range {
        &self.location
    }

    fn accept(&self, visitor: &mut dyn Visitor) {
        visitor.visit_list_item(self);
        super::super::traits::visit_children(visitor, &self.children);
        visitor.leave_list_item(self);
    }
}

impl VisualStructure for ListItem {
    fn is_source_line_node(&self) -> bool {
        true
    }
}

impl Container for ListItem {
    fn label(&self) -> &str {
        self.text[0].as_string()
    }
    fn children(&self) -> &[ContentItem] {
        &self.children
    }
    fn children_mut(&mut self) -> &mut Vec<ContentItem> {
        self.children.as_mut_vec()
    }
}

impl fmt::Display for ListItem {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "ListItem('{}')", self.text())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::lex::ast::elements::label::Label;
    use crate::lex::ast::elements::paragraph::Paragraph;
    use crate::lex::ast::elements::typed_content::ContentElement;
    use crate::lex::ast::Data;

    #[test]
    fn test_list() {
        let location = super::super::super::range::Range::new(
            0..0,
            super::super::super::range::Position::new(1, 0),
            super::super::super::range::Position::new(1, 10),
        );
        let list = List::new(vec![]).at(location.clone());
        assert_eq!(list.location, location);
    }

    #[test]
    fn test_list_body_location() {
        let item_range = Range::new(5..10, Position::new(1, 0), Position::new(1, 5));
        let item = ListItem::with_text_content(
            TextContent::from_string("-".to_string(), Some(item_range.clone())),
            TextContent::from_string("Item".to_string(), Some(item_range.clone())),
            Vec::new(),
        )
        .at(item_range.clone());

        let list =
            List::new(vec![item]).at(Range::new(0..15, Position::new(0, 0), Position::new(2, 0)));

        assert!(list.header_location().is_none());
        assert_eq!(list.body_location().unwrap().span, item_range.span);
    }

    #[test]
    fn list_body_location_spans_multiple_items_and_empty_list() {
        let item1_range = Range::new(0..5, Position::new(0, 0), Position::new(0, 5));
        let item2_range = Range::new(10..14, Position::new(1, 0), Position::new(1, 4));

        let item1 = ListItem::with_text_content(
            TextContent::from_string("-".to_string(), Some(item1_range.clone())),
            TextContent::from_string("One".to_string(), Some(item1_range.clone())),
            Vec::new(),
        )
        .at(item1_range.clone());
        let item2 = ListItem::with_text_content(
            TextContent::from_string("-".to_string(), Some(item2_range.clone())),
            TextContent::from_string("Two".to_string(), Some(item2_range.clone())),
            Vec::new(),
        )
        .at(item2_range.clone());

        let list = List::new(vec![item1.clone(), item2.clone()]);
        let body = list
            .body_location()
            .expect("expected bounding box for items");

        assert_eq!(body.span.start, item1_range.span.start);
        assert_eq!(body.span.end, item2_range.span.end);

        let empty_list = List::new(vec![]);
        assert!(empty_list.body_location().is_none());
    }

    #[test]
    fn list_annotation_iteration_exposes_children() {
        let child = ContentItem::Paragraph(Paragraph::from_line("note".to_string()));
        let annotation = Annotation::from_data(
            Data::new(Label::new("meta".into()), Vec::new()),
            vec![ContentElement::try_from(child).unwrap()],
        );

        let mut list = List::new(vec![ListItem::new("-".into(), "Item".into())]);
        list.annotations.push(annotation.clone());

        let contents: Vec<&ContentItem> = list.iter_annotation_contents().collect();
        assert_eq!(contents.len(), 1);

        let mut item = ListItem::new("-".into(), "Item".into());
        item.annotations.push(annotation);
        let item_contents: Vec<&ContentItem> = item.iter_annotation_contents().collect();
        assert_eq!(item_contents.len(), 1);
    }

    #[test]
    fn display_label_truncates_long_text() {
        let long_text = "x".repeat(60);
        let item = ListItem::new("-".into(), long_text.clone());

        let label = item.display_label();
        assert!(label.ends_with("…"));
        assert!(label.chars().count() < long_text.chars().count());

        let short = ListItem::new("-".into(), "short".into());
        assert_eq!(short.display_label(), "short");
    }

    mod sequence_marker_integration {
        use super::*;
        use crate::lex::ast::elements::{DecorationStyle, Form, Separator};
        use crate::lex::ast::ContentItem;
        use crate::lex::loader::DocumentLoader;

        #[test]
        fn parse_extracts_plain_marker() {
            let source = "- Item one\n- Item two";
            let doc = DocumentLoader::from_string(source)
                .parse()
                .expect("parse failed");

            let list = doc
                .root
                .children
                .get(0)
                .and_then(|item| {
                    if let ContentItem::List(list) = item {
                        Some(list)
                    } else {
                        None
                    }
                })
                .expect("expected list");

            assert!(list.marker.is_some());
            let marker = list.marker.as_ref().unwrap();
            assert_eq!(marker.style, DecorationStyle::Plain);
            assert_eq!(marker.separator, Separator::Period);
            assert_eq!(marker.form, Form::Short);
            assert_eq!(marker.raw_text.as_string(), "-");
        }

        #[test]
        fn parse_extracts_numerical_period_marker() {
            let source = "1. First item\n2. Second item";
            let doc = DocumentLoader::from_string(source)
                .parse()
                .expect("parse failed");

            let list = doc
                .root
                .children
                .get(0)
                .and_then(|item| {
                    if let ContentItem::List(list) = item {
                        Some(list)
                    } else {
                        None
                    }
                })
                .expect("expected list");

            assert!(list.marker.is_some());
            let marker = list.marker.as_ref().unwrap();
            assert_eq!(marker.style, DecorationStyle::Numerical);
            assert_eq!(marker.separator, Separator::Period);
            assert_eq!(marker.form, Form::Short);
            assert_eq!(marker.raw_text.as_string(), "1.");
        }

        #[test]
        fn parse_extracts_numerical_paren_marker() {
            let source = "1) First item\n2) Second item";
            let doc = DocumentLoader::from_string(source)
                .parse()
                .expect("parse failed");

            let list = doc
                .root
                .children
                .get(0)
                .and_then(|item| {
                    if let ContentItem::List(list) = item {
                        Some(list)
                    } else {
                        None
                    }
                })
                .expect("expected list");

            assert!(list.marker.is_some());
            let marker = list.marker.as_ref().unwrap();
            assert_eq!(marker.style, DecorationStyle::Numerical);
            assert_eq!(marker.separator, Separator::Parenthesis);
            assert_eq!(marker.form, Form::Short);
            assert_eq!(marker.raw_text.as_string(), "1)");
        }

        #[test]
        fn parse_extracts_alphabetical_marker() {
            let source = "a. Alpha\nb. Beta";
            let doc = DocumentLoader::from_string(source)
                .parse()
                .expect("parse failed");

            let list = doc
                .root
                .children
                .get(0)
                .and_then(|item| {
                    if let ContentItem::List(list) = item {
                        Some(list)
                    } else {
                        None
                    }
                })
                .expect("expected list");

            assert!(list.marker.is_some());
            let marker = list.marker.as_ref().unwrap();
            assert_eq!(marker.style, DecorationStyle::Alphabetical);
            assert_eq!(marker.separator, Separator::Period);
            assert_eq!(marker.form, Form::Short);
            assert_eq!(marker.raw_text.as_string(), "a.");
        }

        #[test]
        fn parse_extracts_roman_marker() {
            let source = "I. First\nII. Second";
            let doc = DocumentLoader::from_string(source)
                .parse()
                .expect("parse failed");

            let list = doc
                .root
                .children
                .get(0)
                .and_then(|item| {
                    if let ContentItem::List(list) = item {
                        Some(list)
                    } else {
                        None
                    }
                })
                .expect("expected list");

            assert!(list.marker.is_some());
            let marker = list.marker.as_ref().unwrap();
            assert_eq!(marker.style, DecorationStyle::Roman);
            assert_eq!(marker.separator, Separator::Period);
            assert_eq!(marker.form, Form::Short);
            assert_eq!(marker.raw_text.as_string(), "I.");
        }

        #[test]
        fn parse_extracts_extended_numerical_marker() {
            let source = "1.2.3 Item\n1.2.4 Item";
            let doc = DocumentLoader::from_string(source)
                .parse()
                .expect("parse failed");

            let list = doc
                .root
                .children
                .get(0)
                .and_then(|item| {
                    if let ContentItem::List(list) = item {
                        Some(list)
                    } else {
                        None
                    }
                })
                .expect("expected list");

            assert!(list.marker.is_some());
            let marker = list.marker.as_ref().unwrap();
            assert_eq!(marker.style, DecorationStyle::Numerical);
            assert_eq!(marker.separator, Separator::Period);
            assert_eq!(marker.form, Form::Extended);
            assert_eq!(marker.raw_text.as_string(), "1.2.3");
        }

        #[test]
        fn parse_extracts_double_paren_marker() {
            let source = "(1) Item one\n(2) Item two";
            let doc = DocumentLoader::from_string(source)
                .parse()
                .expect("parse failed");

            let list = doc
                .root
                .children
                .get(0)
                .and_then(|item| {
                    if let ContentItem::List(list) = item {
                        Some(list)
                    } else {
                        None
                    }
                })
                .expect("expected list");

            assert!(list.marker.is_some());
            let marker = list.marker.as_ref().unwrap();
            assert_eq!(marker.style, DecorationStyle::Numerical);
            assert_eq!(marker.separator, Separator::DoubleParens);
            assert_eq!(marker.form, Form::Short);
            assert_eq!(marker.raw_text.as_string(), "(1)");
        }

        #[test]
        fn empty_list_has_no_marker() {
            let list = List::new(vec![]);
            assert!(list.marker.is_none());
        }
    }
}