acdc-parser 0.10.0

`AsciiDoc` parser
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
//! The data models for the `AsciiDoc` document.
use std::{collections::HashMap, fmt::Display, str::FromStr, string::ToString};

use bumpalo::Bump;
use serde::{
    Serialize,
    ser::{SerializeMap, Serializer},
};

mod admonition;
mod anchor;
pub(crate) use anchor::{BibliographyLabel, SectionReference};
mod attributes;
mod attribution;
pub(crate) mod caption;
mod inlines;
mod lists;
mod location;
mod media;
mod metadata;
pub(crate) mod section;
pub(crate) mod substitution;
mod tables;
mod title;

pub use admonition::{Admonition, AdmonitionVariant};
pub use anchor::{Anchor, Reference, TocEntry, UNNUMBERED_SECTION_STYLES};
pub(crate) use attributes::RawAttributes;
pub(crate) use attributes::{
    AttributeInlineFragment, DocumentAttributeStatus, default_document_attribute_values,
};
pub use attributes::{
    AttributeName, AttributeValue, DocumentAttributeAssignment, DocumentAttributeValue,
    DocumentAttributes, ElementAttributes, MAX_SECTION_LEVELS, MAX_TOC_LEVELS, strip_quotes,
};
pub use attribution::{Attribution, CiteTitle};
pub use caption::{Caption, CaptionKind};
pub use inlines::*;
pub use lists::{
    CalloutList, CalloutListItem, DescriptionList, DescriptionListItem, ListItem,
    ListItemCheckedStatus, ListLevel, OrderedList, UnorderedList,
};
pub use location::*;
pub use media::{Audio, Image, Source, SourceUrl, Video};
pub(crate) use metadata::PositionalAttribute;
pub use metadata::{BlockMetadata, Role};
pub use section::*;
pub use substitution::*;
pub use tables::{
    ColumnFormat, ColumnStyle, ColumnWidth, HorizontalAlignment, Table, TableColumn, TableFrame,
    TableGrid, TablePresentation, TableRow, TableStripes, VerticalAlignment,
};
pub use title::{Subtitle, Title};

/// A `Document` represents the root of an `AsciiDoc` document.
#[derive(Default, Debug, PartialEq)]
#[non_exhaustive]
pub struct Document<'a> {
    pub header: Option<Header<'a>>,
    /// Effective end-of-header values. Later accepted changes are ordered
    /// [`Block::DocumentAttribute`] nodes and do not update this snapshot.
    pub attributes: DocumentAttributes<'a>,
    pub blocks: Vec<Block<'a>>,
    pub footnotes: Vec<Footnote<'a>>,
    pub toc_entries: Vec<TocEntry<'a>>,
    /// Cross-reference targets keyed by id, for O(1) `<<id>>` resolution.
    /// Covers sections, blocks, explicit inline anchors, and IDs on formatted
    /// inline spans; collected during parsing. `toc_entries` remains the ordered
    /// list used to render the table of contents. An empty key supplies the
    /// document title or label when a reference addresses the document top.
    /// Like `toc_entries` and
    /// `footnotes`, this is not serialized.
    pub references: HashMap<&'a str, Reference<'a>>,
    pub location: Location,
}

impl Document<'_> {
    /// Reassign section numbers from the current section tree.
    ///
    /// Parsing does this automatically. Call it after changing the section tree or a
    /// section's numbering policy. Existing cross-reference targets and
    /// table-of-contents entries receive the new numbers, but this method does not
    /// add, remove, or reorder those entries.
    ///
    /// Automatic cross-references select the signifier for the target's current
    /// category from their original source-position attributes. Explicit
    /// [`CrossReference::set_signifier`] overrides are preserved.
    pub fn renumber_sections(&mut self) {
        let is_book = matches!(
            self.attributes.get("doctype"),
            Some(value) if value.as_str() == Some("book")
        );
        section::renumber_sections(
            &mut self.blocks,
            &mut self.toc_entries,
            &mut self.references,
            is_book,
        );
        let section_names = self
            .references
            .iter()
            .filter_map(|(target, reference)| Some((*target, reference.section.as_ref()?.name)))
            .collect::<HashMap<_, _>>();
        crate::grammar::walk_document_inline_nodes_mut(self, &mut |inline| {
            if let InlineNode::Macro(InlineMacro::CrossReference(xref)) = inline {
                xref.refresh_signifier(section_names.get(xref.target).copied());
            }
        });
    }

    /// Reassign every automatic caption ordinal, numbering a block's content before the block
    /// itself as asciidoctor does.
    ///
    /// Parsing does this already. Call it after reordering or removing blocks, changing titles,
    /// or inserting a block whose `metadata.caption` has been set. A caller-built block whose
    /// `metadata.caption` is `None` stays unnumbered: nothing knows the document attributes at
    /// a source position it never had, so a converter's own fallback owns it.
    pub fn renumber_captions(&mut self) {
        caption::renumber_captions(&mut self.blocks);
    }

    /// The highest caption ordinal assigned to any block of `kind`, or 0 when none carries one.
    ///
    /// A converter that renders a title the parser never numbered — one on a caller-built
    /// block, or added after parsing — should start its own counter here, so its numbers
    /// cannot collide with the parser's.
    #[must_use]
    pub fn highest_caption_number(&self, kind: CaptionKind) -> u32 {
        caption::highest_caption_number(&self.blocks, kind)
    }
}

