lex-babel 0.8.2

Format conversion 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
619
620
621
622
623
624
625
626
627
628
//! Conversion from IR to Lex AST.
//!
//! This module provides functions to convert from the Intermediate Representation
//! back to Lex AST structures.

use lex_core::lex::ast::elements::{
    typed_content, verbatim::VerbatimBlockMode, Annotation as LexAnnotation, ContentElement,
    ContentItem as LexContentItem, Definition as LexDefinition, Label, List as LexList,
    ListItem as LexListItem, Paragraph as LexParagraph, Session as LexSession,
    Verbatim as LexVerbatim, VerbatimContent, VerbatimLine as LexVerbatimLine,
};
use lex_core::lex::ast::range::Position;
use lex_core::lex::ast::{Data, Document as LexDocument, Parameter, Range, TextContent};

use super::nodes::{
    Annotation, Definition, DocNode, Document, Heading, InlineContent, List, ListItem, Paragraph,
    Table, TableCell, TableRow, Verbatim,
};

/// Converts an IR document to a Lex document.
pub fn to_lex_document(doc: &Document) -> LexDocument {
    let mut children = Vec::new();

    for node in &doc.children {
        children.extend(to_lex_content_items(node, 1));
    }

    let mut lex_doc = LexDocument::with_content(children);

    // Restore document title and subtitle from IR
    if let Some(title_inlines) = &doc.title {
        let title_text = inline_content_to_text(title_inlines);
        if !title_text.is_empty() {
            use lex_core::lex::ast::elements::document::DocumentTitle;
            let title_tc = TextContent::from_string(title_text, None);
            let subtitle_tc = doc.subtitle.as_ref().map(|sub_inlines| {
                TextContent::from_string(inline_content_to_text(sub_inlines), None)
            });
            lex_doc.title = Some(match subtitle_tc {
                Some(sub) => DocumentTitle::with_subtitle(title_tc, sub, Range::default()),
                None => DocumentTitle::new(title_tc, Range::default()),
            });
        }
    }

    lex_doc
}

/// Converts an IR DocNode to one or more Lex ContentItems.
///
/// Some IR nodes may expand to multiple ContentItems (e.g., a Heading with children
/// becomes a Session with nested content).
fn to_lex_content_items(node: &DocNode, level: usize) -> Vec<LexContentItem> {
    match node {
        DocNode::Document(_) => {
            // Document should only appear at root, not recursively
            vec![]
        }
        DocNode::Heading(heading) => vec![to_lex_session(heading, level)],
        DocNode::Paragraph(para) => vec![to_lex_paragraph(para)],
        DocNode::List(list) => vec![to_lex_list(list)],
        DocNode::ListItem(item) => vec![to_lex_list_item(item)],
        DocNode::Definition(def) => vec![to_lex_definition(def)],
        DocNode::Verbatim(verb) => vec![to_lex_verbatim(verb)],
        DocNode::Annotation(ann) => vec![to_lex_annotation(ann, level)],
        DocNode::Table(table) => vec![to_lex_table(table, level)],
        DocNode::Image(_) | DocNode::Video(_) | DocNode::Audio(_) => vec![to_lex_media(node)],
        DocNode::Inline(_) => {
            // Inline content should not appear at block level
            vec![]
        }
    }
}

fn to_lex_session(heading: &Heading, level: usize) -> LexContentItem {
    let title_text = inline_content_to_text(&heading.content);
    let title = TextContent::from_string(title_text, None);

    let mut children = Vec::new();
    for child in &heading.children {
        children.extend(to_lex_content_items(child, level + 1));
    }

    // Convert ContentItem to SessionContent
    let session_children = typed_content::into_session_contents(children);

    LexContentItem::Session(LexSession::new(title, session_children))
}

