mant-engine 0.11.0

Structured manual and Markdown document engine used by ManT
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
//! Existing regressions grouped by tables behavior; expected values remain independent.
use super::*;

#[test]
fn lowers_tbl_and_eqn_payloads_into_structured_blocks() {
    let path = temporary_source(
        "table-equation",
        ".TH PAYLOAD 1\n.SH TABLE\n.TS\ntab(|);\nl r.\nleft|right\n.TE\n\
         .SH EQUATION\n.EQ\nx + {width over 2}\n.EN\n",
    );

    let document = parse_manual_source(&path).expect("lower table and equation");
    fs::remove_file(path).expect("remove temporary roff fixture");

    assert!(matches!(
        document.sections[0].blocks[0],
        Block::Table { ref rows, .. } if rows.len() == 1 && rows[0].cells.len() == 2
    ));
    assert!(matches!(
        document.sections[1].blocks[0],
        Block::Equation { ref value, .. } if value == "x + width / 2"
    ));
}

#[test]
fn large_tbl_rows_scale_without_changing_their_topology() {
    const ROW_COUNT: usize = 2_048;
    let mut source = String::from(".TH TABLE-SCALE 7\n.SH TABLE\n.TS\nl l.\n");
    for index in 0..ROW_COUNT {
        writeln!(source, "left {index}\tright {index}").expect("append table row");
    }
    source.push_str(".TE\n");

    let document = parse_manual_bytes(std::path::Path::new("table-scale.7"), source.as_bytes())
        .expect("lower large table");

    let [Block::Table { rows, .. }] = document.sections[0].blocks.as_slice() else {
        panic!("large tbl input must remain one table");
    };
    assert_eq!(rows.len(), ROW_COUNT);
    assert!(matches!(
        rows.first().and_then(|row| row.cells.first()),
        Some(mant_ir::TableCell { blocks, .. })
            if matches!(blocks.as_slice(), [Block::Paragraph { children, .. }]
                if inline_text(children) == "left 0")
    ));
    assert!(matches!(
        rows.last().and_then(|row| row.cells.get(1)),
        Some(mant_ir::TableCell { blocks, .. })
            if matches!(blocks.as_slice(), [Block::Paragraph { children, .. }]
                if inline_text(children) == format!("right {}", ROW_COUNT - 1))
    ));
}

#[test]
fn keeps_inline_equations_in_macro_arguments_and_filled_prose() {
    let document = parse_manual_bytes(
        std::path::Path::new("inline-equation.7"),
        b".TH EQNPROBE2 7\n.SH DESCRIPTION\n.EQ\ndelim $$\n.EN\n.TP\n.BR Dp\\~ \"$dx sub 1 ~ ldots ~ dx sub n$\"\nDraw a polygon with,\nfor $i = 1 , ldots , n + 1$,\nits vertex.\n",
    )
    .expect("lower inline equations");

    let [Block::DefinitionList { items, .. }] = document.sections[0].blocks.as_slice() else {
        panic!(
            "expected one definition list: {:?}",
            document.sections[0].blocks
        );
    };
    let [item] = items.as_slice() else {
        panic!("expected one equation definition");
    };
    assert_eq!(inline_text(&item.terms[0]), "Dp dx _ 1 ... dx _ n");
    let [Block::Paragraph { children, .. }] = item.description.as_slice() else {
        panic!("expected one filled description: {:?}", item.description);
    };
    assert_eq!(
        inline_text(children),
        "Draw a polygon with, for i = 1 , ... , n + 1, its vertex."
    );
    assert!(
        children
            .iter()
            .any(|child| matches!(child, Inline::Code { value } if value == "i = 1 , ... , n + 1"))
    );
}

