markdown-syntax 0.1.2

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
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
//! The owned Markdown AST that [`parse()`](crate::parse()) produces and
//! `Document::to_markdown`/`to_html` consume. Every node carries a [`NodeMeta`]
//! with an optional source [`Span`]. [`Block`] and [`Inline`] are the two node
//! enums; everything else is a concrete node struct or a small enum describing
//! a node's variant.

use alloc::{string::String, vec::Vec};

use crate::span::Span;

/// Metadata attached to every AST node; currently just the source span.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct NodeMeta {
    /// The node's source location, or `None` for hand-built nodes.
    pub span: Option<Span>,
}

impl NodeMeta {
    /// Wrap an optional [`Span`] into a [`NodeMeta`].
    pub const fn new(span: Option<Span>) -> Self {
        Self { span }
    }
}

/// The root of a parsed document: a sequence of top-level [`Block`]s.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Document {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// The document's top-level blocks, in source order.
    pub children: Vec<Block>,
}

/// A block-level node: the building blocks of a document's vertical structure.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Block {
    /// A paragraph of inline content.
    Paragraph(Paragraph),
    /// An ATX (`# h`) or setext (underlined) heading.
    Heading(Heading),
    /// A thematic break / horizontal rule: `---`, `***`, or `___`.
    ThematicBreak(ThematicBreak),
    /// A block quote: lines prefixed with `> `.
    BlockQuote(BlockQuote),
    /// A GFM alert / admonition: `> [!NOTE]` etc.
    Alert(Alert),
    /// A bullet or ordered list.
    List(List),
    /// A description / definition list (term + details).
    DescriptionList(DescriptionList),
    /// A fenced (```` ``` ````) or indented code block.
    CodeBlock(CodeBlock),
    /// A raw HTML block.
    HtmlBlock(HtmlBlock),
    /// A link reference definition: `[label]: url "title"`.
    Definition(Definition),
    /// A footnote definition: `[^id]: text`.
    FootnoteDefinition(FootnoteDefinition),
    /// A GFM pipe table.
    Table(Table),
    /// A display math block: `$$ … $$`.
    MathBlock(MathBlock),
    /// A leading frontmatter block (`---` YAML or `+++` TOML).
    Frontmatter(Frontmatter),
    /// An MDX ESM block (`import`/`export` statements).
    MdxEsm(MdxEsm),
    /// A block-level MDX expression: `{ … }`.
    MdxExpression(MdxExpression),
    /// A block-level MDX JSX element.
    MdxJsx(MdxJsx),
    /// A leaf directive: `::name[label]{attrs}` (distinct from MDX).
    LeafDirective(LeafDirective),
    /// A container directive: `:::name … :::` (distinct from MDX).
    ContainerDirective(ContainerDirective),
}

/// A paragraph: a run of inline content. Source: any plain text line(s).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Paragraph {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// The paragraph's inline content.
    pub children: Vec<Inline>,
}

/// A heading. Source: `# Title` (ATX) or `Title\n===` (setext).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Heading {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// Heading level, 1..=6.
    pub depth: u8,
    /// Whether the heading used ATX or setext syntax.
    pub kind: HeadingKind,
    /// The heading's inline content.
    pub children: Vec<Inline>,
}

/// Which heading syntax produced a [`Heading`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum HeadingKind {
    /// ATX heading: `# Title` … `###### Title`.
    Atx,
    /// Setext heading: `Title` underlined with `===` (level 1) or `---` (level 2).
    Setext,
}

/// A thematic break / horizontal rule. Source: `---`, `***`, or `___`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ThematicBreak {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// Which character formed the break.
    pub marker: ThematicBreakMarker,
}

/// The character used to draw a [`ThematicBreak`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ThematicBreakMarker {
    /// Dashes: `---`.
    Dash,
    /// Asterisks: `***`.
    Asterisk,
    /// Underscores: `___`.
    Underscore,
}

/// A block quote: content prefixed with `> `.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BlockQuote {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// The quoted block content.
    pub children: Vec<Block>,
}

/// A GFM alert / admonition. Source: `> [!NOTE]` followed by quoted content.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Alert {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// The alert severity / type.
    pub kind: AlertKind,
    /// An optional custom title following the `[!KIND]` marker.
    pub title: Option<String>,
    /// The alert's block content.
    pub children: Vec<Block>,
}