/// A `Header` represents the header of a document.
///
/// The header contains the title, subtitle, authors, and optional metadata
/// (such as ID and roles) that can be applied to the document title.
#[derive(Debug, PartialEq, Serialize)]
#[non_exhaustive]
pub struct Header<'a> {
    #[serde(skip_serializing_if = "BlockMetadata::is_default")]
    pub metadata: BlockMetadata<'a>,
    #[serde(skip_serializing_if = "Title::is_empty")]
    pub title: Title<'a>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subtitle: Option<Subtitle<'a>>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub authors: Vec<Author<'a>>,
    pub location: Location,
}

/// An `Author` represents the author of a document.
#[derive(Debug, PartialEq, Serialize)]
#[non_exhaustive]
pub struct Author<'a> {
    #[serde(rename = "firstname")]
    pub first_name: &'a str,
    #[serde(skip_serializing_if = "Option::is_none", rename = "middlename")]
    pub middle_name: Option<&'a str>,
    #[serde(rename = "lastname")]
    pub last_name: &'a str,
    pub initials: &'a str,
    #[serde(skip_serializing_if = "Option::is_none", rename = "address")]
    pub email: Option<&'a str>,
}

impl<'a> Header<'a> {
    /// Create a new header with the given title and location.
    #[must_use]
    pub fn new(title: Title<'a>, location: Location) -> Self {
        Self {
            metadata: BlockMetadata::default(),
            title,
            subtitle: None,
            authors: Vec::new(),
            location,
        }
    }

    /// Set the metadata.
    #[must_use]
    pub fn with_metadata(mut self, metadata: BlockMetadata<'a>) -> Self {
        self.metadata = metadata;
        self
    }

    /// Set the subtitle.
    #[must_use]
    pub fn with_subtitle(mut self, subtitle: Subtitle<'a>) -> Self {
        self.subtitle = Some(subtitle);
        self
    }

    /// Set the authors.
    #[must_use]
    pub fn with_authors(mut self, authors: Vec<Author<'a>>) -> Self {
        self.authors = authors;
        self
    }
}

impl<'a> Author<'a> {
    /// Assemble an author from already-prepared name parts. No normalization
    /// or allocation happens — callers (tests, external consumers) are
    /// responsible for providing the display-ready strings they want.
    #[must_use]
    pub fn from_parts(
        first_name: &'a str,
        middle_name: Option<&'a str>,
        last_name: &'a str,
        initials: &'a str,
    ) -> Self {
        Self {
            first_name,
            middle_name,
            last_name,
            initials,
            email: None,
        }
    }

    /// Create a new author with the given names. Arena-allocates any
    /// underscore-normalized strings and computed initials.
    #[must_use]
    pub(crate) fn new(
        arena: &'a Bump,
        first_name: &'a str,
        middle_name: Option<&'a str>,
        last_name: Option<&'a str>,
    ) -> Self {
        let first_processed = first_name.replace('_', " ");
        let middle_processed = middle_name.map(|m| m.replace('_', " "));
        let last_processed = last_name.map(|l| l.replace('_', " "));

        let initials = Self::generate_initials(
            &first_processed,
            middle_processed.as_deref(),
            last_processed.as_deref(),
        );

        Self {
            first_name: if first_processed == first_name {
                first_name
            } else {
                arena.alloc_str(&first_processed)
            },
            middle_name: middle_name
                .zip(middle_processed.as_ref())
                .map(|(orig, proc)| {
                    if proc == orig {
                        orig
                    } else {
                        &*arena.alloc_str(proc)
                    }
                }),
            last_name: last_name
                .zip(last_processed.as_ref())
                .map_or("", |(orig, proc)| {
                    if proc == orig {
                        orig
                    } else {
                        arena.alloc_str(proc)
                    }
                }),
            initials: arena.alloc_str(&initials),
            email: None,
        }
    }