#[test]
fn normalizes_inline_equations_retained_as_tbl_cell_text() {
    let document = parse_manual_bytes(
        std::path::Path::new("table-inline-equation.3"),
        b".TH TABLE-EQN 3\n.SH DESCRIPTION\n.EQ\ndelim %%\n.EN\n.TS\nl l.\n%0%\tfor values in % [ 0 , ~pi over 2 ]%\n.TE\n",
    )
    .expect("lower table equations");

    let Block::Table { rows, .. } = &document.sections[0].blocks[0] else {
        panic!("expected equation table");
    };
    let [left, right] = rows[0].cells.as_slice() else {
        panic!("expected two cells");
    };
    let [Block::Paragraph { children: left, .. }] = left.blocks.as_slice() else {
        panic!("expected left paragraph");
    };
    let [
        Block::Paragraph {
            children: right, ..
        },
    ] = right.blocks.as_slice()
    else {
        panic!("expected right paragraph");
    };
    assert!(matches!(left.as_slice(), [Inline::Code { value }] if value == "0"));
    assert_eq!(inline_text(right), "for values in [ 0 , π / 2 ]");
    assert!(
        right
            .iter()
            .any(|child| matches!(child, Inline::Code { .. }))
    );
}

#[test]
fn preserves_tbl_rows_across_interleaved_comments_and_text_blocks() {
    let source = b".TH COMMENTED-TABLE 1\n.SH TABLE\n.TS\nl l.\na\t1\n.\\\" disabled text block T{\n.\\\" ignored\n.\\\" T}\nb\t2\nc\t3\nT{\n.BR d (1)\nT}\t4\ne\t5\n.TE\n";
    let document = parse_manual_bytes(std::path::Path::new("commented-table.1"), source)
        .expect("lower commented table");

    let Block::Table { rows, .. } = &document.sections[0].blocks[0] else {
        panic!("expected a table");
    };
    assert_eq!(rows.len(), 5);
    let first_cells = rows
        .iter()
        .map(|row| match row.cells[0].blocks.as_slice() {
            [Block::Paragraph { children, .. }] => inline_text(children),
            cells => panic!("expected one paragraph per table cell: {cells:?}"),
        })
        .collect::<Vec<_>>();
    assert_eq!(first_cells, ["a", "b", "c", "d(1)", "e"]);
}

#[test]
fn keeps_tbl_vertical_span_markers_out_of_visible_cells() {
    let document = parse_manual_bytes(
        std::path::Path::new("vertical-table-span.1"),
        b".TH VERTICAL-TABLE-SPAN 1\n.SH ATTRIBUTES\n.TS\nl l l.\nInterface\tAttribute\tValue\nT{\n.BR demo (1)\nT}\tThread safety\tMT-Safe\n\\^\tAsync-signal safety\tAS-Unsafe\n\\^\tAsync-cancel safety\tAC-Unsafe\n.TE\n",
    )
    .expect("lower vertical table span");

    let Block::Table { rows, .. } = &document.sections[0].blocks[0] else {
        panic!("expected a table");
    };
    assert_eq!(rows.len(), 4);
    assert_eq!(rows[1].cells[0].row_span, 3);
    assert!(rows[2].cells[0].blocks.is_empty());
    assert!(rows[3].cells[0].blocks.is_empty());
}

#[test]
fn preserves_tbl_rows_nested_in_unfilled_mdoc_displays() {
    let document = parse_manual_bytes(
        std::path::Path::new("unfilled-table.7"),
        b".Dd August 19, 2026\n.Dt UNFILLED-TABLE 7\n.Os\n.Sh DESCRIPTION\n\
.Bd -unfilled -offset indent\n.TS\ntab(@);\nl l.\nleft@right\nnext@value\n.TE\n.Ed\n",
    )
    .expect("lower table nested in an unfilled display");

    let table = document.sections[0]
        .blocks
        .iter()
        .find_map(|block| match block {
            Block::Table { rows, .. } => Some(rows),
            _ => None,
        })
        .expect("nested table must remain structured");
    assert_eq!(table.len(), 2);
    assert_eq!(table[0].cells.len(), 2);
    assert!(
        document.sections[0].blocks.iter().all(
            |block| !matches!(block, Block::Preformatted { children, .. } if children.is_empty())
        ),
        "the surrounding display must not leave an empty placeholder"
    );
}