/// Converts an IR Table to a Lex VerbatimBlock via the verbatim registry,
/// falling back to a nested Annotation structure if the registry has no handler.
fn to_lex_table(table: &Table, level: usize) -> LexContentItem {
    let registry = crate::common::verbatim::VerbatimRegistry::default_with_standard();
    let node = DocNode::Table(table.clone());

    if let Some(handler) = registry.get("doc.table") {
        if let Some((content, params)) = handler.convert_from_ir(&node) {
            let label = Label::new("doc.table".to_string());
            let parameters = params
                .into_iter()
                .map(|(k, v)| Parameter {
                    key: k,
                    value: v,
                    location: default_range(),
                })
                .collect();

            let subject = TextContent::from_string("".to_string(), None);
            let lines = content
                .lines()
                .map(|l| VerbatimContent::VerbatimLine(LexVerbatimLine::new(l.to_string())))
                .collect();

            let closing_data = Data::new(label, parameters);

            return LexContentItem::VerbatimBlock(Box::new(LexVerbatim::new(
                subject,
                lines,
                closing_data,
                VerbatimBlockMode::Inflow,
            )));
        }
    }

    // Fallback to annotation if registry fails (though TableHandler should handle it)
    let label = Label::new("table".to_string());
    let parameters = Vec::new(); // Could add caption here if needed

    let mut children = Vec::new();

    // Header
    if !table.header.is_empty() {
        let thead_label = Label::new("thead".to_string());
        let mut thead_rows = Vec::new();
        for row in &table.header {
            thead_rows.push(to_lex_table_row(row, level + 1));
        }
        let thead = LexContentItem::Annotation(LexAnnotation::new(
            thead_label,
            Vec::new(),
            to_content_elements(thead_rows),
        ));
        children.push(thead);
    }

    // Body (rows)
    let tbody_label = Label::new("tbody".to_string());
    let mut tbody_rows = Vec::new();
    for row in &table.rows {
        tbody_rows.push(to_lex_table_row(row, level + 1));
    }
    let tbody = LexContentItem::Annotation(LexAnnotation::new(
        tbody_label,
        Vec::new(),
        to_content_elements(tbody_rows),
    ));
    children.push(tbody);

    LexContentItem::Annotation(LexAnnotation::new(
        label,
        parameters,
        to_content_elements(children),
    ))
}

fn to_lex_table_row(row: &TableRow, level: usize) -> LexContentItem {
    let label = Label::new("tr".to_string());
    let mut cells = Vec::new();
    for cell in &row.cells {
        cells.push(to_lex_table_cell(cell, level + 1));
    }
    LexContentItem::Annotation(LexAnnotation::new(
        label,
        Vec::new(),
        to_content_elements(cells),
    ))
}

fn to_lex_table_cell(cell: &TableCell, level: usize) -> LexContentItem {
    let label_str = if cell.header { "th" } else { "td" };
    let label = Label::new(label_str.to_string());

    let mut parameters = Vec::new();
    // Handle alignment
    let align_val = match cell.align {
        crate::ir::nodes::TableCellAlignment::Left => Some("left"),
        crate::ir::nodes::TableCellAlignment::Center => Some("center"),
        crate::ir::nodes::TableCellAlignment::Right => Some("right"),
        crate::ir::nodes::TableCellAlignment::None => None,
    };
    if let Some(align) = align_val {
        parameters.push(Parameter {
            key: "align".to_string(),
            value: align.to_string(),
            location: default_range(),
        });
    }

    let mut content = Vec::new();
    for child in &cell.content {
        content.extend(to_lex_content_items(child, level + 1));
    }

    LexContentItem::Annotation(LexAnnotation::new(
        label,
        parameters,
        to_content_elements(content),
    ))
}

/// Converts an IR Paragraph to a Lex Paragraph.
fn to_lex_paragraph(para: &Paragraph) -> LexContentItem {
    let text = inline_content_to_text(&para.content);
    LexContentItem::Paragraph(LexParagraph::from_line(text))
}

/// Converts an IR List to a Lex List.
///
/// Derives marker text for each item from the List's style and the item's position.
fn to_lex_list(list: &List) -> LexContentItem {
    let items: Vec<LexListItem> = list
        .items
        .iter()
        .enumerate()
        .map(|(i, item)| to_lex_list_item_with_style(item, &list.style, i + 1))
        .collect();
    LexContentItem::List(LexList::new(items))
}

