markdown-syntax 0.8.0

no_std + alloc Markdown syntax parser and serializer
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
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
//! AST validation: [`Document::validate`] walks the tree and reports each
//! invalid or unsupported node shape as a [`Diagnostic`]. Serialization and HTML
//! rendering run this first and refuse an invalid document.

use alloc::vec::Vec;

use crate::{
    ast::{
        Alert, Block, CodeBlock, CodeBlockKind, CodeInline, ContainerDirective, Definition,
        DirectiveAttribute, Document, Escape, Frontmatter, Heading, HtmlContainer,
        HtmlContainerContent, Inline, LeafDirective, LineBreakKind, LinkDestinationKind, List,
        ListItem, MathInline, MathInlineKind, NodePath, ReferenceKind, Table, TextDirective,
    },
    diagnostic::Diagnostic,
    parse::{
        alert_title, frontmatter_fence_kind, html_block_ends_at_blank_line, html_block_left_open,
        html_block_opens, interrupts_paragraph, is_blank, is_footnote_label, is_reference_label,
        is_written_footnote_label, normalize_label, reads_as_inline_math, MAX_BLOCK_NESTING,
    },
    serialize::{
        item_misreads_after_marker, write_inline_math, written_marker, written_opens_fence_like,
    },
    span::Span,
};

impl Document {
    /// Validate this document's AST shape, returning a diagnostic for each
    /// invalid or unsupported node (empty when the document is well-formed).
    pub fn validate(&self) -> Vec<Diagnostic> {
        validate_document(self)
    }
}

pub(crate) fn validate_document(document: &Document) -> Vec<Diagnostic> {
    let mut report = Report::default();
    validate_blocks(&document.children, 0, false, &mut report);
    report.diagnostics
}

/// The diagnostics found so far, and the path of the node being checked,
/// which each diagnostic pushed carries.
#[derive(Default)]
struct Report {
    diagnostics: Vec<Diagnostic>,
    path: Vec<usize>,
}

impl Report {
    fn push(&mut self, mut diagnostic: Diagnostic) {
        diagnostic.path = Some(NodePath(self.path.clone()));
        self.diagnostics.push(diagnostic);
    }

    /// Runs `check` with the path at the child `index` of the current node.
    fn at(&mut self, index: usize, check: impl FnOnce(&mut Self)) {
        self.path.push(index);
        check(self);
        self.path.pop();
    }
}

/// A sequence of sibling blocks: each block, and two adjacent lists that one
/// marker would write as one list. `depth` counts the containers around the
/// blocks as the parser's nesting limit counts them: block quotes and alerts,
/// list items, footnote definitions, HTML containers, and container
/// directives.
fn validate_blocks(blocks: &[Block], depth: usize, tight: bool, diagnostics: &mut Report) {
    // Blank lines beyond the separator change how no block reads, so the
    // block before each one is the last one before them.
    let mut before: Option<&Block> = None;
    for (index, block) in blocks.iter().enumerate() {
        diagnostics.at(index, |diagnostics| {
            if let (Some(Block::List(before)), Block::List(list)) = (before, block) {
                if written_marker(before) == written_marker(list) {
                    diagnostics.push(Diagnostic::invalid(
                        list.meta.span,
                        "adjacent lists cannot use the same marker",
                    ));
                }
            }
            if let Some(before) = before {
                validate_taken_block(before, block, tight, diagnostics);
            }
            if let Block::Definition(definition) = block {
                // A line indented four columns or more continues a paragraph,
                // and starts one on the line after an alert's marker, which may
                // open containers first; neither starts a footnote definition.
                let indented = match before {
                    Some(before) => matches!(before, Block::Definition(_)),
                    None => depth > 0,
                };
                validate_definition(definition, depth, indented, diagnostics);
            }
            validate_block(block, depth, diagnostics);
        });
        if !matches!(block, Block::BlankLine(_)) {
            before = Some(block);
        }
    }
}