#[test]
fn restores_mdoc_names_inside_tbl_text_blocks() {
    let document = parse_manual_bytes(
        std::path::Path::new("table-text-block.3"),
        b".Dd August 19, 2026\n.Dt TABLE-TEXT-BLOCK 3\n.Os\n\
.Sh NAME\n.Nm table-text-block\n.Nd test tbl text blocks\n\
.Sh ATTRIBUTES\n.TS\nallbox;\nl l.\nInterface\tValue\n\
T{\n.Nm\nT}\tMT-Safe\n.TE\n",
    )
    .expect("lower tbl text blocks");

    let Block::Table { rows, .. } = &document.sections[1].blocks[0] else {
        panic!("expected attributes table");
    };
    let [Block::Paragraph { children, .. }] = rows[1].cells[0].blocks.as_slice() else {
        panic!("expected recovered name cell");
    };
    assert_eq!(inline_text(children), "table-text-block");
    assert!(matches!(children.as_slice(), [Inline::Strong { .. }]));
}

#[test]
fn restores_alternating_font_arguments_inside_tbl_text_blocks() {
    let document = parse_manual_bytes(
        std::path::Path::new("table-text-alternation.7"),
        b".TH TABLE-TEXT-ALTERNATION 7\n.SH DESCRIPTION\n.TS\nl l.\nT{\n\
.BI \\[aq] s1 \\[aq] s2 \\[aq]\nT}\tT{\n\
.I s1\nproduces the same formatted output as\n.IR s2 .\nT}\n.TE\n",
    )
    .expect("lower alternating man macros inside a tbl text block");

    let Block::Table { rows, .. } = &document.sections[0].blocks[0] else {
        panic!("expected a structured table");
    };
    let [left, right] = rows[0].cells.as_slice() else {
        panic!("expected both reconstructed table cells");
    };
    let [Block::Paragraph { children: left, .. }] = left.blocks.as_slice() else {
        panic!("expected a reconstructed left table-cell paragraph");
    };
    let [
        Block::Paragraph {
            children: right, ..
        },
    ] = right.blocks.as_slice()
    else {
        panic!("expected a reconstructed right table-cell paragraph");
    };
    assert_eq!(inline_text(left), "'s1's2'");
    assert_eq!(
        inline_text(right),
        "s1 produces the same formatted output as s2."
    );
    assert!(
        right
            .iter()
            .any(|inline| matches!(inline, Inline::Emphasis { .. }))
    );
}

#[test]
fn mixed_mdoc_table_requests_preserve_content_when_block_semantics_are_unsupported() {
    for body in [
        ".Cm TOKENA\n.Pp\nTOKENB",
        ".Em TOKENA\n.Bl -bullet\n.It\nTOKENB\n.El",
        ".Cm TOKENA\n.Bd -literal\nTOKENB\n.Ed",
    ] {
        let source = format!(
            ".Dd September 6, 2026\n.Dt MIXED 1\n.Os\n.Sh DESCRIPTION\n.TS\nl.\nT{{\n{body}\nT}}\n.TE\n"
        );
        let query = mant_loader::load_roff_bytes(source.as_bytes()).unwrap();
        let text = mant_render::render_query_text(&query);
        assert!(
            text.contains("TOKENA") && text.contains("TOKENB"),
            "{source}: {text}"
        );
        assert_eq!(text.matches("TOKENA").count(), 1, "{text}");
        assert_eq!(text.matches("TOKENB").count(), 1, "{text}");
        assert!(
            query
                .document
                .as_ref()
                .unwrap()
                .diagnostics
                .iter()
                .any(|d| d.code.as_deref() == Some("manual.unhandled-table-text-block"))
        );
    }
}