/// The kind of a GFM [`Alert`] (the `[!KIND]` marker).
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AlertKind {
    /// `> [!NOTE]`.
    Note,
    /// `> [!TIP]`.
    Tip,
    /// `> [!IMPORTANT]`.
    Important,
    /// `> [!WARNING]`.
    Warning,
    /// `> [!CAUTION]`.
    Caution,
}

/// A bullet or ordered list. Source: `- a` / `1. a` lines.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct List {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// `true` for an ordered list, `false` for a bullet list.
    pub ordered: bool,
    /// The starting number of an ordered list (e.g. `3.` => `Some(3)`).
    pub start: Option<u64>,
    /// The marker delimiter used by the list items.
    pub delimiter: ListDelimiter,
    /// `true` if the list is tight (no blank lines between items / no `<p>`).
    pub tight: bool,
    /// The list's items.
    pub children: Vec<ListItem>,
}

/// The marker character that delimits a list's items.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ListDelimiter {
    /// Bullet `-`.
    Dash,
    /// Bullet `*`.
    Asterisk,
    /// Bullet `+`.
    Plus,
    /// Ordered `1.`.
    Period,
    /// Ordered `1)`.
    Paren,
}

/// A single list item, optionally a GFM task-list checkbox.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ListItem {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// Task-list state: `Some(true)` for `[x]`, `Some(false)` for `[ ]`, `None` otherwise.
    pub checked: Option<bool>,
    /// The item's block content.
    pub children: Vec<Block>,
}

/// A description / definition list of term + details pairs.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DescriptionList {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// `true` if the list is tight (no blank lines between items).
    pub tight: bool,
    /// The list's term/details items.
    pub children: Vec<DescriptionItem>,
}

/// One entry of a [`DescriptionList`]: a term and its detail blocks. Source: a
/// term line followed by `: details` lines.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DescriptionItem {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// The term's inline content.
    pub term: Vec<Inline>,
    /// The detail group(s) attached to this term.
    pub details: Vec<DescriptionDetails>,
}

/// The details (`: …`) attached to a [`DescriptionItem`]'s term.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DescriptionDetails {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// The details' block content.
    pub children: Vec<Block>,
}

/// A code block. Source: ```` ```lang … ``` ```` (fenced) or 4-space-indented lines.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CodeBlock {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// Whether the block is fenced (and with what fence) or indented.
    pub kind: CodeBlockKind,
    /// The info string after a fence (e.g. the `rust` in ```` ```rust ````).
    pub info: Option<String>,
    /// The literal code contents.
    pub value: String,
}

/// Whether a [`CodeBlock`] is fenced or indented.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CodeBlockKind {
    /// A fenced code block; records the fence char and its run length.
    Fenced {
        /// Which character formed the fence (backtick or tilde).
        marker: FenceMarker,
        /// The number of fence characters in the opening fence (>=3).
        length: usize,
    },
    /// A 4-space-indented code block.
    Indented,
}

/// The character used to fence a [`CodeBlock`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum FenceMarker {
    /// Backtick fence: ```` ``` ````.
    Backtick,
    /// Tilde fence: `~~~`.
    Tilde,
}

/// A raw HTML block: HTML emitted verbatim.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct HtmlBlock {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// The literal HTML source.
    pub value: String,
}

/// A link reference definition. Source: `[label]: destination "title"`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Definition {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// The label as written in the source (e.g. `Foo Bar`).
    pub label: String,
    /// The normalized lookup key (case-folded, whitespace-collapsed) for matching references.
    pub identifier: String,
    /// The link target URL.
    pub destination: String,
    /// How the destination was delimited (bare or `<…>`).
    pub destination_kind: LinkDestinationKind,
    /// The optional link title.
    pub title: Option<String>,
    /// How the title was quoted, if present.
    pub title_kind: Option<LinkTitleKind>,
}

/// A footnote definition. Source: `[^id]: footnote text`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FootnoteDefinition {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// The label as written in the source (the text after `^`).
    pub label: String,
    /// The normalized lookup key matching [`FootnoteReference`]s.
    pub identifier: String,
    /// The footnote's block content.
    pub children: Vec<Block>,
}

