lex-core 0.14.1

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
//! Forward codec: lex-core internal AST → `lex_extension::WireNode`.
//!
//! Total over the AST shapes a parsed lex document can produce. Every
//! [`ContentItem`] variant is wired through to a structured [`WireNode`];
//! variants that have no direct slot in the wire form are mapped to the
//! closest equivalent (standalone `TextLine` becomes a single-line
//! [`WireNode::Paragraph`]; `VerbatimLine` outside a block becomes a
//! [`WireNode::Verbatim`] with an empty label) so that the reverse codec
//! can reconstruct a structurally equivalent AST.
//!
//! See the module-level docs in [`super`] for the documented losses
//! (annotation slots on inline nodes, document-level title/annotations,
//! verbatim multi-group bodies, byte-offset spans).

use crate::lex::ast::elements::annotation::Annotation;
use crate::lex::ast::elements::blank_line_group::BlankLineGroup;
use crate::lex::ast::elements::content_item::ContentItem;
use crate::lex::ast::elements::definition::Definition;
use crate::lex::ast::elements::list::{List, ListItem};
use crate::lex::ast::elements::paragraph::{Paragraph, TextLine};
use crate::lex::ast::elements::sequence_marker::DecorationStyle;
use crate::lex::ast::elements::session::Session;
use crate::lex::ast::elements::table::{Table, TableCell, TableCellAlignment};
use crate::lex::ast::elements::verbatim::Verbatim;
use crate::lex::ast::elements::verbatim_line::VerbatimLine;
use crate::lex::ast::Document;
use lex_extension::wire::{
    WireFootnote, WireInline, WireListItem, WireNode, WireRow, WireTableCell,
};
use serde_json::{Map, Value};

use super::inline::text_content_to_wire;
use super::range::{origin_string, range_to_wire};

/// Convert a lex-core `Document` to a `WireNode::Document`.
///
/// The document's root session's children become the wire document's
/// children. Document-level title and document-level annotations are
/// **dropped** in this codec (lex.include's splice path discards both
/// for similar reasons — only the body content is interesting).
pub fn to_wire_document(doc: &Document) -> WireNode {
    let children = doc
        .root
        .children
        .iter()
        .map(to_wire_node)
        .collect::<Vec<_>>();
    WireNode::Document {
        range: range_to_wire(&doc.root.location),
        origin: origin_string(&doc.root.location),
        children,
    }
}

/// Convert a single `ContentItem` to a `WireNode`.
pub fn to_wire_node(item: &ContentItem) -> WireNode {
    match item {
        ContentItem::Paragraph(p) => paragraph_to_wire(p),
        ContentItem::BlankLineGroup(blg) => blank_to_wire(blg),
        ContentItem::Annotation(a) => annotation_to_wire(a),
        ContentItem::Session(s) => session_to_wire(s),
        ContentItem::Definition(d) => definition_to_wire(d),
        ContentItem::List(l) => list_to_wire(l),
        ContentItem::ListItem(li) => list_item_standalone_to_wire(li),
        ContentItem::Table(t) => table_to_wire(t),
        ContentItem::VerbatimBlock(v) => verbatim_to_wire(v),
        ContentItem::VerbatimLine(vl) => verbatim_line_standalone_to_wire(vl),
        ContentItem::TextLine(tl) => text_line_standalone_to_wire(tl),
    }
}

fn paragraph_to_wire(p: &Paragraph) -> WireNode {
    // Walk each TextLine, separating lines with explicit newline
    // inlines so the reverse codec can reconstruct the original
    // multi-line shape. Without the separator, "Hello" + "World"
    // would round-trip as "HelloWorld".
    let mut inlines = Vec::new();
    let mut first_line = true;
    for line_item in &p.lines {
        if let ContentItem::TextLine(line) = line_item {
            if !first_line {
                inlines.push(WireInline::Text { text: "\n".into() });
            }
            inlines.extend(text_content_to_wire(&line.content));
            first_line = false;
        }
    }
    WireNode::Paragraph {
        range: range_to_wire(&p.location),
        origin: origin_string(&p.location),
        inlines,
    }
}

