asciidoc-parser 0.28.1

Parser for AsciiDoc format
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
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
//! Describes where (and whether) a document's table of contents is rendered,
//! together with the resolved depth, title, and CSS class.

use crate::{Parser, document::InterpretedValue};

/// Where (and whether) a document's table of contents (TOC) is generated,
/// resolved from the [`toc` attribute] and, when `toc` carries no placement
/// keyword, the `toc-placement` attribute.
///
/// The `toc`/`toc-placement` attributes are header-only, so this value is fixed
/// once a document's header has been processed. A nested [AsciiDoc table cell]
/// behaves as its own standalone document and resolves its own [`TocMode`]
/// independently – it does **not** inherit the parent document's setting.
///
/// The `auto`, `left`, `right`, `top`, and `bottom` placements all render the
/// TOC automatically near the top of the document;
/// `left`/`right`/`top`/`bottom` additionally request a fixed side (or
/// top/bottom) column when converting to standalone HTML (a presentation detail
/// outside this crate's scope). `preamble` places the TOC immediately below the
/// preamble, and `macro` defers placement to a `toc::[]` block macro.
///
/// The positional placement can be selected by a keyword or a direction
/// shorthand in the `toc` value (`<`/`>`/`^`/`v` for `left`/`right`/`top`/
/// `bottom`), by the separate `toc-position` attribute, or by the legacy `toc2`
/// alias, mirroring Asciidoctor's header normalization.
///
/// [`toc` attribute]: https://docs.asciidoctor.org/asciidoc/latest/toc/
/// [AsciiDoc table cell]: crate::blocks::TableCellContent::AsciiDoc
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum TocMode {
    /// The `toc` attribute is unset: no table of contents is generated.
    Disabled,

    /// The `toc` attribute is empty (the value an empty `:toc:` resolves to) or
    /// set to `auto`. The TOC is generated automatically near the top of the
    /// document.
    Auto,

    /// The `toc` attribute is set to `left` (or the legacy `toc2` alias is
    /// set): an automatically placed TOC that, in standalone HTML, is rendered
    /// as a fixed left-hand side column.
    Left,

    /// The `toc` attribute is set to `right`: an automatically placed TOC that,
    /// in standalone HTML, is rendered as a fixed right-hand side column.
    Right,

    /// The placement resolves to `top` (via `:toc: top` / `:toc: ^`, or a
    /// `toc-position` of `top`): an automatically placed TOC rendered as a
    /// fixed top column in standalone HTML.
    Top,

    /// The placement resolves to `bottom` (via `:toc: bottom` / `:toc: v`, or a
    /// `toc-position` of `bottom`): an automatically placed TOC rendered as a
    /// fixed bottom column in standalone HTML.
    Bottom,

    /// The placement resolves to `preamble` (via `:toc: preamble` or
    /// `:toc-placement: preamble`): the TOC is generated immediately below the
    /// document's preamble.
    Preamble,

    /// The placement resolves to `macro` (via `:toc: macro` or
    /// `:toc-placement: macro`): the table of contents is generated only where
    /// a `toc::[]` block macro appears.
    Macro,
}