    /// Set the email address.
    #[must_use]
    pub fn with_email(mut self, email: &'a str) -> Self {
        self.email = Some(email);
        self
    }

    /// Generate initials from first, optional middle, and last name parts
    fn generate_initials(first: &str, middle: Option<&str>, last: Option<&str>) -> String {
        let first_initial = first.chars().next().unwrap_or_default().to_string();
        let middle_initial = middle
            .map(|m| m.chars().next().unwrap_or_default().to_string())
            .unwrap_or_default();
        let last_initial = last
            .map(|m| m.chars().next().unwrap_or_default().to_string())
            .unwrap_or_default();
        first_initial + &middle_initial + &last_initial
    }
}

/// The syntactic form a [`Comment`] originated from.
///
/// A `[comment]`-styled `--` block is represented as a
/// [`DelimitedBlockType::DelimitedComment`] (distinguished from a `////` block
/// by its retained `comment` style), so it is not covered here.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum CommentKind {
    /// A `//` single-line comment.
    #[default]
    Line,
    /// A `[comment]`-styled paragraph.
    Paragraph,
}

/// A comment in a document that produces no output.
///
/// Either a `//` single-line comment or a `[comment]`-styled paragraph; the
/// [`kind`](Comment::kind) distinguishes them.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct Comment<'a> {
    pub kind: CommentKind,
    pub content: &'a str,
    pub location: Location,
}