/// Converts an IR ListItem to a Lex ListItem with a marker derived from style and position.
fn to_lex_list_item_with_style(
    item: &ListItem,
    style: &super::nodes::ListStyle,
    index: usize,
) -> LexListItem {
    let marker = format_marker_for_style(style, index);
    let text = inline_content_to_text(&item.content);

    let mut child_items = Vec::new();
    for child in &item.children {
        child_items.extend(to_lex_content_items(child, 1));
    }

    let children = to_content_elements(child_items);
    LexListItem::with_content(marker, text, children)
}

/// Formats a marker string from a ListStyle and 1-based index.
fn format_marker_for_style(style: &super::nodes::ListStyle, index: usize) -> String {
    use super::nodes::ListStyle;
    match style {
        ListStyle::Bullet => "-".to_string(),
        ListStyle::Numeric => format!("{index}."),
        ListStyle::AlphaLower => {
            let c = if (1..=26).contains(&index) {
                char::from_u32((index as u32) + 96).unwrap()
            } else {
                return format!("{index}.");
            };
            format!("{c}.")
        }
        ListStyle::AlphaUpper => {
            let c = if (1..=26).contains(&index) {
                char::from_u32((index as u32) + 64).unwrap()
            } else {
                return format!("{index}.");
            };
            format!("{c}.")
        }
        ListStyle::RomanLower => {
            let roman = to_roman_lower(index);
            format!("{roman}.")
        }
        ListStyle::RomanUpper => {
            let roman = to_roman_upper(index);
            format!("{roman}.")
        }
    }
}

fn to_roman_lower(n: usize) -> String {
    to_roman_upper(n).to_lowercase()
}

fn to_roman_upper(n: usize) -> String {
    match n {
        1 => "I",
        2 => "II",
        3 => "III",
        4 => "IV",
        5 => "V",
        6 => "VI",
        7 => "VII",
        8 => "VIII",
        9 => "IX",
        10 => "X",
        11 => "XI",
        12 => "XII",
        13 => "XIII",
        14 => "XIV",
        15 => "XV",
        16 => "XVI",
        17 => "XVII",
        18 => "XVIII",
        19 => "XIX",
        20 => "XX",
        _ => return n.to_string(),
    }
    .to_string()
}

/// Converts an IR ListItem to a ContentItem::ListItem.
fn to_lex_list_item(item: &ListItem) -> LexContentItem {
    LexContentItem::ListItem(to_lex_list_item_struct(item))
}

/// Converts an IR ListItem to a Lex ListItem struct.
///
/// The marker is derived from the parent List's style/form and the item's
/// position, not from the item's inline content.
fn to_lex_list_item_struct(item: &ListItem) -> LexListItem {
    // Default marker — callers should use to_lex_list which provides proper markers
    let marker = "-".to_string();
    let text = inline_content_to_text(&item.content);

    let mut child_items = Vec::new();
    for child in &item.children {
        child_items.extend(to_lex_content_items(child, 1));
    }

    let children = to_content_elements(child_items);
    LexListItem::with_content(marker, text, children)
}

/// Converts an IR Definition to a Lex Definition.
fn to_lex_definition(def: &Definition) -> LexContentItem {
    let term_text = inline_content_to_text(&def.term);
    let term = TextContent::from_string(term_text, None);

    let mut child_items = Vec::new();
    for child in &def.description {
        child_items.extend(to_lex_content_items(child, 1));
    }

    let children = to_content_elements(child_items);
    LexContentItem::Definition(LexDefinition::new(term, children))
}