fn validate_block(block: &Block, depth: usize, diagnostics: &mut Report) {
    match block {
        Block::Paragraph(paragraph) => {
            // An empty paragraph writes nothing and reads back as no block.
            if paragraph.children.iter().all(is_empty_text) {
                diagnostics.push(Diagnostic::invalid(
                    paragraph.meta.span,
                    "paragraph cannot be empty",
                ));
            }
            validate_inlines(&paragraph.children, diagnostics);
        }
        Block::Heading(heading) => validate_heading(heading, diagnostics),
        Block::BlockQuote(block_quote) => {
            validate_blocks(&block_quote.children, depth + 1, false, diagnostics);
        }
        Block::Alert(alert) => validate_alert(alert, depth, diagnostics),
        Block::List(list) => validate_list(list, depth, diagnostics),
        Block::Table(table) => validate_table(table, diagnostics),
        Block::FootnoteDefinition(definition) => {
            if definition.identifier.is_empty() {
                diagnostics.push(Diagnostic::invalid(
                    definition.meta.span,
                    "footnote definition identifier cannot be empty",
                ));
            }
            validate_footnote_label(
                definition.meta.span,
                &definition.label,
                &definition.identifier,
                diagnostics,
            );
            // Its first line holds its label, and a blank line after its last
            // block belongs to the container around it.
            let last = definition.children.len().saturating_sub(1);
            if let Some((at, Block::BlankLine(blank))) = [0, last]
                .into_iter()
                .filter_map(|at| definition.children.get(at).map(|block| (at, block)))
                .find(|(_, block)| matches!(block, Block::BlankLine(_)))
            {
                diagnostics.at(at, |diagnostics| {
                    diagnostics.push(Diagnostic::invalid(
                        blank.meta.span,
                        "a footnote definition cannot open or end with a blank line",
                    ))
                });
            }
            validate_blocks(&definition.children, depth + 1, false, diagnostics);
        }
        // Checked with its siblings in `validate_blocks`.
        Block::Definition(_) => {}
        Block::LeafDirective(directive) => validate_leaf_directive(directive, diagnostics),
        Block::ContainerDirective(directive) => {
            validate_container_directive(directive, depth, diagnostics)
        }
        Block::HtmlContainer(container) => validate_html_container(container, depth, diagnostics),
        Block::CodeBlock(code) => validate_code_block(code, diagnostics),
        Block::Frontmatter(frontmatter) => validate_frontmatter(frontmatter, depth, diagnostics),
        Block::ThematicBreak(_)
        | Block::HtmlBlock(_)
        | Block::MathBlock(_)
        | Block::BlankLine(_) => {}
    }
}

fn validate_html_container(container: &HtmlContainer, depth: usize, diagnostics: &mut Report) {
    if container.opening.name.is_empty() {
        diagnostics.push(Diagnostic::invalid(
            container.opening.meta.span,
            "HTML container opening tag name cannot be empty",
        ));
    }
    if container.closing.name.is_empty() {
        diagnostics.push(Diagnostic::invalid(
            container.closing.meta.span,
            "HTML container closing tag name cannot be empty",
        ));
    }
    if container.opening.name != container.closing.name {
        diagnostics.push(Diagnostic::invalid(
            container.meta.span,
            "HTML container opening and closing tag names must match",
        ));
    }
    if container.opening.raw.is_empty() {
        diagnostics.push(Diagnostic::invalid(
            container.opening.meta.span,
            "HTML container opening tag source cannot be empty",
        ));
    }
    if container.closing.raw.is_empty() {
        diagnostics.push(Diagnostic::invalid(
            container.closing.meta.span,
            "HTML container closing tag source cannot be empty",
        ));
    }

    match &container.content {
        HtmlContainerContent::Blocks(children) => {
            validate_blocks(children, depth + 1, false, diagnostics);
        }
        HtmlContainerContent::Inlines(children) => validate_inlines(children, diagnostics),
    }
}

fn validate_heading(heading: &Heading, diagnostics: &mut Report) {
    if heading.depth == 0 || heading.depth > 6 {
        diagnostics.push(Diagnostic::invalid(
            heading.meta.span,
            "heading depth must be in the range 1..=6",
        ));
    }
    validate_inlines(&heading.children, diagnostics);
}

/// An alert's title is what the parser reads from its marker line: never
/// empty, and without spaces or tabs around it.
fn validate_alert(alert: &Alert, depth: usize, diagnostics: &mut Report) {
    if let Some(title) = &alert.title {
        if alert_title(title).as_deref() != Some(title.as_str()) {
            diagnostics.push(Diagnostic::invalid(
                alert.meta.span,
                "alert title cannot be empty or start or end with a space or a tab",
            ));
        }
    }
    validate_blocks(&alert.children, depth + 1, false, diagnostics);
}

fn validate_list(list: &List, depth: usize, diagnostics: &mut Report) {
    if list.children.is_empty() {
        diagnostics.push(Diagnostic::invalid(
            list.meta.span,
            "list must hold at least one item",
        ));
    }
    // A list is loose when blank lines part its items or two blocks of one
    // item, so one item of at most one block is always tight.
    if !list.tight
        && matches!(list.children.as_slice(), [item] if item
            .children
            .iter()
            .filter(|block| !matches!(block, Block::BlankLine(_)))
            .count()
            <= 1)
    {
        diagnostics.push(Diagnostic::invalid(
            list.meta.span,
            "a loose list must hold two items or an item of two blocks",
        ));
    }
    for (index, item) in list.children.iter().enumerate() {
        diagnostics.at(index, |diagnostics| {
            validate_item_number(list, item, diagnostics);
            validate_item_first_line(list, item, diagnostics);
            validate_item_blank_lines(list, index, item, diagnostics);
            validate_task_item(item, diagnostics);
            validate_blocks(&item.children, depth + 1, list.tight, diagnostics);
        });
    }
}