/// A `Block` represents a block in a document.
///
/// A block is a structural element in a document that can contain other blocks.
// The variant sizes differ widely by design — `DelimitedBlock`/`Image` are large
// value types while `PageBreak`/`Comment` are tiny. Boxing the large variants is a
// separate refactor; the disparity is structural, not a per-node-allocation concern.
#[allow(clippy::large_enum_variant)]
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(untagged)]
pub enum Block<'a> {
    TableOfContents(TableOfContents<'a>),
    // TODO(nlopes): we shouldn't have an admonition type here, instead it should be
    // picked up from the style attribute from the block metadata.
    //
    // The main one that would need changing is the Paragraph and the Delimited Example
    // blocks, where we currently use this but don't need to.
    Admonition(Admonition<'a>),
    DiscreteHeader(DiscreteHeader<'a>),
    DocumentAttribute(DocumentAttribute<'a>),
    ThematicBreak(ThematicBreak<'a>),
    PageBreak(PageBreak<'a>),
    UnorderedList(UnorderedList<'a>),
    OrderedList(OrderedList<'a>),
    CalloutList(CalloutList<'a>),
    DescriptionList(DescriptionList<'a>),
    Section(Section<'a>),
    DelimitedBlock(DelimitedBlock<'a>),
    Paragraph(Paragraph<'a>),
    Image(Image<'a>),
    Audio(Audio<'a>),
    Video(Video<'a>),
    Comment(Comment<'a>),
}

impl<'a> Block<'a> {
    /// The source location of this block.
    #[must_use]
    pub fn location(&self) -> &Location {
        match self {
            Block::Section(s) => &s.location,
            Block::Paragraph(p) => &p.location,
            Block::UnorderedList(l) => &l.location,
            Block::OrderedList(l) => &l.location,
            Block::DescriptionList(l) => &l.location,
            Block::CalloutList(l) => &l.location,
            Block::DelimitedBlock(d) => &d.location,
            Block::Admonition(a) => &a.location,
            Block::TableOfContents(t) => &t.location,
            Block::DiscreteHeader(h) => &h.location,
            Block::DocumentAttribute(a) => &a.location,
            Block::ThematicBreak(tb) => &tb.location,
            Block::PageBreak(pb) => &pb.location,
            Block::Image(i) => &i.location,
            Block::Audio(a) => &a.location,
            Block::Video(v) => &v.location,
            Block::Comment(c) => &c.location,
        }
    }

    /// This block's metadata, for the blocks that carry any.
    #[must_use]
    pub fn metadata(&self) -> Option<&BlockMetadata<'a>> {
        match self {
            Block::Section(block) => Some(&block.metadata),
            Block::DelimitedBlock(block) => Some(&block.metadata),
            Block::Admonition(block) => Some(&block.metadata),
            Block::DiscreteHeader(block) => Some(&block.metadata),
            Block::PageBreak(block) => Some(&block.metadata),
            Block::Paragraph(block) => Some(&block.metadata),
            Block::Image(block) => Some(&block.metadata),
            Block::Audio(block) => Some(&block.metadata),
            Block::Video(block) => Some(&block.metadata),
            Block::UnorderedList(block) => Some(&block.metadata),
            Block::OrderedList(block) => Some(&block.metadata),
            Block::CalloutList(block) => Some(&block.metadata),
            Block::DescriptionList(block) => Some(&block.metadata),
            Block::TableOfContents(block) => Some(&block.metadata),
            Block::ThematicBreak(_) | Block::DocumentAttribute(_) | Block::Comment(_) => None,
        }
    }

    /// This block's metadata, for the blocks that carry any.
    pub(crate) fn metadata_mut(&mut self) -> Option<&mut BlockMetadata<'a>> {
        match self {
            Block::Section(block) => Some(&mut block.metadata),
            Block::DelimitedBlock(block) => Some(&mut block.metadata),
            Block::Admonition(block) => Some(&mut block.metadata),
            Block::DiscreteHeader(block) => Some(&mut block.metadata),
            Block::PageBreak(block) => Some(&mut block.metadata),
            Block::Paragraph(block) => Some(&mut block.metadata),
            Block::Image(block) => Some(&mut block.metadata),
            Block::Audio(block) => Some(&mut block.metadata),
            Block::Video(block) => Some(&mut block.metadata),
            Block::UnorderedList(block) => Some(&mut block.metadata),
            Block::OrderedList(block) => Some(&mut block.metadata),
            Block::CalloutList(block) => Some(&mut block.metadata),
            Block::DescriptionList(block) => Some(&mut block.metadata),
            Block::TableOfContents(block) => Some(&mut block.metadata),
            Block::ThematicBreak(_) | Block::DocumentAttribute(_) | Block::Comment(_) => None,
        }
    }

    /// The anchor defining this block's id (its cross-reference target), if any:
    /// the explicit `[#id]` or the first `[[id]]` anchor.
    pub(crate) fn anchor(&self) -> Option<&Anchor<'a>> {
        match self {
            Block::Section(b) => b.metadata.id_anchor(),
            Block::DelimitedBlock(b) => b.metadata.id_anchor(),
            Block::Admonition(b) => b.metadata.id_anchor(),
            Block::DiscreteHeader(b) => b.metadata.id_anchor(),
            Block::PageBreak(b) => b.metadata.id_anchor(),
            Block::Paragraph(b) => b.metadata.id_anchor(),
            Block::Image(b) => b.metadata.id_anchor(),
            Block::Audio(b) => b.metadata.id_anchor(),
            Block::Video(b) => b.metadata.id_anchor(),
            Block::UnorderedList(b) => b.metadata.id_anchor(),
            Block::OrderedList(b) => b.metadata.id_anchor(),
            Block::CalloutList(b) => b.metadata.id_anchor(),
            Block::DescriptionList(b) => b.metadata.id_anchor(),
            Block::TableOfContents(b) => b.metadata.id_anchor(),
            Block::ThematicBreak(b) => b.anchors.first(),
            Block::DocumentAttribute(_) | Block::Comment(_) => None,
        }
    }

    /// This block's title, if it has a non-empty one (used as the cross-reference
    /// text when an `<<id>>` to this block has no explicit label).
    pub(crate) fn title(&self) -> Option<&Title<'a>> {
        let title = match self {
            Block::Section(b) => &b.title,
            Block::DelimitedBlock(b) => &b.title,
            Block::Admonition(b) => &b.title,
            Block::DiscreteHeader(b) => &b.title,
            Block::PageBreak(b) => &b.title,
            Block::Paragraph(b) => &b.title,
            Block::Image(b) => &b.title,
            Block::Audio(b) => &b.title,
            Block::Video(b) => &b.title,
            Block::UnorderedList(b) => &b.title,
            Block::OrderedList(b) => &b.title,
            Block::CalloutList(b) => &b.title,
            Block::DescriptionList(b) => &b.title,
            Block::ThematicBreak(b) => &b.title,
            Block::TableOfContents(_) | Block::DocumentAttribute(_) | Block::Comment(_) => {
                return None;
            }
        };
        (!title.is_empty()).then_some(title)
    }
}

impl Block<'_> {
    /// Mutable access to this block's own location (the post-parse source remap
    /// pass rewrites it). Counterpart to [`Self::location`].
    pub(crate) fn location_mut(&mut self) -> &mut Location {
        match self {
            Block::Section(s) => &mut s.location,
            Block::Paragraph(p) => &mut p.location,
            Block::UnorderedList(l) => &mut l.location,
            Block::OrderedList(l) => &mut l.location,
            Block::DescriptionList(l) => &mut l.location,
            Block::CalloutList(l) => &mut l.location,
            Block::DelimitedBlock(d) => &mut d.location,
            Block::Admonition(a) => &mut a.location,
            Block::TableOfContents(t) => &mut t.location,
            Block::DiscreteHeader(h) => &mut h.location,
            Block::DocumentAttribute(a) => &mut a.location,
            Block::ThematicBreak(tb) => &mut tb.location,
            Block::PageBreak(pb) => &mut pb.location,
            Block::Image(i) => &mut i.location,
            Block::Audio(a) => &mut a.location,
            Block::Video(v) => &mut v.location,
            Block::Comment(c) => &mut c.location,
        }
    }
}

/// An accepted document-attribute assignment in the document body.
#[derive(Clone, PartialEq)]
#[non_exhaustive]
pub struct DocumentAttribute<'a> {
    pub name: AttributeName<'a>,
    pub location: Location,
    assignment: DocumentAttributeAssignment<'a>,
    accepted: bool,
}

impl<'a> DocumentAttribute<'a> {
    pub(crate) fn accepted(
        name: AttributeName<'a>,
        applied: DocumentAttributeAssignment<'a>,
        location: Location,
    ) -> Self {
        Self {
            name,
            location,
            assignment: applied,
            accepted: true,
        }
    }

    pub(crate) fn rejected(name: AttributeName<'a>, location: Location) -> Self {
        Self {
            name,
            location,
            assignment: DocumentAttributeAssignment::Unset,
            accepted: false,
        }
    }

    pub(crate) const fn is_accepted(&self) -> bool {
        self.accepted
    }

    /// Borrow the accepted set or unset assignment.
    #[must_use]
    pub const fn assignment(&self) -> &DocumentAttributeAssignment<'a> {
        &self.assignment
    }
}

impl std::fmt::Debug for DocumentAttribute<'_> {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("DocumentAttribute")
            .field("name", &self.name)
            .field("assignment", &self.assignment)
            .field("location", &self.location)
            .field("accepted", &self.accepted)
            .finish()
    }
}

impl Serialize for DocumentAttribute<'_> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut state = serializer.serialize_map(None)?;
        state.serialize_entry("name", &self.name)?;
        state.serialize_entry("type", "attribute")?;
        state.serialize_entry("value", &self.assignment.serialized_value(false))?;
        state.serialize_entry("location", &self.location)?;
        state.end()
    }
}

/// A `DiscreteHeader` represents a discrete header in a document.
///
/// Discrete headings are useful for making headings inside of other blocks, like a
/// sidebar.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct DiscreteHeader<'a> {
    pub metadata: BlockMetadata<'a>,
    pub title: Title<'a>,
    pub level: u8,
    pub location: Location,
}

/// A `ThematicBreak` represents a thematic break in a document.
#[derive(Clone, Default, Debug, PartialEq)]
#[non_exhaustive]
pub struct ThematicBreak<'a> {
    pub anchors: Vec<Anchor<'a>>,
    pub title: Title<'a>,
    pub location: Location,
}

impl Serialize for ThematicBreak<'_> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut state = serializer.serialize_map(None)?;
        state.serialize_entry("name", "break")?;
        state.serialize_entry("type", "block")?;
        state.serialize_entry("variant", "thematic")?;
        if !self.anchors.is_empty() {
            state.serialize_entry("anchors", &self.anchors)?;
        }
        if !self.title.is_empty() {
            state.serialize_entry("title", &self.title)?;
        }
        state.serialize_entry("location", &self.location)?;
        state.end()
    }
}

/// A `PageBreak` represents a page break in a document.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct PageBreak<'a> {
    pub title: Title<'a>,
    pub metadata: BlockMetadata<'a>,
    pub location: Location,
}