/// A GFM pipe table: a header row, an alignment row, then body rows. Source:
/// `| a | b |` / `|---|---|` / `| 1 | 2 |`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Table {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// Per-column alignment from the delimiter row.
    pub alignments: Vec<TableAlignment>,
    /// All rows; the first is the header row.
    pub rows: Vec<TableRow>,
}

/// The alignment of a [`Table`] column, from the `:---:` delimiter row.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum TableAlignment {
    /// No explicit alignment: `---`.
    None,
    /// Left-aligned: `:---`.
    Left,
    /// Center-aligned: `:---:`.
    Center,
    /// Right-aligned: `---:`.
    Right,
}

/// A single row of a [`Table`].
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TableRow {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// The row's cells.
    pub cells: Vec<TableCell>,
}

/// A single cell of a [`TableRow`].
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TableCell {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// The cell's inline content.
    pub children: Vec<Inline>,
}

/// A display math block. Source: `$$ … $$`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MathBlock {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// The literal math contents (between the `$$` fences).
    pub value: String,
}

/// A leading frontmatter block. Source: `---` YAML or `+++` TOML at the top of
/// the document.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Frontmatter {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// Whether the frontmatter is YAML or TOML.
    pub kind: FrontmatterKind,
    /// The literal frontmatter contents (between the fences).
    pub value: String,
}

/// The format of a [`Frontmatter`] block.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum FrontmatterKind {
    /// YAML frontmatter, fenced by `---`.
    Yaml,
    /// TOML frontmatter, fenced by `+++`.
    Toml,
}

/// An MDX ESM block: top-level `import`/`export` statements (distinct from directives).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MdxEsm {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// The literal ESM source.
    pub value: String,
}

/// A block-level MDX expression: `{ … }` (distinct from directives).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MdxExpression {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// The literal expression source (between the braces).
    pub value: String,
}

/// A block-level MDX JSX element (distinct from directives).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MdxJsx {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// The literal JSX source.
    pub value: String,
}

/// A leaf directive. Source: `::name[label]{attrs}` (a directive feature,
/// not MDX).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LeafDirective {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// The directive name following the `::`.
    pub name: String,
    /// The optional `[label]` inline content.
    pub label: Vec<Inline>,
    /// The optional `{attrs}` attributes.
    pub attributes: Vec<DirectiveAttribute>,
}

/// A container directive. Source: `:::name[label]{attrs}` … `:::` (a directive
/// feature, not MDX).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ContainerDirective {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// The directive name following the `:::`.
    pub name: String,
    /// The optional `[label]` inline content.
    pub label: Vec<Inline>,
    /// The optional `{attrs}` attributes.
    pub attributes: Vec<DirectiveAttribute>,
    /// The directive's enclosed block content.
    pub children: Vec<Block>,
}

/// An inline-level node: the leaf and span content inside blocks.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Inline {
    /// Literal text.
    Text(Text),
    /// A backslash escape such as `\*`.
    Escape(Escape),
    /// A character reference such as `&amp;` or `&#247;`.
    CharacterReference(CharacterReference),
    /// Emphasis: `*text*` or `_text_`.
    Emphasis(Emphasis),
    /// Strong emphasis: `**text**` or `__text__`.
    Strong(Strong),
    /// Underline: `__text__`/`___text___` (underscore extension).
    Underline(Underline),
    /// Strikethrough: `~~text~~`.
    Delete(Delete),
    /// A CriticMarkup-style insertion: `++text++`.
    Insert(Insert),
    /// A highlight / "mark" span: `==text==`.
    Mark(Mark),
    /// Subscript: `~x~`.
    Subscript(Subscript),
    /// Superscript: `^x^`.
    Superscript(Superscript),
    /// A spoiler span: `||text||`.
    Spoiler(Spoiler),
    /// An emoji-style shortcode: `:name:`.
    Shortcode(Shortcode),
    /// An inline code span: `` `code` ``.
    Code(CodeInline),
    /// An inline link: `[text](url)`.
    Link(Link),
    /// An inline image: `![alt](url)`.
    Image(Image),
    /// A reference link: `[text][label]`.
    LinkReference(LinkReference),
    /// A reference image: `![alt][label]`.
    ImageReference(ImageReference),
    /// An autolink: `<url>` or a GFM bare URL.
    Autolink(Autolink),
    /// Raw inline HTML such as `<span>`.
    Html(HtmlInline),
    /// A soft line break (a plain newline within a paragraph).
    SoftBreak(SoftBreak),
    /// A hard line break (`\` or two trailing spaces).
    LineBreak(LineBreak),
    /// Inline math: `$x$`.
    Math(MathInline),
    /// A footnote reference: `[^id]`.
    FootnoteReference(FootnoteReference),
    /// An inline footnote: `^[inline note]`.
    InlineFootnote(InlineFootnote),
    /// A wiki link: `[[target|label]]`.
    WikiLink(WikiLink),
    /// An inline MDX expression: `{ … }` (distinct from directives).
    MdxExpression(MdxExpressionInline),
    /// An inline MDX JSX element (distinct from directives).
    MdxJsx(MdxJsxInline),
    /// A text directive: `:name[label]{attrs}` (distinct from MDX).
    TextDirective(TextDirective),
}