/// A task item's checkbox opens its first paragraph after the definitions it
/// starts with; without one, `[ ]` or `[x]` reads as text.
fn validate_task_item(item: &ListItem, diagnostics: &mut Report) {
    if item.checked.is_none() {
        return;
    }
    let first = item
        .children
        .iter()
        .find(|block| !matches!(block, Block::Definition(_)));
    if !matches!(first, Some(Block::Paragraph(paragraph)) if !paragraph.children.is_empty()) {
        diagnostics.push(Diagnostic::invalid(
            item.meta.span,
            "task list item must hold a non-empty paragraph after its leading definitions",
        ));
    }
}

/// Refuses `right` where `left`, the block before it, takes its first line:
/// an HTML block its value leaves open takes every line to its container's
/// end, an indented code block is written four columns in, which some blocks take
/// across a blank line (see [`takes_indented_code`]), and a tight item writes
/// each block on the line after the one before (see [`takes_next_line`]).
fn validate_taken_block(left: &Block, right: &Block, tight: bool, diagnostics: &mut Report) {
    let message = if matches!(left, Block::HtmlBlock(node) if html_block_left_open(node)) {
        "a block must not follow an HTML block that its value leaves open"
    } else if matches!(right, Block::CodeBlock(code) if code.kind == CodeBlockKind::Indented)
        && takes_indented_code(left)
    {
        "an indented code block must not be read as part of the block before it"
    } else if tight && matches!(left, Block::Paragraph(_)) && takes_next_line(left, right) {
        "in a tight list item, a block after a paragraph must be able to interrupt it"
    } else if tight && takes_next_line(left, right) {
        "in a tight list item, a block must not be read as part of the block before it"
    } else {
        return;
    };
    diagnostics.push(Diagnostic::invalid(right.span(), message));
}

/// Whether `left` takes the lines of an indented code block written after
/// it, on the next line or after blank lines: an indented code block's, which
/// they continue, and a footnote definition's, whose content is indented four
/// columns. A list's last item takes them only where its content starts at
/// most four columns in, which the source's marker sets, so a parsed list
/// before indented code is written as it reads only from the source.
fn takes_indented_code(left: &Block) -> bool {
    match left {
        Block::CodeBlock(code) => code.kind == CodeBlockKind::Indented,
        Block::FootnoteDefinition(_) => true,
        _ => false,
    }
}

/// Whether `left`, written on the line before `right` in the same
/// container, takes `right`'s first line, by the parser's own checks: a
/// paragraph takes a line that does not interrupt it; a table, and a
/// container whose last line, through its last block and last item, is a
/// paragraph's (which takes it lazily), take a line that starts no block
/// where no paragraph is the line's container; an HTML block that a blank
/// line ends takes every line; and a quote's `>` lines continue a quote
/// before it. Every other block ends where its own syntax or line does.
fn takes_next_line(left: &Block, right: &Block) -> bool {
    match left {
        Block::Paragraph(_) => !interrupts_paragraph(right),
        // A definition's lines are a paragraph's until it is read, so a
        // line that cannot interrupt one continues them; only a paragraph
        // and a definition read the same after it.
        Block::Definition(_) => {
            !interrupts_paragraph(right)
                && !matches!(right, Block::Paragraph(_) | Block::Definition(_))
        }
        Block::Table(_) => !starts_outside_paragraph(right, false),
        Block::HtmlBlock(node) => html_block_ends_at_blank_line(node),
        Block::BlockQuote(_) | Block::Alert(_)
            if matches!(right, Block::BlockQuote(_) | Block::Alert(_)) =>
        {
            true
        }
        _ => match ends_in_open_paragraph(left) {
            // A line opening like a fence ends a quote's paragraph instead of
            // continuing it.
            Some(through_quote) => {
                !starts_outside_paragraph(right, true)
                    && !(through_quote && written_opens_fence_like(right))
            }
            None => false,
        },
    }
}

/// Whether `block`'s first line, written where the line's container is not
/// a paragraph, starts a block: a paragraph's, a definition's, and a
/// table's first line are text, and an HTML block's starts
/// one only where it opens one. With `lazy`, a paragraph (or an alert's
/// marker line) is still the last open block, where no indented code
/// starts.
fn starts_outside_paragraph(block: &Block, lazy: bool) -> bool {
    match block {
        Block::Paragraph(_) | Block::Definition(_) | Block::Table(_) => false,
        Block::HtmlBlock(node) => html_block_opens(node),
        Block::CodeBlock(code) => !(lazy && code.kind == CodeBlockKind::Indented),
        _ => true,
    }
}