impl TocMode {
    /// Resolves the table-of-contents placement from a parser's current `toc`
    /// attribute state, mirroring Asciidoctor's header normalization
    /// (`lib/asciidoctor/document.rb`, the `toc_val = (attrs.delete 'toc2') …`
    /// block).
    ///
    /// This reads the raw stored `toc`, `toc2`, `toc-placement`, and
    /// `toc-position` attributes, distinguishing a never-set `toc-placement`
    /// from an explicit unset tombstone. The derived `toc-position` /
    /// `toc-placement` / `toc-class` document attributes are materialized from
    /// the resolved placement *after* this runs – see
    /// [`Parser::materialize_toc_attributes`](crate::Parser).
    pub(crate) fn from_parser(parser: &Parser) -> Self {
        // Asciidoctor: `toc_val = (attrs.delete 'toc2') ? 'left' : attrs['toc']`.
        // `toc2` is a legacy alias for a left side-column TOC: when set it
        // overrides the `toc` value with `left`. (A soft-unset `toc2!` records an
        // `Unset` tombstone, which does not enable it.)
        let toc_val = if parser.attribute_value("toc2") != InterpretedValue::Unset {
            "left".to_string()
        } else {
            let toc = parser.attribute_value("toc");

            // No `toc` (and no `toc2`): no table of contents is generated.
            if toc == InterpretedValue::Unset {
                return Self::Disabled;
            }

            // `toc` carries a built-in `auto` default, so a bare `:toc:` reads as
            // `Value("auto")` (never `Set`); any other value is taken as-is, and a
            // set-but-empty value folds to empty.
            toc.as_maybe_str().unwrap_or_default().to_string()
        };

        // A bare `:toc:` carries this crate's built-in `auto` default; Asciidoctor
        // treats a bare `toc` as an empty value, so fold `auto` back to empty to
        // match its `toc_val.empty?` branches below.
        let toc_val = toc_val.trim();
        let toc_val = if toc_val == "auto" { "" } else { toc_val };

        // `toc-placement` lets a document separate the *position* of the TOC from
        // the *slot* it occupies. Asciidoctor fetches it with a `macro` fallback
        // (`attrs.fetch 'toc-placement', 'macro'`) while its default attribute
        // normally seeds `auto`; this crate seeds no such default, so a never-set
        // `toc-placement` reads as `auto`, an explicit value is taken as-is, and a
        // soft-unset tombstone – which Asciidoctor *deletes*, so its `fetch` yields
        // the `macro` fallback – reads as `macro`.
        let toc_placement_val = match parser.attribute_value("toc-placement") {
            InterpretedValue::Value(v) => v.trim().to_string(),
            InterpretedValue::Set => String::new(),
            InterpretedValue::Unset if parser.has_attribute("toc-placement") => "macro".to_string(),
            InterpretedValue::Unset => "auto".to_string(),
        };

        // Asciidoctor: `toc_placement_val && toc_placement_val != 'auto' ?
        // toc_placement_val : attrs['toc-position']`. When `toc-placement` names
        // anything other than `auto` it *is* the position (so `preamble`/`macro`,
        // or a side keyword on `toc-placement`, override the `toc` value's own
        // keyword); otherwise the separate `toc-position` attribute supplies it.
        let toc_position_val = if toc_placement_val != "auto" {
            toc_placement_val
        } else {
            parser
                .attribute_value("toc-position")
                .as_maybe_str()
                .map(str::trim)
                .unwrap_or_default()
                .to_string()
        };

        // With neither a `toc` value nor a resolved position, the TOC is an
        // ordinary automatically placed top TOC (Asciidoctor skips its
        // normalization block, leaving `toc-position` unset).
        if toc_val.is_empty() && toc_position_val.is_empty() {
            return Self::Auto;
        }

        // A resolved `toc-position` wins over the `toc` value; when `toc-position`
        // is empty the empty/empty early return above guarantees a non-empty `toc`
        // value, which then supplies the position. (Asciidoctor's
        // `default_toc_position` fallback of `left` is likewise unreachable once
        // that case has returned.)
        let position = if toc_position_val.is_empty() {
            toc_val
        } else {
            toc_position_val.as_str()
        };

        // Map the resolved position to a placement, mirroring Asciidoctor's
        // `case`. The direction shorthands arrive here already special-character
        // substituted (`>` as `&gt;`, `<` as `&lt;`), so both spellings are
        // matched; a literally typed `&gt;`/`&lt;` becomes `&amp;gt;`/`&amp;lt;`
        // and correctly falls through to an automatic placement, as in
        // Asciidoctor. An unrecognized position (including `content`, `auto`, or a
        // bogus value) is an automatic placement.
        match position {
            "left" | "<" | "&lt;" => Self::Left,
            "right" | ">" | "&gt;" => Self::Right,
            "top" | "^" => Self::Top,
            "bottom" | "v" => Self::Bottom,
            "preamble" => Self::Preamble,
            "macro" => Self::Macro,
            _ => Self::Auto,
        }
    }

    /// Returns `true` unless the `toc` attribute is unset (i.e. a table of
    /// contents is generated somewhere in the document).
    pub fn is_enabled(self) -> bool {
        self != Self::Disabled
    }