#[test]
fn mixed_table_requests_never_replace_complete_content_with_partial_recovery() {
    for font in ["B", "I", "BR"] {
        for paragraph in ["PP", "TP"] {
            for apostrophe in [false, true] {
                let control = if apostrophe { "'" } else { "." };
                let source = format!(
                    ".TH MIXED 1\n.SH DESCRIPTION\n.TS\nl l.\nT{{\n{control}{font} TOKENA\n{control}{paragraph}\nTOKENB\nT}}\tNEIGHBOR\n.TE\n"
                );
                let document =
                    parse_manual_bytes(std::path::Path::new("mixed-table.1"), source.as_bytes())
                        .unwrap();
                let [Block::Table { rows, .. }] = document.sections[0].blocks.as_slice() else {
                    panic!("table structure must survive {source}")
                };
                let [Block::Paragraph { children, .. }] = rows[0].cells[0].blocks.as_slice() else {
                    panic!("table cell")
                };
                let text = inline_text(children);
                assert!(
                    text.contains("TOKENA") && text.contains("TOKENB"),
                    "{source}: {text}"
                );
                assert!(text.find("TOKENA") < text.find("TOKENB"));
                assert!(!text.contains("NEIGHBOR"));
                assert_eq!(text.matches("TOKENA").count(), 1);
                assert_eq!(text.matches("TOKENB").count(), 1);
                assert!(
                    document
                        .diagnostics
                        .iter()
                        .any(|d| d.code.as_deref() == Some("manual.unhandled-table-text-block"))
                );
            }
        }
    }
}

#[test]
fn table_inline_requests_match_their_native_dialect_and_keep_cross_line_state() {
    for (header, request, expected) in [
        (
            ".Dd September 5, 2026\n.Dt PROBE 1\n.Os\n.Sh DESCRIPTION",
            ".Fl Fl help",
            "--help",
        ),
        (
            ".Dd September 5, 2026\n.Dt PROBE 1\n.Os\n.Sh DESCRIPTION",
            ".Cm TOKENA Ns : Ns Ar TOKENB",
            "TOKENA:TOKENB",
        ),
        (
            ".Dd September 5, 2026\n.Dt PROBE 1\n.Os\n.Sh DESCRIPTION",
            ".Oo Fl a Oc No TOKENA",
            "[-a] TOKENA",
        ),
        (
            ".Dd September 5, 2026\n.Dt PROBE 1\n.Os\n.Sh DESCRIPTION",
            ".Sm off\n.Cm TOKENA\n.Ar TOKENB\n.Sm on\n.No TOKENC",
            "TOKENATOKENB TOKENC",
        ),
        (
            ".Dd September 5, 2026\n.Dt PROBE 1\n.Os\n.Sh DESCRIPTION",
            ".Oo\n.Fl a\n.Oc\n.No TOKENA",
            "[-a] TOKENA",
        ),
        (".TH PROBE 1\n.SH DESCRIPTION", ".B Fl", "Fl"),
        (".TH PROBE 1\n.SH DESCRIPTION", ".I Ar Ns Op", "Ar Ns Op"),
    ] {
        let table_source = format!("{header}\n.TS\nl.\nT{{\n{request}\nT}}\n.TE\n");
        let table =
            parse_manual_bytes(std::path::Path::new("table.1"), table_source.as_bytes()).unwrap();
        let plain_source = format!("{header}\n{request}\n");
        let plain =
            parse_manual_bytes(std::path::Path::new("plain.1"), plain_source.as_bytes()).unwrap();
        let [Block::Table { rows, .. }] = table.sections[0].blocks.as_slice() else {
            panic!("expected table: {table:#?}")
        };
        let [Block::Paragraph { children, .. }] = rows[0].cells[0].blocks.as_slice() else {
            panic!("expected cell paragraph")
        };
        let actual = inline_text(children);
        assert_eq!(actual, expected, "{request}");
        let [Block::Paragraph { children, .. }] = plain.sections[0].blocks.as_slice() else {
            panic!("expected native paragraph")
        };
        assert_eq!(
            actual,
            inline_text(children),
            "body/table disagreement for {request}"
        );
    }
}