impl Serialize for PageBreak<'_> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut state = serializer.serialize_map(None)?;
        state.serialize_entry("name", "break")?;
        state.serialize_entry("type", "block")?;
        state.serialize_entry("variant", "page")?;
        if !self.title.is_empty() {
            state.serialize_entry("title", &self.title)?;
        }
        if !self.metadata.is_default() {
            state.serialize_entry("metadata", &self.metadata)?;
        }
        state.serialize_entry("location", &self.location)?;
        state.end()
    }
}

impl Serialize for Comment<'_> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut state = serializer.serialize_map(None)?;
        state.serialize_entry("name", "comment")?;
        state.serialize_entry("type", "block")?;
        // Omit the default `Line` kind so plain `//` comments serialize unchanged.
        if self.kind != CommentKind::Line {
            state.serialize_entry("variant", &self.kind)?;
        }
        if !self.content.is_empty() {
            state.serialize_entry("content", &self.content)?;
        }
        state.serialize_entry("location", &self.location)?;
        state.end()
    }
}

/// A `TableOfContents` represents a table of contents block.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct TableOfContents<'a> {
    pub metadata: BlockMetadata<'a>,
    pub location: Location,
}

impl Serialize for TableOfContents<'_> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut state = serializer.serialize_map(None)?;
        state.serialize_entry("name", "toc")?;
        state.serialize_entry("type", "block")?;
        if !self.metadata.is_default() {
            state.serialize_entry("metadata", &self.metadata)?;
        }
        state.serialize_entry("location", &self.location)?;
        state.end()
    }
}