    /// Returns the value of the derived `toc-position` document attribute for
    /// this placement, or `None` when Asciidoctor leaves it unset (its `nil`
    /// default). The positional placements report their side (`left` / `right`
    /// / `top` / `bottom`); the content-flow placements (`preamble` /
    /// `macro`) report `content`; an automatic top TOC (and a disabled TOC)
    /// leave it unset.
    ///
    /// See [`Parser::materialize_toc_attributes`](crate::Parser).
    pub(crate) fn derived_toc_position(self) -> Option<&'static str> {
        match self {
            Self::Left => Some("left"),
            Self::Right => Some("right"),
            Self::Top => Some("top"),
            Self::Bottom => Some("bottom"),
            Self::Preamble | Self::Macro => Some("content"),
            Self::Auto | Self::Disabled => None,
        }
    }

    /// Returns the value of the derived `toc-placement` document attribute for
    /// this placement, or `None` when no TOC is generated. The automatic and
    /// side-column placements all fold to `auto`; `preamble` / `macro` report
    /// themselves. This is the placement keyword Asciidoctor exposes once the
    /// `toc` shorthand has been folded into `toc-placement`.
    pub(crate) fn derived_toc_placement(self) -> Option<&'static str> {
        match self {
            Self::Disabled => None,
            Self::Preamble => Some("preamble"),
            Self::Macro => Some("macro"),
            Self::Auto | Self::Left | Self::Right | Self::Top | Self::Bottom => Some("auto"),
        }
    }

    /// Returns the value the derived `toc-class` document attribute defaults to
    /// for this placement when the author has not set `toc-class`, or `None`
    /// when Asciidoctor leaves it unset (its `nil` default). Only a positional
    /// (`left` / `right` / `top` / `bottom`) TOC introduces a default (`toc2`,
    /// the side-column class).
    pub(crate) fn derived_toc_class(self) -> Option<&'static str> {
        match self {
            Self::Left | Self::Right | Self::Top | Self::Bottom => Some(DEFAULT_TOC_CLASS_SIDE),
            _ => None,
        }
    }
}

/// The depth of section levels included in a table of contents when the
/// `toclevels` attribute is not set. Matches Asciidoctor's default of 2
/// (sections up to and including `===`).
pub(crate) const DEFAULT_TOCLEVELS: usize = 2;

/// The title of the table of contents when the `toc-title` attribute is not
/// set. Matches Asciidoctor's default.
pub(crate) const DEFAULT_TOC_TITLE: &str = "Table of Contents";

/// The CSS class applied to the table of contents container when the
/// `toc-class` attribute is not set. Matches Asciidoctor's default.
pub(crate) const DEFAULT_TOC_CLASS: &str = "toc";

/// The CSS class applied to the table of contents container for a
/// `left`/`right` side-column TOC when the `toc-class` attribute is not set.
/// This is the class that drives the fixed side-column styling in Asciidoctor's
/// standalone HTML.
pub(crate) const DEFAULT_TOC_CLASS_SIDE: &str = "toc2";

/// The resolved table-of-contents configuration for a document (or a nested
/// AsciiDoc table cell, which resolves its own configuration independently).
///
/// Like [`TocMode`], the underlying attributes (`toc`, `toclevels`,
/// `toc-title`, `toc-class`) are header-only, so this value is captured once
/// the header has been processed and the parser still holds the document's
/// resolved attribute state.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub(crate) struct TocConfig {
    /// Where (and whether) the TOC is placed.
    pub(crate) mode: TocMode,

    /// The depth of section levels included in the TOC, from the `toclevels`
    /// attribute (default [`DEFAULT_TOCLEVELS`]).
    pub(crate) levels: usize,

    /// The TOC title, from the `toc-title` attribute (default
    /// [`DEFAULT_TOC_TITLE`]).
    pub(crate) title: String,

    /// The CSS class applied to the TOC container, from the `toc-class`
    /// attribute (default [`DEFAULT_TOC_CLASS`]).
    pub(crate) class: String,
}

impl TocConfig {
    /// Resolves the full table-of-contents configuration from a parser's
    /// current attribute state.
    pub(crate) fn from_parser(parser: &Parser) -> Self {
        let mode = TocMode::from_parser(parser);
        Self {
            mode,
            levels: resolve_levels(parser),
            title: resolve_title(parser),
            class: resolve_class(parser, mode),
        }
    }