/// Literal text content.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Text {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// The text value.
    pub value: String,
}

/// A backslash escape such as `\*` or `\\`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Escape {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// The escaped (literal) character.
    pub value: char,
}

/// A character reference such as `&amp;` or `&#247;`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CharacterReference {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// The reference as written, including `&` and `;` (e.g. `amp` for `&amp;`).
    pub reference: String,
    /// The resolved character value (e.g. `&` for `&amp;`).
    pub value: String,
}

/// Emphasis (typically italic): `*text*` or `_text_`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Emphasis {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// The emphasized inline content.
    pub children: Vec<Inline>,
}

/// Strong emphasis (typically bold): `**text**` or `__text__`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Strong {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// The strongly-emphasized inline content.
    pub children: Vec<Inline>,
}

/// Underline (underscore extension): `__text__` or `___text___`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Underline {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// The underlined inline content.
    pub children: Vec<Inline>,
}

/// Strikethrough: `~~text~~` (or single `~text~` when single-tilde is enabled).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Delete {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// Whether the span used one or two tildes.
    pub marker: DeleteMarker,
    /// The struck-through inline content.
    pub children: Vec<Inline>,
}

/// Which tilde run delimited a [`Delete`] span.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DeleteMarker {
    /// Single-tilde strikethrough: `~text~`.
    SingleTilde,
    /// Double-tilde strikethrough: `~~text~~`.
    DoubleTilde,
}

/// A CriticMarkup-style insertion: `++text++`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Insert {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// The inserted inline content.
    pub children: Vec<Inline>,
}

/// A highlight / "mark" span: `==text==`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Mark {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// The highlighted inline content.
    pub children: Vec<Inline>,
}

/// Subscript: `~x~`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Subscript {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// The subscripted inline content.
    pub children: Vec<Inline>,
}

/// Superscript: `^x^`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Superscript {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// The superscripted inline content.
    pub children: Vec<Inline>,
}

/// A spoiler span: `||text||`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Spoiler {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// The hidden inline content.
    pub children: Vec<Inline>,
}

/// An emoji-style shortcode: `:name:`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Shortcode {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// The shortcode name between the colons (e.g. `smile` for `:smile:`).
    pub name: String,
}

/// An inline code span: `` `code` ``.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CodeInline {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// The normalized code text (trimmed/collapsed per CommonMark).
    pub value: String,
    /// The raw text between the backtick fences, before normalization.
    pub raw: String,
    /// The number of backticks in the fence.
    pub fence_length: usize,
}

/// An inline link: `[text](destination "title")`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Link {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// The link target URL.
    pub destination: String,
    /// How the destination was delimited (bare or `<…>`).
    pub destination_kind: LinkDestinationKind,
    /// The optional link title.
    pub title: Option<String>,
    /// How the title was quoted, if present.
    pub title_kind: Option<LinkTitleKind>,
    /// The link's inline content (the visible text).
    pub children: Vec<Inline>,
}

/// An inline image: `![alt](destination "title")`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Image {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// The image source URL.
    pub destination: String,
    /// How the destination was delimited (bare or `<…>`).
    pub destination_kind: LinkDestinationKind,
    /// The optional image title.
    pub title: Option<String>,
    /// How the title was quoted, if present.
    pub title_kind: Option<LinkTitleKind>,
    /// The image's alt-text inline content.
    pub alt: Vec<Inline>,
}