fn blank_to_wire(blg: &BlankLineGroup) -> WireNode {
    WireNode::Blank {
        range: range_to_wire(&blg.location),
        origin: origin_string(&blg.location),
    }
}

fn annotation_to_wire(a: &Annotation) -> WireNode {
    let label = a.data.label.value.clone();
    let params = parameters_to_json(&a.data.parameters);
    let body = annotation_body_to_json(a);
    WireNode::Annotation {
        range: range_to_wire(&a.location),
        origin: origin_string(&a.location),
        label,
        params,
        body,
    }
}

fn session_to_wire(s: &Session) -> WireNode {
    let children = s.children.iter().map(to_wire_node).collect::<Vec<_>>();
    WireNode::Session {
        range: range_to_wire(&s.location),
        origin: origin_string(&s.location),
        // `full_title()` matches what the parser stores in
        // `Session.title` — the title string as authored, including
        // any leading marker. The wire `marker` field is a parallel
        // channel for handlers that want the structured marker
        // without re-parsing the title; the reverse codec pairs them
        // up identically.
        title: s.full_title().to_string(),
        marker: s.marker.as_ref().map(|m| m.as_str().to_string()),
        children,
    }
}

fn definition_to_wire(d: &Definition) -> WireNode {
    let children = d.children.iter().map(to_wire_node).collect::<Vec<_>>();
    WireNode::Definition {
        range: range_to_wire(&d.location),
        origin: origin_string(&d.location),
        subject: d.subject.as_string().to_string(),
        children,
    }
}

fn list_to_wire(l: &List) -> WireNode {
    let marker_style = l
        .marker
        .as_ref()
        .map(|m| decoration_style_name(m.style))
        .unwrap_or("dash")
        .to_string();
    let items = l
        .items
        .iter()
        .filter_map(|item| match item {
            ContentItem::ListItem(li) => Some(list_item_to_wire(li)),
            _ => None,
        })
        .collect();
    WireNode::List {
        range: range_to_wire(&l.location),
        origin: origin_string(&l.location),
        marker_style,
        items,
    }
}

fn list_item_to_wire(li: &ListItem) -> WireListItem {
    // Concatenate every TextContent in `text` into a single inline run,
    // interleaving `\n` separators between continuation lines so a
    // multi-line list-item body round-trips. The reverse codec splits
    // the joined run back into its components.
    let mut inlines = Vec::new();
    for (i, tc) in li.text.iter().enumerate() {
        if i > 0 {
            inlines.push(WireInline::Text { text: "\n".into() });
        }
        inlines.extend(text_content_to_wire(tc));
    }
    let children = li.children.iter().map(to_wire_node).collect();
    WireListItem {
        range: range_to_wire(&li.location),
        inlines,
        children,
    }
}

/// Wire form for a `ListItem` that appears outside a `List` (which the
/// parser does not produce, but the codec must still handle to stay
/// total). Wraps the item as a singleton list with a default marker so
/// the reverse codec produces a valid `List` rather than a malformed
/// node.
fn list_item_standalone_to_wire(li: &ListItem) -> WireNode {
    WireNode::List {
        range: range_to_wire(&li.location),
        origin: origin_string(&li.location),
        marker_style: "dash".into(),
        items: vec![list_item_to_wire(li)],
    }
}