/// A `Paragraph` represents a paragraph in a document.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct Paragraph<'a> {
    pub metadata: BlockMetadata<'a>,
    pub title: Title<'a>,
    pub content: Vec<InlineNode<'a>>,
    pub location: Location,
    pub(crate) source_text: Option<&'a str>,
}

impl PartialEq for Paragraph<'_> {
    fn eq(&self, other: &Self) -> bool {
        self.metadata == other.metadata
            && self.title == other.title
            && self.content == other.content
            && self.location == other.location
    }
}

impl<'a> Paragraph<'a> {
    /// Create a new paragraph with the given content and location.
    #[must_use]
    pub fn new(content: Vec<InlineNode<'a>>, location: Location) -> Self {
        Self {
            metadata: BlockMetadata::default(),
            title: Title::default(),
            content,
            location,
            source_text: None,
        }
    }

    /// The paragraph body after document preprocessing, before inline substitutions.
    ///
    /// Absent for programmatically constructed paragraphs. This text is not part
    /// of ASG serialization or semantic equality.
    #[must_use]
    pub fn source_text(&self) -> Option<&'a str> {
        self.source_text
    }

    /// Set the metadata.
    #[must_use]
    pub fn with_metadata(mut self, metadata: BlockMetadata<'a>) -> Self {
        self.metadata = metadata;
        self
    }

    /// Set the title.
    #[must_use]
    pub fn with_title(mut self, title: Title<'a>) -> Self {
        self.title = title;
        self
    }
}

/// A `DelimitedBlock` represents a delimited block in a document.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct DelimitedBlock<'a> {
    pub metadata: BlockMetadata<'a>,
    pub inner: DelimitedBlockType<'a>,
    pub delimiter: &'a str,
    pub title: Title<'a>,
    pub location: Location,
    pub open_delimiter_location: Option<Location>,
    pub close_delimiter_location: Option<Location>,
    pub(crate) source_text: Option<&'a str>,
}

impl PartialEq for DelimitedBlock<'_> {
    fn eq(&self, other: &Self) -> bool {
        self.metadata == other.metadata
            && self.inner == other.inner
            && self.delimiter == other.delimiter
            && self.title == other.title
            && self.location == other.location
            && self.open_delimiter_location == other.open_delimiter_location
            && self.close_delimiter_location == other.close_delimiter_location
    }
}

impl<'a> DelimitedBlock<'a> {
    /// Create a new delimited block.
    #[must_use]
    pub fn new(inner: DelimitedBlockType<'a>, delimiter: &'a str, location: Location) -> Self {
        Self {
            metadata: BlockMetadata::default(),
            inner,
            delimiter,
            title: Title::default(),
            location,
            open_delimiter_location: None,
            close_delimiter_location: None,
            source_text: None,
        }
    }