/// How a link/image destination was delimited in the source.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum LinkDestinationKind {
    /// A bare destination: `(url)`.
    Bare,
    /// An angle-bracketed destination: `(<url>)`.
    Angle,
    /// No destination present: `()`.
    Omitted,
}

/// How a link/image title was quoted in the source.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum LinkTitleKind {
    /// Double-quoted: `"title"`.
    DoubleQuote,
    /// Single-quoted: `'title'`.
    SingleQuote,
    /// Parenthesized: `(title)`.
    Paren,
}

/// A reference link: `[text][label]`, `[text][]`, or `[text]`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LinkReference {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// The normalized lookup key matching a [`Definition`].
    pub identifier: String,
    /// The label as written in the source.
    pub label: String,
    /// Whether the reference is full, collapsed, or shortcut form.
    pub kind: ReferenceKind,
    /// The link's inline content (the visible text).
    pub children: Vec<Inline>,
}

/// A reference image: `![alt][label]`, `![alt][]`, or `![alt]`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ImageReference {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// The normalized lookup key matching a [`Definition`].
    pub identifier: String,
    /// The label as written in the source.
    pub label: String,
    /// Whether the reference is full, collapsed, or shortcut form.
    pub kind: ReferenceKind,
    /// The image's alt-text inline content.
    pub alt: Vec<Inline>,
}

/// The form of a reference link/image.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ReferenceKind {
    /// Full reference: `[text][label]`.
    Full,
    /// Collapsed reference: `[label][]`.
    Collapsed,
    /// Shortcut reference: `[label]`.
    Shortcut,
}

/// An autolink: `<url>` or a GFM bare URL.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Autolink {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// The resolved link href.
    pub destination: String,
    /// Whether the link was angle-bracketed or a GFM literal.
    pub kind: AutolinkKind,
}

/// Whether an [`Autolink`] is angle-bracketed or a GFM bare literal.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum AutolinkKind {
    /// An angle-bracket autolink `<dest>`. The destination is the raw text
    /// between the brackets; `>` is forbidden in the destination and the
    /// serializer re-emits `<dest>`.
    Angle,
    /// A GFM literal autolink (bare `www.`/`http(s)://`/`mailto:`/`xmpp:` URL
    /// or email). `original` is the raw source text that produced the link
    /// (the visible label); `destination` is the synthesized href (e.g. a
    /// `http://`/`mailto:` prefix may have been prepended). The serializer
    /// re-emits `original`, which re-parses to the same literal.
    GfmLiteral {
        /// The raw source text that produced the link (the visible label).
        original: String,
    },
}

/// Raw inline HTML such as `<span>` or `</em>`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct HtmlInline {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// The literal HTML source.
    pub value: String,
}

/// A soft line break: a plain newline within a paragraph.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SoftBreak {
    /// Node metadata (source span).
    pub meta: NodeMeta,
}

/// A hard line break: a trailing `\` or two trailing spaces.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LineBreak {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// Which syntax produced the break.
    pub kind: LineBreakKind,
}

/// Which syntax produced a hard [`LineBreak`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum LineBreakKind {
    /// A trailing backslash: `\`.
    Backslash,
    /// Two or more trailing spaces.
    Spaces,
}

/// Which syntax delimited an inline [`MathInline`] span.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MathInlineKind {
    /// Dollar-fenced inline math (`$…$`, `$$…$$`, …); `dollars` is the fence
    /// length (>=1). Dollar math always renders inline, while a 2-dollar fence
    /// is conventionally treated as display elsewhere in the ecosystem.
    Dollar {
        /// The number of `$` characters in the fence (>=1).
        dollars: u8,
    },
    /// Math-code span: `$`…`$`.
    Code,
}

/// Inline math: `$x$`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MathInline {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// The literal math contents (between the fences).
    pub value: String,
    /// Which delimiter syntax was used.
    pub kind: MathInlineKind,
}

/// A footnote reference: `[^id]`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FootnoteReference {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// The label as written in the source (the text after `^`).
    pub label: String,
    /// The normalized lookup key matching a [`FootnoteDefinition`].
    pub identifier: String,
}

/// An inline footnote: `^[inline note]`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct InlineFootnote {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// The footnote's inline content.
    pub children: Vec<Inline>,
}