/// Whether `block` is a container whose last line, through the last block
/// of each container and the last item of each list, is a paragraph's or a
/// definition's, or is the marker line of an alert holding no blocks: a
/// line after it that starts no block continues that paragraph lazily. When
/// it is, whether a block quote or an alert is passed on the way. Only last
/// children are visited, which no other pair of a container starts from, so
/// the walks over a tree stay linear.
fn ends_in_open_paragraph(block: &Block) -> Option<bool> {
    let mut block = block;
    let mut nested = false;
    let mut through_quote = false;
    loop {
        let children = match block {
            Block::Paragraph(_) | Block::Definition(_) => return nested.then_some(through_quote),
            Block::Alert(alert) if alert.children.is_empty() => return Some(true),
            Block::BlockQuote(quote) => &quote.children,
            Block::Alert(alert) => &alert.children,
            Block::FootnoteDefinition(footnote) => &footnote.children,
            Block::List(list) => &list.children.last()?.children,
            _ => return None,
        };
        through_quote |= matches!(block, Block::BlockQuote(_) | Block::Alert(_));
        block = children.last()?;
        nested = true;
    }
}

fn validate_table(table: &Table, diagnostics: &mut Report) {
    if table.rows.is_empty() {
        diagnostics.push(Diagnostic::invalid(
            table.meta.span,
            "table must contain at least a header row",
        ));
        return;
    }

    let width = table.rows[0].cells.len();
    if width == 0 {
        diagnostics.push(Diagnostic::invalid(
            table.meta.span,
            "table header row must contain at least one cell",
        ));
    }

    if table.alignments.len() != width {
        diagnostics.push(Diagnostic::invalid(
            table.meta.span,
            "table alignment count must match header width",
        ));
    }

    for (index, row) in table.rows.iter().enumerate() {
        diagnostics.at(index, |diagnostics| {
            if row.cells.len() != width {
                diagnostics.push(Diagnostic::invalid(
                    row.meta.span,
                    "table row width must match header width",
                ));
            }
            for (index, cell) in row.cells.iter().enumerate() {
                diagnostics.at(index, |diagnostics| {
                    validate_inlines(&cell.children, diagnostics);
                    validate_cell_values(&cell.children, diagnostics);
                    validate_one_line(
                        &cell.children,
                        "a table cell cannot hold a line break",
                        diagnostics,
                    );
                });
            }
        });
    }
}

/// The values a table cell writes as they are. The row splits at each `|`
/// after no backslash or an even run of them, and the cell's inline input
/// reads an odd run before a `|` with one backslash less, so no cell source
/// gives a value that holds a `|` after an odd backslash run.
fn validate_cell_values(inlines: &[Inline], diagnostics: &mut Report) {
    for inline in inlines {
        let unwritable = match inline {
            Inline::Code(node) => has_odd_escaped_pipe(&node.value),
            Inline::Math(node) => has_odd_escaped_pipe(&node.value),
            Inline::Html(node) => has_odd_escaped_pipe(&node.value),
            Inline::Autolink(node) => has_odd_escaped_pipe(&node.text),
            Inline::LinkReference(node) => has_odd_escaped_pipe(&node.label),
            Inline::ImageReference(node) => has_odd_escaped_pipe(&node.label),
            Inline::FootnoteReference(node) => has_odd_escaped_pipe(&node.label),
            Inline::WikiLink(node) => {
                has_odd_escaped_pipe(&node.target) || has_odd_escaped_pipe(&node.label)
            }
            _ => false,
        };
        if unwritable {
            diagnostics.push(Diagnostic::invalid(
                inline.span(),
                "a value in a table cell cannot hold a `|` after an odd run of backslashes",
            ));
        }
        validate_cell_values(inline.children(), diagnostics);
    }
}

/// Whether `value` holds a `|` right after an odd run of backslashes.
fn has_odd_escaped_pipe(value: &str) -> bool {
    let mut backslashes = 0usize;
    for byte in value.bytes() {
        if byte == b'|' && backslashes % 2 == 1 {
            return true;
        }
        backslashes = if byte == b'\\' { backslashes + 1 } else { 0 };
    }
    false
}

/// Inline content written on one line, at any depth: a table cell, or a leaf
/// or container directive's label on its opening line.
fn validate_one_line(inlines: &[Inline], message: &'static str, diagnostics: &mut Report) {
    for inline in inlines {
        if matches!(inline, Inline::SoftBreak(_) | Inline::LineBreak(_)) {
            diagnostics.push(Diagnostic::invalid(inline.span(), message));
        }
        validate_one_line(inline.children(), message, diagnostics);
    }
}

fn validate_leaf_directive(directive: &LeafDirective, diagnostics: &mut Report) {
    validate_directive_name(directive.meta.span, &directive.name, diagnostics);
    validate_directive_attributes(&directive.attributes, diagnostics);
    validate_inlines(&directive.label, diagnostics);
    validate_one_line(
        &directive.label,
        "a leaf directive label cannot hold a line break",
        diagnostics,
    );
}

fn validate_container_directive(
    directive: &ContainerDirective,
    depth: usize,
    diagnostics: &mut Report,
) {
    validate_directive_name(directive.meta.span, &directive.name, diagnostics);
    validate_directive_attributes(&directive.attributes, diagnostics);
    validate_inlines(&directive.label, diagnostics);
    validate_one_line(
        &directive.label,
        "a container directive label cannot hold a line break",
        diagnostics,
    );
    validate_blocks(&directive.children, depth + 1, false, diagnostics);
}