/// Converts an IR Verbatim to a Lex Verbatim block.
fn to_lex_verbatim(verb: &Verbatim) -> LexContentItem {
    let subject_text = verb.subject.clone().unwrap_or_default();
    let subject = TextContent::from_string(subject_text, None);

    // Split content into lines and create VerbatimLine items
    let lines: Vec<VerbatimContent> = verb
        .content
        .lines()
        .map(|line| VerbatimContent::VerbatimLine(LexVerbatimLine::new(line.to_string())))
        .collect();

    // Create closing data with language label
    let label_text = verb.language.clone().unwrap_or_default();
    let label = Label::new(label_text);
    let closing_data = Data::new(label, Vec::new());

    LexContentItem::VerbatimBlock(Box::new(LexVerbatim::new(
        subject,
        lines,
        closing_data,
        VerbatimBlockMode::Inflow,
    )))
}

/// Converts an IR Annotation to a Lex Annotation.
fn to_lex_annotation(ann: &Annotation, level: usize) -> LexContentItem {
    let label = Label::new(ann.label.clone());
    let parameters: Vec<Parameter> = ann
        .parameters
        .iter()
        .map(|(k, v)| Parameter {
            key: k.clone(),
            value: v.clone(),
            location: default_range(),
        })
        .collect();

    let mut child_items = Vec::new();
    for child in &ann.content {
        child_items.extend(to_lex_content_items(child, level));
    }

    let children = to_content_elements(child_items);
    LexContentItem::Annotation(LexAnnotation::new(label, parameters, children))
}

/// Converts IR inline content to plain text string.
///
/// This is a lossy conversion that flattens all inline formatting.
fn inline_content_to_text(content: &[InlineContent]) -> String {
    content
        .iter()
        .map(|inline| match inline {
            InlineContent::Text(text) => text.clone(),
            InlineContent::Bold(children) => {
                format!("*{}*", inline_content_to_text(children))
            }
            InlineContent::Italic(children) => {
                format!("_{}_", inline_content_to_text(children))
            }
            InlineContent::Code(code) => format!("`{code}`"),
            InlineContent::Math(math) => format!("#{math}#"),
            InlineContent::Reference(ref_text) => format!("[{ref_text}]"),
            InlineContent::Link { text, href } => format!("{text} [{href}]"),
            InlineContent::Image(image) => {
                let mut text = format!("![{}]({})", image.alt, image.src);
                if let Some(title) = &image.title {
                    text.push_str(&format!(" \"{title}\""));
                }
                text
            }
        })
        .collect()
}

/// Converts ContentItem to ContentElement, filtering out Sessions and ListItems
fn to_content_elements(items: Vec<LexContentItem>) -> Vec<ContentElement> {
    items
        .into_iter()
        .filter_map(|item| item.try_into().ok())
        .collect()
}

/// Helper to create a default Range
fn default_range() -> Range {
    Range::new(0..0, Position::new(0, 0), Position::new(0, 0))
}