    /// Returns a configuration with no table of contents, used as the default
    /// for a structure that has not enabled a TOC.
    #[cfg(test)]
    pub(crate) fn disabled() -> Self {
        Self {
            mode: TocMode::Disabled,
            levels: DEFAULT_TOCLEVELS,
            title: DEFAULT_TOC_TITLE.to_string(),
            class: DEFAULT_TOC_CLASS.to_string(),
        }
    }
}

/// Resolves the `toclevels` depth. Accepted values are the integers 0 through
/// 5: the value `0` is coerced to `1` (this crate has no multipart-book parts,
/// so level 0 sections never appear) and values above `5` are clamped to `5`,
/// matching the documented range. Any unparseable value falls back to the
/// default of 2.
fn resolve_levels(parser: &Parser) -> usize {
    parser
        .attribute_value("toclevels")
        .as_maybe_str()
        .and_then(|s| s.trim().parse::<usize>().ok())
        .map(|n| n.clamp(1, 5))
        .unwrap_or(DEFAULT_TOCLEVELS)
}

/// Resolves the `toc-title`. An empty `:toc-title:` (set but with no value)
/// yields an empty title, matching Asciidoctor; an unset attribute falls back
/// to the default.
fn resolve_title(parser: &Parser) -> String {
    match parser.attribute_value("toc-title") {
        InterpretedValue::Value(v) => v,
        InterpretedValue::Set => String::new(),
        InterpretedValue::Unset => DEFAULT_TOC_TITLE.to_string(),
    }
}

/// Resolves the `toc-class`. An explicit, non-empty `toc-class` wins outright.
/// Otherwise the default depends on placement: a positional (`left`/`right`/
/// `top`/`bottom`) TOC uses `toc2` (the class that drives the side-column
/// styling), matching Asciidoctor, which switches the default `toc-class` to
/// `toc2` for those placements; every other placement uses the plain `toc`.
fn resolve_class(parser: &Parser, mode: TocMode) -> String {
    match parser.attribute_value("toc-class") {
        InterpretedValue::Value(v) if !v.trim().is_empty() => v,
        _ => default_toc_class(mode).to_string(),
    }
}