fn table_to_wire(t: &Table) -> WireNode {
    // The wire table format only carries inline content per cell;
    // there is no slot for `TableCell.children` (block-level content
    // inside a cell, populated by the parser when a cell contains a
    // list / definition / nested table). Emitting a `WireNode::Table`
    // for a table with block-content cells would silently drop that
    // content, so we surface those as a structural placeholder
    // instead. The reverse codec recognises the
    // `lex.internal.unsupported.*` prefix and rejects with
    // `FromWireError::UnsupportedKind`, making the loss visible.
    if t.cell_children_iter().next().is_some() {
        return WireNode::Verbatim {
            range: range_to_wire(&t.location),
            origin: origin_string(&t.location),
            label: "lex.internal.unsupported.table_block_cells".into(),
            params: Value::Object(Map::new()),
            body_text: String::new(),
            subject: String::new(),
            mode: "inflow".into(),
        };
    }

    let header_rows = u32::try_from(t.header_rows.len()).unwrap_or(u32::MAX);
    let column_aligns = table_column_aligns(t);
    let rows = t
        .all_rows()
        .map(|row| WireRow {
            cells: row.cells.iter().map(table_cell_to_wire).collect(),
        })
        .collect();
    let footnotes = t
        .footnotes
        .as_deref()
        .map(table_footnotes_to_wire)
        .unwrap_or_default();
    WireNode::Table {
        range: range_to_wire(&t.location),
        origin: origin_string(&t.location),
        caption: t.subject.as_string().to_string(),
        header_rows,
        column_aligns,
        rows,
        footnotes,
    }
}

fn table_cell_to_wire(cell: &TableCell) -> WireTableCell {
    // Cells reaching here have already passed the block-content
    // guard in `table_to_wire`, so `cell.children` is empty by
    // construction.
    debug_assert!(
        !cell.has_block_content(),
        "table_to_wire must short-circuit block-content cells before reaching table_cell_to_wire"
    );
    WireTableCell {
        inlines: text_content_to_wire(&cell.content),
        colspan: u32::try_from(cell.colspan).unwrap_or(1),
        rowspan: u32::try_from(cell.rowspan).unwrap_or(1),
    }
}

/// Produce per-column alignment strings for a table's wire form.
///
/// One entry per column. For each column we pick the alignment of
/// the first non-`None` body cell, falling back to the header cell's
/// alignment when every body cell is `None` (matters for
/// header-only tables and for tables whose body cells inherit from
/// the alignment row implicitly). Columns with no alignment
/// anywhere yield `""`.
///
/// `column_aligns.length` equals the widest row in the table (sum of
/// each cell's `colspan`) — this is what the wire spec uses to define
/// the table's column count. Spanning cells contribute their
/// alignment once to the leftmost covered column; the remaining
/// covered columns receive no signal from that cell.
fn table_column_aligns(t: &Table) -> Vec<String> {
    let row_width = |row: &crate::lex::ast::elements::table::TableRow| -> usize {
        row.cells.iter().map(|c| c.colspan.max(1)).sum::<usize>()
    };
    let column_count = t.all_rows().map(row_width).max().unwrap_or(0);
    let mut aligns: Vec<String> = vec![String::new(); column_count];

    let align_str = |a: TableCellAlignment| -> Option<&'static str> {
        match a {
            TableCellAlignment::Left => Some("left"),
            TableCellAlignment::Center => Some("center"),
            TableCellAlignment::Right => Some("right"),
            TableCellAlignment::None => None,
        }
    };

    let mut fill_pass = |rows: &[crate::lex::ast::elements::table::TableRow]| {
        for row in rows {
            let mut col = 0usize;
            for cell in &row.cells {
                if col >= aligns.len() {
                    break;
                }
                if aligns[col].is_empty() {
                    if let Some(s) = align_str(cell.align) {
                        aligns[col] = s.to_string();
                    }
                }
                col = col.saturating_add(cell.colspan.max(1));
            }
        }
    };

    // First pass: body rows, then header rows for any column still
    // empty (header-only tables and tables whose body cells all happen
    // to be `None` for a given column).
    fill_pass(&t.body_rows);
    fill_pass(&t.header_rows);

    aligns
}