#[test]
fn restores_nested_mdoc_requests_inside_tbl_text_blocks() {
    let document = parse_manual_bytes(
        std::path::Path::new("table-mdoc-requests.8"),
        b".Dd August 19, 2026\n.Dt TABLE-MDOC-REQUESTS 8\n.Os\n.Sh DESCRIPTION\n\
.TS\ntab(@);\nl l.\nT{\n.Cm sip Ar addr Ns Op / Ns Ar mask\nT}@T{\n\
bitwise and of the address with\n.Ar mask\nequals\n.Ar addr .\n.Ar addr\n\
can be an IPv4 or IPv6 address.\nT}\n.TE\n",
    )
    .expect("lower nested mdoc requests in table text blocks");

    let Block::Table { rows, .. } = &document.sections[0].blocks[0] else {
        panic!("expected a structured table");
    };
    let [left, right] = rows[0].cells.as_slice() else {
        panic!("expected two reconstructed table cells");
    };
    let [Block::Paragraph { children: left, .. }] = left.blocks.as_slice() else {
        panic!("expected reconstructed selector cell");
    };
    let [
        Block::Paragraph {
            children: right, ..
        },
    ] = right.blocks.as_slice()
    else {
        panic!("expected reconstructed description cell");
    };
    assert_eq!(inline_text(left), "sip addr[/mask]");
    assert_eq!(
        inline_text(right),
        "bitwise and of the address with mask equals addr. addr can be an IPv4 or IPv6 address."
    );
    assert!(
        left.iter()
            .any(|inline| matches!(inline, Inline::Strong { .. }))
    );
    assert!(
        right
            .iter()
            .any(|inline| matches!(inline, Inline::Emphasis { .. }))
    );
}

#[test]
fn decodes_named_characters_inside_equations() {
    let document = parse_manual_bytes(
        std::path::Path::new("equation-characters.1"),
        b".TH EQUATION-CHARACTERS 1\n.SH EQUATION\n.EQ\n\\[*p] \\[mi] x\n.EN\n",
    )
    .expect("lower equation characters");

    assert!(matches!(
        document.sections[0].blocks[0],
        Block::Equation { ref value, .. } if value == "\u{03c0} \u{2212} x"
    ));
}

#[test]
fn lowers_every_mdoc_column_list_cell() {
    let document = parse_manual_bytes(
        std::path::Path::new("columns.3"),
        b".Dd August 19, 2026\n.Dt COLUMNS 3\n.Os\n.Sh DESCRIPTION\n\
.Bl -column name type description\n.It Dv CLSET_TIMEOUT Ta \"struct timeval *\" Ta \"set total timeout\"\n.El\n",
    )
    .expect("lower mdoc column list");

    let Block::Table { rows, .. } = &document.sections[0].blocks[0] else {
        panic!("expected column list to lower as a table");
    };
    assert_eq!(rows.len(), 1);
    assert_eq!(rows[0].cells.len(), 3);
    let rendered = rows[0]
        .cells
        .iter()
        .map(|cell| match cell.blocks.as_slice() {
            [Block::Paragraph { children, .. }] => inline_text(children),
            blocks => panic!("expected one paragraph per cell, got {blocks:?}"),
        })
        .collect::<Vec<_>>();
    assert_eq!(
        rendered,
        ["CLSET_TIMEOUT", "struct timeval *", "set total timeout"]
    );
}

#[test]
fn keeps_unexpanded_tabular_cells_visible_with_a_diagnostic() {
    let document = parse_manual_bytes(
        std::path::Path::new("unexpanded-table-cell.7"),
        b".TH UNEXPANDED-TABLE-CELL 7\n.SH DESCRIPTION\n.TS\nl l.\n1\t\\*[unknown-label]\n.TE\n",
    )
    .expect("lower unresolved formatter string in a table cell");

    let Block::Table { rows, .. } = &document.sections[0].blocks[0] else {
        panic!("expected a structured table");
    };
    assert_eq!(rows[0].cells.len(), 2);
    let [Block::Paragraph { children, .. }] = rows[0].cells[1].blocks.as_slice() else {
        panic!("expected one recovered table-cell paragraph");
    };
    assert_eq!(inline_text(children), r"\*[unknown-label]");
    assert!(document.diagnostics.iter().any(|diagnostic| {
        diagnostic.level == DiagnosticLevel::Unsupported
            && diagnostic.code.as_deref() == Some("manual.unexpanded-table-cell")
    }));
}