/// Returns the default `toc-class` for a resolved placement: `toc2` for a
/// positional (`left`/`right`/`top`/`bottom`) TOC, and the plain `toc` for
/// every other placement.
fn default_toc_class(mode: TocMode) -> &'static str {
    match mode {
        TocMode::Left | TocMode::Right | TocMode::Top | TocMode::Bottom => DEFAULT_TOC_CLASS_SIDE,
        _ => DEFAULT_TOC_CLASS,
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        Parser,
        document::{InterpretedValue, TocMode},
    };

    /// Parses a minimal document with the given header attribute lines and
    /// returns the parsed [`Document`](crate::Document) for inspection.
    fn doc_with(header: &str) -> crate::Document<'static> {
        let src = format!("= Title\n{header}\n\n== Section\n\ncontent");
        Parser::default().parse(&src)
    }

    #[test]
    fn mode_is_disabled_when_unset() {
        assert_eq!(doc_with("").toc_mode(), TocMode::Disabled);
        assert!(!TocMode::Disabled.is_enabled());
    }

    #[test]
    fn mode_resolves_each_placement() {
        assert_eq!(doc_with(":toc:").toc_mode(), TocMode::Auto);
        assert_eq!(doc_with(":toc: auto").toc_mode(), TocMode::Auto);
        assert_eq!(doc_with(":toc: left").toc_mode(), TocMode::Left);
        assert_eq!(doc_with(":toc: right").toc_mode(), TocMode::Right);
        assert_eq!(doc_with(":toc: preamble").toc_mode(), TocMode::Preamble);
        assert_eq!(doc_with(":toc: macro").toc_mode(), TocMode::Macro);

        for mode in [
            TocMode::Auto,
            TocMode::Left,
            TocMode::Right,
            TocMode::Preamble,
            TocMode::Macro,
        ] {
            assert!(mode.is_enabled());
        }
    }

    #[test]
    fn unrecognized_mode_is_treated_as_auto() {
        assert_eq!(doc_with(":toc: bogus").toc_mode(), TocMode::Auto);
    }

    #[test]
    fn mode_resolves_direction_shorthands_and_keywords() {
        // The `<`/`>`/`^`/`v` direction shorthands in the `toc` value resolve to
        // the `left`/`right`/`top`/`bottom` positions, matching Asciidoctor. (The
        // `<`/`>` shorthands reach resolution already special-character
        // substituted to `&lt;`/`&gt;`, but resolve the same.)
        assert_eq!(doc_with(":toc: <").toc_mode(), TocMode::Left);
        assert_eq!(doc_with(":toc: >").toc_mode(), TocMode::Right);
        assert_eq!(doc_with(":toc: ^").toc_mode(), TocMode::Top);
        assert_eq!(doc_with(":toc: v").toc_mode(), TocMode::Bottom);

        // The `top`/`bottom` keywords resolve likewise.
        assert_eq!(doc_with(":toc: top").toc_mode(), TocMode::Top);
        assert_eq!(doc_with(":toc: bottom").toc_mode(), TocMode::Bottom);

        // A literally typed `&gt;`/`&lt;` entity is not a shorthand (it is
        // special-character substituted to `&amp;gt;`/`&amp;lt;`), so it falls
        // back to an automatic placement, as in Asciidoctor's header handling.
        assert_eq!(doc_with(":toc: &gt;").toc_mode(), TocMode::Auto);
        assert_eq!(doc_with(":toc: &lt;").toc_mode(), TocMode::Auto);
    }

    #[test]
    fn toc_position_attribute_selects_the_side() {
        // The separate `toc-position` attribute selects the side of an otherwise
        // automatic TOC. It also overrides the `left` implied by the legacy `toc2`
        // alias, and a bare side keyword in the `toc` value.
        assert_eq!(
            doc_with(":toc:\n:toc-position: right").toc_mode(),
            TocMode::Right
        );
        assert_eq!(
            doc_with(":toc2:\n:toc-position: right").toc_mode(),
            TocMode::Right
        );
        assert_eq!(
            doc_with(":toc: left\n:toc-position: right").toc_mode(),
            TocMode::Right
        );
        assert_eq!(doc_with(":toc:\n:toc-position: ^").toc_mode(), TocMode::Top);
    }

    #[test]
    fn toc_placement_side_resolves_the_position() {
        // `toc-placement` is resolved into the position ahead of the `toc` value,
        // so a `preamble`/`macro` placement (or a side keyword on `toc-placement`)
        // wins over a conflicting keyword in the `toc` value.
        assert_eq!(
            doc_with(":toc: left\n:toc-placement: macro").toc_mode(),
            TocMode::Macro
        );
        assert_eq!(
            doc_with(":toc:\n:toc-placement: right").toc_mode(),
            TocMode::Right
        );

        // A `toc-position` (consulted when `toc-placement` is `auto`) likewise
        // wins over a `preamble` keyword in the `toc` value.
        assert_eq!(
            doc_with(":toc: preamble\n:toc-position: right").toc_mode(),
            TocMode::Right
        );

        // A bare `:toc-placement:` (set with no value) supplies an empty position,
        // so an otherwise-bare `:toc:` stays an automatic top TOC.
        assert_eq!(doc_with(":toc:\n:toc-placement:").toc_mode(), TocMode::Auto);
    }

    #[test]
    fn toc2_alias_enables_a_left_placed_toc() {
        // `toc2` is a legacy alias for `:toc: left`: setting the bare attribute
        // enables a left-positioned table of contents even though the `toc`
        // attribute itself is unset.
        assert_eq!(doc_with(":toc2:").toc_mode(), TocMode::Left);
        assert!(doc_with(":toc2:").toc_mode().is_enabled());

        // Its side-column placement also switches the default `toc-class` to
        // `toc2`, like any other `left`/`right` TOC.
        assert_eq!(doc_with(":toc2:").toc_class(), "toc2");

        // A soft-unset `toc2!` does not enable the TOC.
        assert_eq!(doc_with(":toc2!:").toc_mode(), TocMode::Disabled);
    }

    #[test]
    fn placement_falls_back_to_toc_placement_attribute() {
        // When the `toc` value carries no placement keyword, the separate
        // `toc-placement` attribute determines the placement.
        assert_eq!(
            doc_with(":toc:\n:toc-placement: preamble").toc_mode(),
            TocMode::Preamble
        );
        assert_eq!(
            doc_with(":toc:\n:toc-placement: macro").toc_mode(),
            TocMode::Macro
        );
        assert_eq!(
            doc_with(":toc: auto\n:toc-placement: preamble").toc_mode(),
            TocMode::Preamble
        );

        // A non-`auto` `toc-placement` supplies the position and wins over the
        // `toc` value's own keyword (Asciidoctor resolves `toc-placement` into the
        // position before consulting the `toc` value), so `toc-placement:
        // preamble` overrides `toc: macro`.
        assert_eq!(
            doc_with(":toc: macro\n:toc-placement: preamble").toc_mode(),
            TocMode::Preamble
        );

        // A bogus `toc-placement` falls back to an automatic placement.
        assert_eq!(
            doc_with(":toc:\n:toc-placement: bogus").toc_mode(),
            TocMode::Auto
        );
    }

    #[test]
    fn soft_unset_toc_placement_resolves_to_macro() {
        // With `toc` enabled, explicitly unsetting `toc-placement` defers the
        // TOC to a `toc::[]` block macro (Asciidoctor's `macro` fetch fallback),
        // whereas a `toc-placement` that was never set stays automatic.
        assert_eq!(doc_with(":toc:").toc_mode(), TocMode::Auto);
        assert_eq!(
            doc_with(":toc:\n:toc-placement!:").toc_mode(),
            TocMode::Macro
        );
        assert_eq!(
            doc_with(":toc:\n:!toc-placement:").toc_mode(),
            TocMode::Macro
        );

        // A soft-unset `toc-placement` resolves to `macro` even when the `toc`
        // value names a different placement keyword: Asciidoctor deletes the
        // attribute, so its `fetch` yields the `macro` fallback, which supplies
        // the position and overrides `toc: preamble`.
        assert_eq!(
            doc_with(":toc: preamble\n:toc-placement!:").toc_mode(),
            TocMode::Macro
        );
    }

    #[test]
    fn levels_default_and_overrides() {
        assert_eq!(doc_with(":toc:").toc_levels(), 2);
        assert_eq!(doc_with(":toc:\n:toclevels: 5").toc_levels(), 5);

        // `0` is coerced to `1`, values above `5` are clamped to `5`, and an
        // unparseable value falls back to the default.
        assert_eq!(doc_with(":toc:\n:toclevels: 0").toc_levels(), 1);
        assert_eq!(doc_with(":toc:\n:toclevels: 6").toc_levels(), 5);
        assert_eq!(doc_with(":toc:\n:toclevels: nope").toc_levels(), 2);
    }

    #[test]
    fn title_default_value_and_empty() {
        assert_eq!(doc_with(":toc:").toc_title(), "Table of Contents");
        assert_eq!(doc_with(":toc:\n:toc-title: My TOC").toc_title(), "My TOC");

        // A `:toc-title:` set with no value yields an empty title.
        assert_eq!(doc_with(":toc:\n:toc-title:").toc_title(), "");

        // An explicitly unset `:toc-title!:` falls back to the built-in default.
        assert_eq!(
            doc_with(":toc:\n:toc-title!:").toc_title(),
            "Table of Contents"
        );
    }

    #[test]
    fn class_default_value_and_empty() {
        assert_eq!(doc_with(":toc:").toc_class(), "toc");
        assert_eq!(doc_with(":toc:\n:toc-class: floaty").toc_class(), "floaty");

        // An empty `:toc-class:` falls back to the default.
        assert_eq!(doc_with(":toc:\n:toc-class:").toc_class(), "toc");
    }

    #[test]
    fn class_defaults_to_toc2_for_side_column_placement() {
        // A `left`/`right` side-column TOC switches the default class to `toc2`,
        // matching Asciidoctor; every other placement keeps the plain `toc`.
        assert_eq!(doc_with(":toc: left").toc_class(), "toc2");
        assert_eq!(doc_with(":toc: right").toc_class(), "toc2");
        assert_eq!(doc_with(":toc:\n:toc-placement: left").toc_class(), "toc2");
        assert_eq!(doc_with(":toc:\n:toc-placement: right").toc_class(), "toc2");
        assert_eq!(doc_with(":toc: preamble").toc_class(), "toc");
        assert_eq!(doc_with(":toc: macro").toc_class(), "toc");

        // An explicit `toc-class` still wins over the side-column default.
        assert_eq!(
            doc_with(":toc: left\n:toc-class: floaty").toc_class(),
            "floaty"
        );

        // An explicit but empty `:toc-class:` resolves to the built-in `toc-class`
        // default (`toc`) at the attribute layer, so the placement-derived `toc2`
        // default only applies when `toc-class` is left entirely unset.
        assert_eq!(doc_with(":toc: left\n:toc-class:").toc_class(), "toc");
    }

    /// The derived `toc-position` / `toc-placement` / `toc-class` attributes
    /// are materialized so they are queryable via
    /// `Document::attribute_value`, matching Asciidoctor (see the `verify
    /// toc attribute matrix` upstream test).
    #[test]
    fn derived_attributes_are_materialized() {
        use InterpretedValue::{Unset, Value};

        // Reads the derived (`toc-position`, `toc-placement`, `toc-class`)
        // document attributes as a `(position, placement, class)` triple.
        let derived = |header: &str| {
            let doc = doc_with(header);
            (
                doc.attribute_value("toc-position"),
                doc.attribute_value("toc-placement"),
                doc.attribute_value("toc-class"),
            )
        };

        // An automatic top TOC: position and class stay unset, placement `auto`.
        assert_eq!(derived(":toc:"), (Unset, Value("auto".into()), Unset));

        // An unrecognized `toc` value still resolves to an automatic placement.
        assert_eq!(
            derived(":toc: beeboo"),
            (Unset, Value("auto".into()), Unset)
        );

        // Side-column placements derive their side, keep placement `auto`, and
        // default the class to `toc2`.
        assert_eq!(
            derived(":toc: left"),
            (
                Value("left".into()),
                Value("auto".into()),
                Value("toc2".into())
            )
        );
        assert_eq!(
            derived(":toc: right"),
            (
                Value("right".into()),
                Value("auto".into()),
                Value("toc2".into())
            )
        );

        // The legacy `toc2` alias behaves like `toc=left`.
        assert_eq!(
            derived(":toc2:"),
            (
                Value("left".into()),
                Value("auto".into()),
                Value("toc2".into())
            )
        );

        // Content-flow placements report `content` and leave the class unset.
        assert_eq!(
            derived(":toc: preamble"),
            (Value("content".into()), Value("preamble".into()), Unset)
        );
        assert_eq!(
            derived(":toc: macro"),
            (Value("content".into()), Value("macro".into()), Unset)
        );
    }

    #[test]
    fn derived_placement_overwrites_author_supplied_values() {
        use InterpretedValue::Value;

        // A `toc-position` the resolved placement contradicts is overwritten:
        // the `macro` placement forces `content`.
        let doc = doc_with(":toc:\n:toc-placement: macro\n:toc-position: left");
        assert_eq!(doc.attribute_value("toc-position"), Value("content".into()));
        assert_eq!(doc.attribute_value("toc-placement"), Value("macro".into()));

        // A soft-unset `toc-placement!` with `toc` set defers to a `toc::[]`
        // macro; the derived `toc-placement` is re-materialized as `macro`,
        // overwriting the unset tombstone.
        let doc = doc_with(":toc:\n:toc-placement!:");
        assert_eq!(doc.attribute_value("toc-position"), Value("content".into()));
        assert_eq!(doc.attribute_value("toc-placement"), Value("macro".into()));
    }

    /// The derived `toc-position` / `toc-placement` / `toc-class` attributes
    /// for the direction shorthands, the separate `toc-position` attribute,
    /// and the `toc2` + `toc-position` override – all of which resolve a
    /// side-column TOC (`toc2` class) in Asciidoctor.
    #[test]
    fn toc_position_normalization_derives_side_column() {
        use InterpretedValue::Value;

        let derived = |header: &str| {
            let doc = doc_with(header);
            (
                doc.attribute_value("toc-position"),
                doc.attribute_value("toc-placement"),
                doc.attribute_value("toc-class"),
            )
        };
        let right = || {
            (
                Value("right".into()),
                Value("auto".into()),
                Value("toc2".into()),
            )
        };

        // A `>` direction shorthand derives a right side-column TOC.
        assert_eq!(derived(":toc: >"), right());

        // `:toc:` + `:toc-position: right` derives a right side column and defaults
        // the class to `toc2` (was previously left as the plain `toc`).
        assert_eq!(derived(":toc:\n:toc-position: right"), right());

        // `:toc2:` + `:toc-position: right`: the explicit `toc-position` overrides
        // the `left` implied by the `toc2` alias (was previously left).
        assert_eq!(derived(":toc2:\n:toc-position: right"), right());

        // The `^` shorthand derives a top column, likewise defaulting to `toc2`.
        assert_eq!(
            derived(":toc: ^"),
            (
                Value("top".into()),
                Value("auto".into()),
                Value("toc2".into())
            )
        );
    }

    #[test]
    fn automatic_toc_clears_unrecognized_toc_position() {
        // An enabled automatic TOC drops an author `toc-position` that resolves to
        // no side: Asciidoctor's normalization deletes it in its `else` arm, so a
        // bogus (or `content`) value does not leak into the derived state.
        let doc = doc_with(":toc:\n:toc-position: bogus");
        assert_eq!(doc.toc_mode(), TocMode::Auto);
        assert!(!doc.has_attribute("toc-position"));

        let doc = doc_with(":toc:\n:toc-position: content");
        assert_eq!(doc.toc_mode(), TocMode::Auto);
        assert!(!doc.has_attribute("toc-position"));
    }

    #[test]
    fn explicit_toc_class_survives_side_column_default() {
        // The side-column `toc2` default only fills in an *unset* `toc-class`;
        // an explicit author value is left untouched.
        assert_eq!(
            doc_with(":toc: left\n:toc-class: floaty").attribute_value("toc-class"),
            InterpretedValue::Value("floaty".into())
        );
    }

    #[test]
    fn derived_attributes_do_not_leak_across_parses() {
        // The derived attributes live on each document's snapshot, not on the
        // parser, so reusing a parser must not carry one document's TOC state
        // into the next.
        let mut parser = Parser::default();

        // A first document with a `macro` placement materializes its derived
        // attributes on its own snapshot.
        let doc1 = parser.parse("= One\n:toc: macro\n\n== S\n\nx");
        assert_eq!(doc1.toc_mode(), TocMode::Macro);
        assert_eq!(
            doc1.attribute_value("toc-placement"),
            InterpretedValue::Value("macro".into())
        );

        // A second document that enables an automatic TOC must resolve `Auto` –
        // if the first document's derived `toc-placement: macro` had leaked onto
        // the parser, `TocMode::from_parser` would read it back and wrongly
        // resolve `Macro` here.
        let doc2 = parser.parse("= Two\n:toc:\n\n== S\n\nx");
        assert_eq!(doc2.toc_mode(), TocMode::Auto);
        assert_eq!(
            doc2.attribute_value("toc-placement"),
            InterpretedValue::Value("auto".into())
        );

        // The first document's derived `toc-position` (`content`) likewise does
        // not linger: an automatic TOC leaves it unset.
        assert!(!doc2.has_attribute("toc-position"));
    }

    #[test]
    fn disabled_toc_materializes_no_derived_attributes() {
        // With no TOC enabled, the whole family stays unset (Asciidoctor's
        // defaults), so none of the attributes is even present.
        let doc = doc_with("");
        for name in ["toc-position", "toc-placement", "toc-class"] {
            assert!(!doc.has_attribute(name), "{name} should be absent");
        }
    }

    /// Exercises the derived-attribute mapping directly for every [`TocMode`]
    /// variant, including [`TocMode::Disabled`] – which the parse path never
    /// feeds to these helpers (materialization returns early for it), but whose
    /// arms must still map to "no attribute".
    #[test]
    fn derived_attribute_mapping_covers_every_mode() {
        for (mode, position, placement, class) in [
            (TocMode::Disabled, None, None, None),
            (TocMode::Auto, None, Some("auto"), None),
            (TocMode::Left, Some("left"), Some("auto"), Some("toc2")),
            (TocMode::Right, Some("right"), Some("auto"), Some("toc2")),
            (TocMode::Top, Some("top"), Some("auto"), Some("toc2")),
            (TocMode::Bottom, Some("bottom"), Some("auto"), Some("toc2")),
            (TocMode::Preamble, Some("content"), Some("preamble"), None),
            (TocMode::Macro, Some("content"), Some("macro"), None),
        ] {
            assert_eq!(
                mode.derived_toc_position(),
                position,
                "position for {mode:?}"
            );
            assert_eq!(
                mode.derived_toc_placement(),
                placement,
                "placement for {mode:?}"
            );
            assert_eq!(mode.derived_toc_class(), class, "class for {mode:?}");
        }
    }
}