/// A definition's label is written as a reference label, and its identifier
/// is the parser's normalization of it. A label that is `^` and a footnote
/// label opens a footnote definition instead, unless the definition is past
/// the parser's nesting limit or may come from a line `indented` into a
/// paragraph, which starts no block.
fn validate_definition(
    definition: &Definition,
    depth: usize,
    indented: bool,
    diagnostics: &mut Report,
) {
    if definition
        .identifier
        .trim_matches([' ', '\t', '\n', '\r'])
        .is_empty()
    {
        diagnostics.push(Diagnostic::invalid(
            definition.meta.span,
            "definition identifier cannot be empty",
        ));
    }
    validate_reference_label(
        definition.meta.span,
        &definition.label,
        &definition.identifier,
        true,
        diagnostics,
    );
    let footnote = definition
        .label
        .strip_prefix('^')
        .is_some_and(is_footnote_label);
    if footnote && depth < MAX_BLOCK_NESTING && !indented {
        diagnostics.push(Diagnostic::invalid(
            definition.meta.span,
            "definition label cannot be `^` followed by a footnote label",
        ));
    }
    validate_destination(
        definition.meta.span,
        &definition.destination,
        definition.destination_kind,
        diagnostics,
    );
}

/// A reference's identifier is the parser's normalization of its label, and
/// a label that is `written` (a definition's, or a full reference's) reads
/// back as a reference label.
fn validate_reference_label(
    span: Option<Span>,
    label: &str,
    identifier: &str,
    written: bool,
    diagnostics: &mut Report,
) {
    if normalize_label(label) != identifier {
        diagnostics.push(Diagnostic::invalid(
            span,
            "reference identifier must be the normalized label",
        ));
    }
    if written && !is_reference_label(label) {
        diagnostics.push(Diagnostic::invalid(
            span,
            "reference label must be one the parser reads as a label",
        ));
    }
}

/// A footnote's label reads back as a footnote label, and its identifier is
/// the parser's normalization of it.
fn validate_footnote_label(
    span: Option<Span>,
    label: &str,
    identifier: &str,
    diagnostics: &mut Report,
) {
    if normalize_label(label) != identifier {
        diagnostics.push(Diagnostic::invalid(
            span,
            "footnote identifier must be the normalized label",
        ));
    }
    if !is_written_footnote_label(label) {
        diagnostics.push(Diagnostic::invalid(
            span,
            "footnote label must be one the parser reads as a footnote label",
        ));
    }
}

/// An empty bare destination is written `<>`, which reads as an
/// angle-bracket one.
fn validate_destination(
    span: Option<Span>,
    destination: &str,
    kind: LinkDestinationKind,
    diagnostics: &mut Report,
) {
    if kind == LinkDestinationKind::Bare && destination.is_empty() {
        diagnostics.push(Diagnostic::invalid(
            span,
            "a bare destination cannot be empty",
        ));
    }
}

/// A code block's info string is never empty, and an indented code block's
/// value, which no fence bounds, starts and ends with a line that is not
/// blank.
fn validate_code_block(code: &CodeBlock, diagnostics: &mut Report) {
    if code.info.as_deref() == Some("") {
        diagnostics.push(Diagnostic::invalid(
            code.meta.span,
            "code block info string cannot be empty",
        ));
    }
    if code.kind == CodeBlockKind::Indented {
        // Each line of the value ends with a line ending, the last one
        // optionally.
        let value = code.value.replace("\r\n", "\n");
        let body = value.strip_suffix(['\n', '\r']).unwrap_or(&value);
        let mut lines = body.split(['\n', '\r']);
        let first = lines.next().unwrap_or_default();
        let last = lines.next_back().unwrap_or(first);
        if is_blank(first) || is_blank(last) {
            diagnostics.push(Diagnostic::invalid(
                code.meta.span,
                "indented code cannot be empty or start or end with a blank line",
            ));
        }
    }
}

/// Frontmatter opens only the document, and ends at the first line that is
/// its fence.
fn validate_frontmatter(frontmatter: &Frontmatter, depth: usize, diagnostics: &mut Report) {
    if depth > 0 {
        diagnostics.push(Diagnostic::invalid(
            frontmatter.meta.span,
            "frontmatter cannot be inside a container",
        ));
    }
    if frontmatter
        .value
        .replace("\r\n", "\n")
        .split(['\n', '\r'])
        .any(|line| frontmatter_fence_kind(line) == Some(frontmatter.kind))
    {
        diagnostics.push(Diagnostic::invalid(
            frontmatter.meta.span,
            "frontmatter value cannot hold its own fence line",
        ));
    }
}

/// Inline content whose container ends where its line does, or with a closing
/// delimiter that a line break before it keeps from closing: a final hard line
/// break would not survive serialization.
fn validate_inlines(inlines: &[Inline], diagnostics: &mut Report) {
    if let Some(Inline::LineBreak(node)) = inlines.last() {
        diagnostics.push(Diagnostic::invalid(
            node.meta.span,
            "hard line break cannot be the final inline of its container",
        ));
    }
    validate_inline_nodes(inlines, diagnostics);
}