fn to_lex_media(node: &DocNode) -> LexContentItem {
    let registry = crate::common::verbatim::VerbatimRegistry::default_with_standard();

    let label = match node {
        DocNode::Image(_) => "doc.image",
        DocNode::Video(_) => "doc.video",
        DocNode::Audio(_) => "doc.audio",
        _ => return LexContentItem::Paragraph(LexParagraph::new(vec![])),
    };

    if let Some(handler) = registry.get(label) {
        if let Some((content, params)) = handler.convert_from_ir(node) {
            let label = Label::new(label.to_string());
            let parameters = params
                .into_iter()
                .map(|(k, v)| Parameter {
                    key: k,
                    value: v,
                    location: default_range(),
                })
                .collect();

            let subject = TextContent::from_string("".to_string(), None);
            let lines = content
                .lines()
                .map(|l| VerbatimContent::VerbatimLine(LexVerbatimLine::new(l.to_string())))
                .collect();

            let closing_data = Data::new(label, parameters);

            return LexContentItem::VerbatimBlock(Box::new(LexVerbatim::new(
                subject,
                lines,
                closing_data,
                VerbatimBlockMode::Inflow,
            )));
        }
    }

    LexContentItem::Paragraph(LexParagraph::new(vec![]))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ir::nodes::*;

    #[test]
    fn test_paragraph_to_lex() {
        let ir_para = Paragraph {
            content: vec![InlineContent::Text("Hello world".to_string())],
        };

        let lex_item = to_lex_paragraph(&ir_para);

        match lex_item {
            LexContentItem::Paragraph(para) => {
                assert_eq!(para.text(), "Hello world");
            }
            _ => panic!("Expected Paragraph"),
        }
    }

    #[test]
    fn test_heading_to_session() {
        let ir_heading = Heading {
            level: 1,
            content: vec![InlineContent::Text("Test".to_string())],
            children: vec![],
        };

        let lex_item = to_lex_session(&ir_heading, 1);

        match lex_item {
            LexContentItem::Session(session) => {
                assert!(session.title.as_string().contains("Test"));
            }
            _ => panic!("Expected Session"),
        }
    }

    #[test]
    fn test_list_to_lex() {
        let ir_list = List {
            items: vec![
                ListItem {
                    content: vec![InlineContent::Text("Item 1".to_string())],
                    children: vec![],
                },
                ListItem {
                    content: vec![InlineContent::Text("Item 2".to_string())],
                    children: vec![],
                },
            ],
            ordered: false,
            style: ListStyle::Bullet,
            form: ListForm::Short,
        };

        let lex_item = to_lex_list(&ir_list);

        match lex_item {
            LexContentItem::List(list) => {
                // Lists contain ListItem children
                assert!(!list.items.is_empty());
            }
            _ => panic!("Expected List"),
        }
    }

    #[test]
    fn test_verbatim_with_language() {
        let ir_verb = Verbatim {
            subject: None,
            language: Some("rust".to_string()),
            content: "fn main() {}\nlet x = 1;".to_string(),
        };

        let lex_item = to_lex_verbatim(&ir_verb);

        match lex_item {
            LexContentItem::VerbatimBlock(verb) => {
                assert_eq!(verb.closing_data.label.value, "rust");
                // Should have 2 lines
                assert_eq!(verb.children.len(), 2);
            }
            _ => panic!("Expected VerbatimBlock"),
        }
    }

    #[test]
    fn test_inline_formatting_to_text() {
        let content = vec![
            InlineContent::Text("Plain ".to_string()),
            InlineContent::Bold(vec![InlineContent::Text("bold".to_string())]),
            InlineContent::Text(" ".to_string()),
            InlineContent::Italic(vec![InlineContent::Text("italic".to_string())]),
            InlineContent::Text(" ".to_string()),
            InlineContent::Code("code".to_string()),
        ];

        let text = inline_content_to_text(&content);

        assert!(text.contains("Plain"));
        assert!(text.contains("*bold*"));
        assert!(text.contains("_italic_"));
        assert!(text.contains("`code`"));
    }

    #[test]
    fn test_round_trip_paragraph() {
        use crate::{from_ir, to_ir};
        use lex_core::lex::ast::ContentItem;
        use lex_core::lex::ast::Document as LexDocument;

        // Create a Lex document with a paragraph
        let original_lex = LexDocument::with_content(vec![ContentItem::Paragraph(
            LexParagraph::from_line("Test content".to_string()),
        )]);

        // Convert to IR
        let ir_doc = to_ir(&original_lex);

        // Convert back to Lex
        let back_to_lex = from_ir(&ir_doc);

        // Check the content is preserved
        assert!(!back_to_lex.root.children.is_empty());
    }

    #[test]
    fn test_full_document_to_lex() {
        let ir_doc = Document {
            title: None,
            subtitle: None,
            children: vec![
                DocNode::Paragraph(Paragraph {
                    content: vec![InlineContent::Text("First paragraph".to_string())],
                }),
                DocNode::Paragraph(Paragraph {
                    content: vec![InlineContent::Text("Second paragraph".to_string())],
                }),
            ],
        };

        let lex_doc = to_lex_document(&ir_doc);

        // Document should have root session with our content
        assert!(!lex_doc.root.children.is_empty());
    }
}