fn table_footnotes_to_wire(footnotes: &List) -> Vec<WireFootnote> {
    footnotes
        .items
        .iter()
        .filter_map(|item| match item {
            ContentItem::ListItem(li) => Some(WireFootnote {
                marker: li.marker.as_string().to_string(),
                inlines: li
                    .text
                    .first()
                    .map(text_content_to_wire)
                    .unwrap_or_default(),
            }),
            _ => None,
        })
        .collect()
}

fn verbatim_to_wire(v: &Verbatim) -> WireNode {
    let label = v.closing_data.label.value.clone();
    let params = parameters_to_json(&v.closing_data.parameters);
    // Body is the first group's content lines joined by `\n`. Multi-
    // group verbatims collapse to their first group in the wire form;
    // the documented loss is acceptable for the current codec
    // consumer (lex.include never returns multi-group verbatims).
    let body_text = v
        .children
        .iter()
        .filter_map(|item| match item {
            ContentItem::VerbatimLine(vl) => Some(vl.content.as_string().to_string()),
            _ => None,
        })
        .collect::<Vec<_>>()
        .join("\n");
    WireNode::Verbatim {
        range: range_to_wire(&v.location),
        origin: origin_string(&v.location),
        label,
        params,
        body_text,
        subject: v.subject.as_string().to_string(),
        mode: verbatim_mode_name(v.mode).to_string(),
    }
}

/// Wire form for a `VerbatimLine` that appears outside a verbatim
/// block. Wraps it as a single-line `Verbatim` carrying an empty label
/// — the reverse codec recognises the empty label and reconstructs a
/// `VerbatimLine`.
fn verbatim_line_standalone_to_wire(vl: &VerbatimLine) -> WireNode {
    WireNode::Verbatim {
        range: range_to_wire(&vl.location),
        origin: origin_string(&vl.location),
        label: String::new(),
        params: Value::Object(Map::new()),
        body_text: vl.content.as_string().to_string(),
        subject: String::new(),
        mode: "inflow".into(),
    }
}

/// Wire form for a `TextLine` that appears outside a `Paragraph`. The
/// parser doesn't produce this directly, but `to_wire_node` must stay
/// total, so we wrap it as a single-line paragraph.
fn text_line_standalone_to_wire(tl: &TextLine) -> WireNode {
    WireNode::Paragraph {
        range: range_to_wire(&tl.location),
        origin: origin_string(&tl.location),
        inlines: text_content_to_wire(&tl.content),
    }
}

fn parameters_to_json(params: &[crate::lex::ast::elements::parameter::Parameter]) -> Value {
    let mut obj = Map::with_capacity(params.len());
    for p in params {
        obj.insert(p.key.clone(), Value::String(p.value.clone()));
    }
    Value::Object(obj)
}

fn annotation_body_to_json(a: &Annotation) -> Value {
    let children = a.children.iter().collect::<Vec<_>>();
    if children.is_empty() {
        return Value::Null;
    }
    let wire_children: Vec<Value> = children
        .iter()
        .map(|c| serde_json::to_value(to_wire_node(c)).expect("wire node serialises"))
        .collect();
    let mut obj = Map::with_capacity(2);
    obj.insert("kind".into(), Value::String("block".into()));
    obj.insert("children".into(), Value::Array(wire_children));
    Value::Object(obj)
}

fn decoration_style_name(style: DecorationStyle) -> &'static str {
    match style {
        DecorationStyle::Plain => "dash",
        DecorationStyle::Numerical => "numerical",
        DecorationStyle::Alphabetical => "alphabetical",
        DecorationStyle::Roman => "roman",
    }
}

fn verbatim_mode_name(
    mode: crate::lex::ast::elements::verbatim::VerbatimBlockMode,
) -> &'static str {
    use crate::lex::ast::elements::verbatim::VerbatimBlockMode;
    match mode {
        VerbatimBlockMode::Inflow => "inflow",
        VerbatimBlockMode::Fullwidth => "fullwidth",
    }
}