/// Inline content closed by a `]`, which closes after a line break as well, so
/// it may end with a hard line break.
fn validate_inline_nodes(inlines: &[Inline], diagnostics: &mut Report) {
    for (index, inline) in inlines.iter().enumerate() {
        if let Some(before) = index.checked_sub(1).map(|before| &inlines[before]) {
            validate_siblings(before, inline, diagnostics);
        }
        match inline {
            Inline::Text(node) => {
                if node.value.contains(['\n', '\r']) {
                    diagnostics.push(Diagnostic::invalid(
                        node.meta.span,
                        "text cannot hold a line ending; a line ends with a soft or hard break",
                    ));
                }
            }
            Inline::Emphasis(_) | Inline::Strong(_) | Inline::Delete(_) | Inline::Mark(_) => {
                validate_emphasis_container(inline, diagnostics)
            }
            Inline::Shortcode(node) => {
                if node.glyph().is_none() {
                    diagnostics.push(Diagnostic::invalid(
                        node.meta.span,
                        "shortcode name must be a gemoji name",
                    ));
                }
            }
            Inline::Tag(node) => {
                if !crate::unicode_letters::is_tag_name(&node.name) {
                    diagnostics.push(Diagnostic::invalid(
                        node.meta.span,
                        "tag name must be a Unicode letter followed by letters, numbers, `/`, `_`, or `-`",
                    ));
                }
            }
            Inline::Link(node) => {
                validate_destination(
                    node.meta.span,
                    &node.destination,
                    node.destination_kind,
                    diagnostics,
                );
                validate_link_text(&node.children, diagnostics);
                validate_inline_nodes(&node.children, diagnostics);
            }
            Inline::Autolink(node) => {
                if node.destination().is_none() {
                    diagnostics.push(Diagnostic::invalid(
                        node.meta.span,
                        "autolink text must be exactly one autolink of its form",
                    ));
                }
            }
            Inline::Image(node) => {
                validate_destination(
                    node.meta.span,
                    &node.destination,
                    node.destination_kind,
                    diagnostics,
                );
                validate_inline_nodes(&node.alt, diagnostics);
            }
            Inline::LinkReference(node) => {
                if node.identifier.is_empty() {
                    diagnostics.push(Diagnostic::invalid(
                        node.meta.span,
                        "link reference identifier cannot be empty",
                    ));
                }
                validate_reference_label(
                    node.meta.span,
                    &node.label,
                    &node.identifier,
                    node.kind == ReferenceKind::Full,
                    diagnostics,
                );
                validate_link_text(&node.children, diagnostics);
                validate_inline_nodes(&node.children, diagnostics);
            }
            Inline::ImageReference(node) => {
                if node.identifier.is_empty() {
                    diagnostics.push(Diagnostic::invalid(
                        node.meta.span,
                        "image reference identifier cannot be empty",
                    ));
                }
                validate_reference_label(
                    node.meta.span,
                    &node.label,
                    &node.identifier,
                    node.kind == ReferenceKind::Full,
                    diagnostics,
                );
                validate_inline_nodes(&node.alt, diagnostics);
            }
            Inline::Escape(node) => validate_escape(node, diagnostics),
            Inline::CharacterReference(node) => {
                if node.value().is_none() {
                    diagnostics.push(Diagnostic::invalid(
                        node.meta.span,
                        "character reference must be exactly one character reference",
                    ));
                }
            }
            Inline::TextDirective(node) => validate_text_directive(node, diagnostics),
            Inline::FootnoteReference(node) => {
                if node.identifier.is_empty() {
                    diagnostics.push(Diagnostic::invalid(
                        node.meta.span,
                        "footnote reference identifier cannot be empty",
                    ));
                }
                validate_footnote_label(node.meta.span, &node.label, &node.identifier, diagnostics);
            }
            Inline::InlineFootnote(node) => {
                if node.children.is_empty() {
                    diagnostics.push(Diagnostic::invalid(
                        node.meta.span,
                        "inline footnote cannot be empty",
                    ));
                }
                validate_inline_nodes(&node.children, diagnostics)
            }
            Inline::WikiLink(node) => {
                if node.target.is_empty() {
                    diagnostics.push(Diagnostic::invalid(
                        node.meta.span,
                        "wikilink target cannot be empty",
                    ));
                }
            }
            Inline::Code(node) => validate_code_inline(node, diagnostics),
            Inline::Math(node) => validate_math_inline(node, diagnostics),
            Inline::Html(_) | Inline::SoftBreak(_) | Inline::LineBreak(_) => {}
        }
    }
}