/// A wiki link: `[[target|label]]`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct WikiLink {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// The link target (page name).
    pub target: String,
    /// The visible label.
    pub label: String,
    /// Whether the label appeared before or after the `|` in the source.
    pub label_order: WikiLinkLabelOrder,
}

/// Whether a [`WikiLink`]'s label preceded or followed the `|` separator.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum WikiLinkLabelOrder {
    /// Target then label: `[[target|label]]`.
    AfterPipe,
    /// Label then target: `[[label|target]]`.
    BeforePipe,
}

/// An inline MDX expression: `{ … }` (distinct from directives).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MdxExpressionInline {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// The literal expression source (between the braces).
    pub value: String,
}

/// An inline MDX JSX element (distinct from directives).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MdxJsxInline {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// The literal JSX source.
    pub value: String,
}

/// A text directive. Source: `:name[label]{attrs}` (a directive feature,
/// not MDX).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TextDirective {
    /// Node metadata (source span).
    pub meta: NodeMeta,
    /// The directive name following the `:`.
    pub name: String,
    /// The optional `[label]` inline content.
    pub label: Vec<Inline>,
    /// The optional `{attrs}` attributes.
    pub attributes: Vec<DirectiveAttribute>,
}

/// One attribute of a directive's `{name=value}` block.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DirectiveAttribute {
    /// The attribute name.
    pub name: String,
    /// The attribute value, or `None` for a valueless attribute.
    pub value: Option<String>,
}

// ---------------------------------------------------------------------------
// Ergonomic accessors and a minimal construction layer.
//
// Every node carries a `meta: NodeMeta`, so `meta()`/`span()` are uniform across
// the enums and free callers from writing an exhaustive match just to read a
// span. `From`/`new` collapse the `Variant(Struct { meta, .. })` boilerplate for
// hand-built ASTs; the raw struct literals remain available for full control.
// ---------------------------------------------------------------------------

macro_rules! impl_meta_accessors {
    ($enum:ident { $($variant:ident),+ $(,)? }) => {
        impl $enum {
            /// Borrow this node's [`NodeMeta`].
            pub fn meta(&self) -> &NodeMeta {
                match self { $( $enum::$variant(node) => &node.meta, )+ }
            }

            /// This node's source span, if it carries one.
            pub fn span(&self) -> Option<Span> {
                self.meta().span
            }
        }
    };
}

macro_rules! impl_from_variants {
    ($enum:ident { $($variant:ident($ty:ty)),+ $(,)? }) => {
        $(
            impl From<$ty> for $enum {
                fn from(node: $ty) -> Self {
                    $enum::$variant(node)
                }
            }
        )+
    };
}

impl_meta_accessors!(Block {
    Paragraph,
    Heading,
    ThematicBreak,
    BlockQuote,
    Alert,
    List,
    DescriptionList,
    CodeBlock,
    HtmlBlock,
    Definition,
    FootnoteDefinition,
    Table,
    MathBlock,
    Frontmatter,
    MdxEsm,
    MdxExpression,
    MdxJsx,
    LeafDirective,
    ContainerDirective,
});

impl_from_variants!(Block {
    Paragraph(Paragraph), Heading(Heading), ThematicBreak(ThematicBreak),
    BlockQuote(BlockQuote), Alert(Alert), List(List), DescriptionList(DescriptionList),
    CodeBlock(CodeBlock), HtmlBlock(HtmlBlock), Definition(Definition),
    FootnoteDefinition(FootnoteDefinition), Table(Table), MathBlock(MathBlock),
    Frontmatter(Frontmatter), MdxEsm(MdxEsm), MdxExpression(MdxExpression),
    MdxJsx(MdxJsx), LeafDirective(LeafDirective), ContainerDirective(ContainerDirective),
});

impl_meta_accessors!(Inline {
    Text,
    Escape,
    CharacterReference,
    Emphasis,
    Strong,
    Underline,
    Delete,
    Insert,
    Mark,
    Subscript,
    Superscript,
    Spoiler,
    Shortcode,
    Code,
    Link,
    Image,
    LinkReference,
    ImageReference,
    Autolink,
    Html,
    SoftBreak,
    LineBreak,
    Math,
    FootnoteReference,
    InlineFootnote,
    WikiLink,
    MdxExpression,
    MdxJsx,
    TextDirective,
});