    /// The body after document preprocessing, before inline substitutions.
    ///
    /// Delimiters and metadata are excluded; a newline before the closing delimiter
    /// is retained. Absent for programmatically constructed or synthetic blocks.
    /// This text is not part of ASG serialization or semantic equality.
    #[must_use]
    pub fn source_text(&self) -> Option<&'a str> {
        self.source_text
    }

    /// Set the metadata.
    #[must_use]
    pub fn with_metadata(mut self, metadata: BlockMetadata<'a>) -> Self {
        self.metadata = metadata;
        self
    }

    /// Set the title.
    #[must_use]
    pub fn with_title(mut self, title: Title<'a>) -> Self {
        self.title = title;
        self
    }
}

/// Notation type for mathematical expressions.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum StemNotation {
    Latexmath,
    Asciimath,
}

impl Display for StemNotation {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            StemNotation::Latexmath => write!(f, "latexmath"),
            StemNotation::Asciimath => write!(f, "asciimath"),
        }
    }
}

impl FromStr for StemNotation {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "latexmath" => Ok(Self::Latexmath),
            "asciimath" => Ok(Self::Asciimath),
            _ => Err(format!("unknown stem notation: {s}")),
        }
    }
}

/// Content of a stem block with math notation.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[non_exhaustive]
pub struct StemContent<'a> {
    pub content: &'a str,
    pub notation: StemNotation,
}

impl<'a> StemContent<'a> {
    /// Create a new stem content with the given content and notation.
    #[must_use]
    pub fn new(content: &'a str, notation: StemNotation) -> Self {
        Self { content, notation }
    }
}