/// Two adjacent inlines whose written forms run together: a break after a
/// break leaves an empty line, which ends the paragraph, unless it is a
/// backslash break, which writes its `\` on that line; and two strikethroughs
/// join their delimiters into `~~~~`, which opens and closes none. Whether
/// two emphasis or two strong spans with one delimiter char read back depends
/// on the chars around their joined run (`**:* ~**a**` parses as two
/// emphasis spans), and two marks join into `====`, which reads as two marks
/// again; neither is rejected.
fn validate_siblings(before: &Inline, inline: &Inline, diagnostics: &mut Report) {
    let after_break = matches!(before, Inline::SoftBreak(_) | Inline::LineBreak(_));
    let blank_line = match inline {
        Inline::SoftBreak(_) => true,
        Inline::LineBreak(node) => node.kind == LineBreakKind::Spaces,
        _ => false,
    };
    if after_break && blank_line {
        diagnostics.push(Diagnostic::invalid(
            inline.span(),
            "a soft break or a spaces hard break cannot follow a line break",
        ));
    }
    if matches!((before, inline), (Inline::Delete(_), Inline::Delete(_))) {
        diagnostics.push(Diagnostic::invalid(
            inline.span(),
            "adjacent strikethroughs cannot be written",
        ));
    }
}

/// An emphasis-like container: it holds content without whitespace at its
/// edges, and no only child whose delimiter runs join its own into a run
/// that reads otherwise: `*` around `*a*` writes `**a**`, which is strong;
/// `**` around `*a*` writes `***a***`, emphasis around strong; `~~` around
/// `~~a~~` writes `~~~~a~~~~`, which strikes nothing; and `==` around `==a==`
/// writes `====a====`, one mark between two `==`. `**` around `**a**` reads
/// back as written.
fn validate_emphasis_container(node: &Inline, diagnostics: &mut Report) {
    let children = node.children();
    let span = node.span();
    if children.iter().all(is_empty_text) {
        diagnostics.push(Diagnostic::invalid(
            span,
            "emphasis-like inline container cannot have empty children",
        ));
    } else if starts_with_whitespace(children) || ends_with_whitespace(children) {
        diagnostics.push(Diagnostic::invalid(
            span,
            "emphasis-like inline content cannot start or end with whitespace",
        ));
    }
    let joined = match (node, children) {
        (Inline::Emphasis(outer), [Inline::Emphasis(inner)]) => outer.delimiter == inner.delimiter,
        (Inline::Strong(outer), [Inline::Emphasis(inner)]) => outer.delimiter == inner.delimiter,
        (Inline::Delete(_), [Inline::Delete(_)]) | (Inline::Mark(_), [Inline::Mark(_)]) => true,
        _ => false,
    };
    if joined {
        diagnostics.push(Diagnostic::invalid(
            span,
            "emphasis-like span cannot hold only a span written with the same delimiter",
        ));
    }
    validate_inlines(children, diagnostics);
}

/// Whether inline content, past any empty text, starts with whitespace, as
/// the parser's delimiter flanking reads it, or with a line break other than a
/// backslash break: a delimiter run before `\` is followed by punctuation,
/// which may open it as the characters before it allow.
fn starts_with_whitespace(inlines: &[Inline]) -> bool {
    match inlines.iter().find(|inline| !is_empty_text(inline)) {
        Some(Inline::Text(text)) => text.value.starts_with(char::is_whitespace),
        Some(Inline::SoftBreak(_)) => true,
        Some(Inline::LineBreak(node)) => node.kind == LineBreakKind::Spaces,
        _ => false,
    }
}

/// Whether inline content, before any empty text, ends with whitespace or a
/// line break.
fn ends_with_whitespace(inlines: &[Inline]) -> bool {
    match inlines.iter().rev().find(|inline| !is_empty_text(inline)) {
        Some(Inline::Text(text)) => text.value.ends_with(char::is_whitespace),
        Some(Inline::SoftBreak(_) | Inline::LineBreak(_)) => true,
        _ => false,
    }
}

fn is_empty_text(inline: &Inline) -> bool {
    matches!(inline, Inline::Text(text) if text.value.is_empty())
}

/// Link text holds no link, at any depth.
fn validate_link_text(inlines: &[Inline], diagnostics: &mut Report) {
    for inline in inlines {
        match inline {
            Inline::Link(_)
            | Inline::Autolink(_)
            | Inline::LinkReference(_)
            | Inline::WikiLink(_) => {
                diagnostics.push(Diagnostic::invalid(
                    inline.span(),
                    "link text cannot hold a link",
                ));
            }
            _ => validate_link_text(inline.children(), diagnostics),
        }
    }
}

fn validate_escape(escape: &Escape, diagnostics: &mut Report) {
    if !escape.value.is_ascii_punctuation() {
        diagnostics.push(Diagnostic::invalid(
            escape.meta.span,
            "escaped value must be an ASCII punctuation character",
        ));
    }
}

/// A code span's value is what the parser reads from one: never empty, and
/// with its line endings read as spaces.
fn validate_code_inline(code: &CodeInline, diagnostics: &mut Report) {
    if code.value.is_empty() {
        diagnostics.push(Diagnostic::invalid(
            code.meta.span,
            "inline code value cannot be empty",
        ));
    }
    if code.value.contains(['\n', '\r']) {
        diagnostics.push(Diagnostic::invalid(
            code.meta.span,
            "inline code value cannot hold a line ending",
        ));
    }
}