impl_from_variants!(Inline {
    Text(Text), Escape(Escape), CharacterReference(CharacterReference),
    Emphasis(Emphasis), Strong(Strong), Underline(Underline), Delete(Delete),
    Insert(Insert), Mark(Mark), Subscript(Subscript), Superscript(Superscript),
    Spoiler(Spoiler), Shortcode(Shortcode), Code(CodeInline), Link(Link), Image(Image),
    LinkReference(LinkReference), ImageReference(ImageReference), Autolink(Autolink),
    Html(HtmlInline), SoftBreak(SoftBreak), LineBreak(LineBreak), Math(MathInline),
    FootnoteReference(FootnoteReference), InlineFootnote(InlineFootnote), WikiLink(WikiLink),
    MdxExpression(MdxExpressionInline), MdxJsx(MdxJsxInline), TextDirective(TextDirective),
});

impl Inline {
    /// The inline subtree of this node, or an empty slice for a leaf. Covers the
    /// `alt`/`label` fields uniformly, so a generic walker never silently skips
    /// an image's alt text or a directive's label.
    pub fn children(&self) -> &[Inline] {
        match self {
            Inline::Emphasis(n) => &n.children,
            Inline::Strong(n) => &n.children,
            Inline::Underline(n) => &n.children,
            Inline::Delete(n) => &n.children,
            Inline::Insert(n) => &n.children,
            Inline::Mark(n) => &n.children,
            Inline::Subscript(n) => &n.children,
            Inline::Superscript(n) => &n.children,
            Inline::Spoiler(n) => &n.children,
            Inline::Link(n) => &n.children,
            Inline::Image(n) => &n.alt,
            Inline::LinkReference(n) => &n.children,
            Inline::ImageReference(n) => &n.alt,
            Inline::InlineFootnote(n) => &n.children,
            Inline::TextDirective(n) => &n.label,
            _ => &[],
        }
    }
}

impl Text {
    /// A text node with the given string value.
    pub fn new(value: impl Into<String>) -> Self {
        Self {
            meta: NodeMeta::default(),
            value: value.into(),
        }
    }
}

impl From<&str> for Text {
    fn from(value: &str) -> Self {
        Text::new(value)
    }
}

impl From<String> for Text {
    fn from(value: String) -> Self {
        Text::new(value)
    }
}

impl Paragraph {
    /// A paragraph from any iterator of inline-convertible children.
    pub fn new<I, T>(children: I) -> Self
    where
        I: IntoIterator<Item = T>,
        T: Into<Inline>,
    {
        Self {
            meta: NodeMeta::default(),
            children: children.into_iter().map(Into::into).collect(),
        }
    }
}

impl Heading {
    /// An ATX heading of the given depth.
    pub fn new<I, T>(depth: u8, children: I) -> Self
    where
        I: IntoIterator<Item = T>,
        T: Into<Inline>,
    {
        Self {
            meta: NodeMeta::default(),
            depth,
            kind: HeadingKind::Atx,
            children: children.into_iter().map(Into::into).collect(),
        }
    }
}

impl Link {
    /// A bare-destination link with no title.
    pub fn new<I, T>(destination: impl Into<String>, children: I) -> Self
    where
        I: IntoIterator<Item = T>,
        T: Into<Inline>,
    {
        Self {
            meta: NodeMeta::default(),
            destination: destination.into(),
            destination_kind: LinkDestinationKind::Bare,
            title: None,
            title_kind: None,
            children: children.into_iter().map(Into::into).collect(),
        }
    }
}

impl CodeInline {
    /// An inline code span with a single-backtick fence.
    pub fn new(value: impl Into<String>) -> Self {
        let value = value.into();
        Self {
            meta: NodeMeta::default(),
            raw: value.clone(),
            value,
            fence_length: 1,
        }
    }
}

impl List {
    /// A tight, dash-delimited bullet list.
    pub fn new<I>(children: I) -> Self
    where
        I: IntoIterator<Item = ListItem>,
    {
        Self {
            meta: NodeMeta::default(),
            ordered: false,
            start: None,
            delimiter: ListDelimiter::Dash,
            tight: true,
            children: children.into_iter().collect(),
        }
    }
}