/// The inner content type of a delimited block.
///
/// Each variant wraps the content appropriate for that block type:
/// - **Verbatim content** (`Vec<InlineNode>`): `DelimitedListing`, `DelimitedLiteral`,
///   `DelimitedPass`, `DelimitedVerse`, `DelimitedComment` - preserves whitespace/formatting
/// - **Compound content** (`Vec<Block>`): `DelimitedExample`, `DelimitedOpen`,
///   `DelimitedSidebar`, `DelimitedQuote` - can contain nested blocks
/// - **Structured content**: `DelimitedTable(Table)`, `DelimitedStem(StemContent)`
///
/// # Accessing Content
///
/// Use pattern matching to extract the inner content:
///
/// ```
/// # use acdc_parser::{DelimitedBlockType, Block, InlineNode};
/// fn process_block(block_type: &DelimitedBlockType) {
///     match block_type {
///         DelimitedBlockType::DelimitedListing(inlines) => {
///             // Handle listing content (source code, etc.)
///         }
///         DelimitedBlockType::DelimitedExample(blocks) => {
///             // Handle example with nested blocks
///         }
///         DelimitedBlockType::DelimitedTable(table) => {
///             // Access table.rows, table.header, etc.
///         }
///         // ... other variants
///         _ => {}
///     }
/// }
/// ```
///
/// # Note on Variant Names
///
/// Variants are prefixed with `Delimited` to disambiguate from potential future
/// non-delimited block types and to make pattern matching more explicit.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(untagged)]
pub enum DelimitedBlockType<'a> {
    /// Comment block content (not rendered in output).
    DelimitedComment(Vec<InlineNode<'a>>),
    /// Example block - can contain nested blocks, admonitions, etc.
    DelimitedExample(Vec<Block<'a>>),
    /// Listing block - typically source code with syntax highlighting.
    DelimitedListing(Vec<InlineNode<'a>>),
    /// Literal block - preformatted text rendered verbatim.
    DelimitedLiteral(Vec<InlineNode<'a>>),
    /// Open block - generic container for nested blocks.
    DelimitedOpen(Vec<Block<'a>>),
    /// Sidebar block - supplementary content in a styled container.
    DelimitedSidebar(Vec<Block<'a>>),
    /// Table block - structured tabular data.
    DelimitedTable(Table<'a>),
    /// Passthrough block - content passed directly to output without processing.
    DelimitedPass(Vec<InlineNode<'a>>),
    /// Quote block - blockquote with optional attribution.
    DelimitedQuote(Vec<Block<'a>>),
    /// Verse block - poetry/lyrics preserving line breaks.
    DelimitedVerse(Vec<InlineNode<'a>>),
    /// STEM (math) block - LaTeX or `AsciiMath` notation.
    DelimitedStem(StemContent<'a>),
}

impl DelimitedBlockType<'_> {
    fn name(&self) -> &'static str {
        match self {
            DelimitedBlockType::DelimitedComment(_) => "comment",
            DelimitedBlockType::DelimitedExample(_) => "example",
            DelimitedBlockType::DelimitedListing(_) => "listing",
            DelimitedBlockType::DelimitedLiteral(_) => "literal",
            DelimitedBlockType::DelimitedOpen(_) => "open",
            DelimitedBlockType::DelimitedSidebar(_) => "sidebar",
            DelimitedBlockType::DelimitedTable(_) => "table",
            DelimitedBlockType::DelimitedPass(_) => "pass",
            DelimitedBlockType::DelimitedQuote(_) => "quote",
            DelimitedBlockType::DelimitedVerse(_) => "verse",
            DelimitedBlockType::DelimitedStem(_) => "stem",
        }
    }
}

impl Serialize for Document<'_> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut state = serializer.serialize_map(None)?;
        state.serialize_entry("name", "document")?;
        state.serialize_entry("type", "block")?;
        if let Some(header) = &self.header {
            state.serialize_entry("header", header)?;
            // We serialize the attributes even if they're empty because that's what the
            // TCK expects (odd but true)
            state.serialize_entry("attributes", &self.attributes)?;
        } else if !self.attributes.serialization_is_empty() {
            state.serialize_entry("attributes", &self.attributes)?;
        }
        if !self.blocks.is_empty() {
            state.serialize_entry("blocks", &self.blocks)?;
        }
        state.serialize_entry("location", &self.location)?;
        state.end()
    }
}

impl Serialize for DelimitedBlock<'_> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut state = serializer.serialize_map(None)?;
        state.serialize_entry("name", self.inner.name())?;
        state.serialize_entry("type", "block")?;
        state.serialize_entry("form", "delimited")?;
        state.serialize_entry("delimiter", &self.delimiter)?;
        if !self.metadata.is_default() {
            state.serialize_entry("metadata", &self.metadata)?;
        }

        match &self.inner {
            DelimitedBlockType::DelimitedStem(stem) => {
                state.serialize_entry("content", &stem.content)?;
                state.serialize_entry("notation", &stem.notation)?;
            }
            DelimitedBlockType::DelimitedListing(inner)
            | DelimitedBlockType::DelimitedLiteral(inner)
            | DelimitedBlockType::DelimitedPass(inner)
            | DelimitedBlockType::DelimitedVerse(inner) => {
                state.serialize_entry("inlines", &inner)?;
            }
            DelimitedBlockType::DelimitedTable(inner) => {
                state.serialize_entry("content", &inner)?;
            }
            inner @ (DelimitedBlockType::DelimitedComment(_)
            | DelimitedBlockType::DelimitedExample(_)
            | DelimitedBlockType::DelimitedOpen(_)
            | DelimitedBlockType::DelimitedQuote(_)
            | DelimitedBlockType::DelimitedSidebar(_)) => {
                state.serialize_entry("blocks", &inner)?;
            }
        }
        if !self.title.is_empty() {
            state.serialize_entry("title", &self.title)?;
        }
        state.serialize_entry("location", &self.location)?;
        state.end()
    }
}

impl Serialize for DiscreteHeader<'_> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut state = serializer.serialize_map(None)?;
        state.serialize_entry("name", "heading")?;
        state.serialize_entry("type", "block")?;
        if !self.title.is_empty() {
            state.serialize_entry("title", &self.title)?;
        }
        state.serialize_entry("level", &self.level)?;
        if !self.metadata.is_default() {
            state.serialize_entry("metadata", &self.metadata)?;
        }
        state.serialize_entry("location", &self.location)?;
        state.end()
    }
}

impl Serialize for Paragraph<'_> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut state = serializer.serialize_map(None)?;
        state.serialize_entry("name", "paragraph")?;
        state.serialize_entry("type", "block")?;
        if !self.title.is_empty() {
            state.serialize_entry("title", &self.title)?;
        }
        state.serialize_entry("inlines", &self.content)?;
        if !self.metadata.is_default() {
            state.serialize_entry("metadata", &self.metadata)?;
        }
        state.serialize_entry("location", &self.location)?;
        state.end()
    }
}