/// Inline math that its fence closes around: math needs a value (both `$$`
/// and `` $`` `$ `` read back as other text), and code-form math ends at the
/// first `` `$ ``, so its value cannot hold one.
fn validate_math_inline(math: &MathInline, diagnostics: &mut Report) {
    if math.value.is_empty() {
        diagnostics.push(Diagnostic::invalid(
            math.meta.span,
            "inline math value cannot be empty",
        ));
    }
    match math.kind {
        MathInlineKind::Dollar { dollars: 0 } => diagnostics.push(Diagnostic::invalid(
            math.meta.span,
            "dollar-fenced inline math must have a fence length of at least 1",
        )),
        MathInlineKind::Code if math.value.contains("`$") => diagnostics.push(Diagnostic::invalid(
            math.meta.span,
            "code-form inline math value cannot contain a backtick followed by `$`",
        )),
        // The parser's own scan tells whether the fence closes where it is
        // written: not before a `$` inside, nor around edge whitespace or a
        // line ending the single-`$` form reads as a space.
        MathInlineKind::Dollar { .. }
            if !math.value.is_empty()
                && !reads_as_inline_math(&write_inline_math(math), &math.value, math.kind) =>
        {
            diagnostics.push(Diagnostic::invalid(
                math.meta.span,
                "dollar-fenced inline math must read back as written",
            ));
        }
        _ => {}
    }
}

fn validate_item_number(list: &List, item: &ListItem, diagnostics: &mut Report) {
    let Some(number) = item.number else {
        return;
    };
    if !list.ordered {
        diagnostics.push(Diagnostic::invalid(
            item.meta.span,
            "a bullet list item cannot hold a number",
        ));
    } else if number > crate::parse::MAX_ORDERED_NUMBER {
        diagnostics.push(Diagnostic::invalid(
            item.meta.span,
            "ordered list item number must be representable in at most 9 digits",
        ));
    }
}

/// An item's content is written on its marker's line, after one space, so
/// it cannot open with what reads as more space after the marker, or, after
/// a `-` or `*` bullet, read as one thematic break with it.
fn validate_item_first_line(list: &List, item: &ListItem, diagnostics: &mut Report) {
    if item_misreads_after_marker(list, item) {
        diagnostics.push(Diagnostic::invalid(
            item.meta.span,
            "a list item's first line must not read as padding after its marker or as a thematic break with it",
        ));
    }
}

/// A blank line in a list item is written below the item's first line and
/// above a later item, so it cannot open an item, end the last item, or sit
/// in a tight list.
fn validate_item_blank_lines(list: &List, index: usize, item: &ListItem, diagnostics: &mut Report) {
    let last_item = index + 1 == list.children.len();
    for (at, block) in item.children.iter().enumerate() {
        let Block::BlankLine(blank) = block else {
            continue;
        };
        let message = if list.tight {
            "a tight list cannot hold a blank line"
        } else if at == 0 {
            "a list item cannot open with a blank line"
        } else if last_item && at + 1 == item.children.len() {
            "the last item of a list cannot end with a blank line"
        } else {
            continue;
        };
        diagnostics.at(at, |diagnostics| {
            diagnostics.push(Diagnostic::invalid(blank.meta.span, message))
        });
    }
}

fn validate_text_directive(directive: &TextDirective, diagnostics: &mut Report) {
    validate_directive_name(directive.meta.span, &directive.name, diagnostics);
    validate_directive_attributes(&directive.attributes, diagnostics);
    validate_inline_nodes(&directive.label, diagnostics);
}

fn validate_directive_name(span: Option<Span>, name: &str, diagnostics: &mut Report) {
    if !is_directive_name(name) {
        diagnostics.push(Diagnostic::invalid(
            span,
            "directive name must be runs of ASCII letters joined by single `-`",
        ));
    }
}

fn validate_directive_attributes(attributes: &[DirectiveAttribute], diagnostics: &mut Report) {
    for attribute in attributes {
        if !is_attribute_name(&attribute.name) {
            diagnostics.push(Diagnostic::invalid(
                None,
                "directive attribute name must start with a letter, `_`, or `-`",
            ));
        }
    }
}

/// Whether `name` is one or more runs of ASCII letters joined by single `-`.
pub(crate) fn is_directive_name(name: &str) -> bool {
    name.split('-')
        .all(|run| !run.is_empty() && run.bytes().all(|byte| byte.is_ascii_alphabetic()))
}

pub(crate) fn is_attribute_name(name: &str) -> bool {
    let mut chars = name.chars();
    let Some(first) = chars.next() else {
        return false;
    };
    if !(first.is_ascii_alphabetic() || first == '_' || first == '-') {
        return false;
    }
    chars.all(|char| char.is_ascii_alphanumeric() || char == '_' || char == '-' || char == ':')
}