acdc-parser 0.8.0

`AsciiDoc` parser using PEG grammars
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
//! Substitution types and application for `AsciiDoc` content.
//!
//! # Architecture: Parser vs Converter Responsibilities
//!
//! Substitutions are split between the parser and converters by design:
//!
//! ## Parser handles (format-agnostic)
//!
//! - **Attributes** - Expands `{name}` references using document attributes.
//!   This is document-wide and doesn't depend on output format.
//!
//! - **Group expansion** - `Normal` and `Verbatim` expand to their constituent
//!   substitution lists recursively.
//!
//! ## Converters handle (format-specific)
//!
//! - **`SpecialChars`** - HTML converter escapes `<`, `>`, `&` to entities.
//!   Other converters may handle differently (e.g., terminal needs no escaping).
//!
//! - **Quotes** - Parses inline formatting (`*bold*`, `_italic_`, etc.) via
//!   [`crate::parse_text_for_quotes`]. The converter then renders the parsed
//!   nodes appropriately for the output format.
//!
//! - **Replacements** - Typography transformations (em-dashes, arrows, ellipsis).
//!   Output varies by format (HTML entities vs Unicode characters).
//!
//! - **Callouts** - Already parsed into [`crate::CalloutRef`] nodes by the grammar.
//!   Converters render the callout markers.
//!
//! - **Macros** - Handled at the grammar level: when macros are disabled via `subs`,
//!   macro grammar rules are gated by a predicate and macro-like text becomes plain text.
//!
//! - **`PostReplacements`** - Not yet implemented.
//!
//! ## Why this split?
//!
//! The parser stays format-agnostic. It extracts the substitution list from
//! `[subs=...]` attributes and stores it in the AST. Each converter then
//! applies the relevant substitutions for its output format. This allows
//! adding new converters (terminal, manpage, PDF) without modifying the parser.
//!
//! ## Usage flow
//!
//! 1. Parser extracts `subs=` attribute → stored in [`crate::BlockMetadata`]
//! 2. Parser applies `Attributes` substitution during parsing
//! 3. Converter reads the substitution list from AST
//! 4. Converter applies remaining substitutions during rendering

use serde::Serialize;

use crate::{AttributeValue, DocumentAttributes};

/// A `Substitution` represents a substitution in a passthrough macro.
#[derive(Clone, Debug, Hash, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Substitution {
    SpecialChars,
    Attributes,
    Replacements,
    Macros,
    PostReplacements,
    Normal,
    Verbatim,
    Quotes,
    Callouts,
}

impl std::fmt::Display for Substitution {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let name = match self {
            Self::SpecialChars => "special_chars",
            Self::Attributes => "attributes",
            Self::Replacements => "replacements",
            Self::Macros => "macros",
            Self::PostReplacements => "post_replacements",
            Self::Normal => "normal",
            Self::Verbatim => "verbatim",
            Self::Quotes => "quotes",
            Self::Callouts => "callouts",
        };
        write!(f, "{name}")
    }
}

/// Parse a substitution name into a `Substitution` enum variant.
///
/// Returns `None` for unknown substitution types, which are logged and skipped.
pub(crate) fn parse_substitution(value: &str) -> Option<Substitution> {
    match value {
        "attributes" | "a" => Some(Substitution::Attributes),
        "replacements" | "r" => Some(Substitution::Replacements),
        "macros" | "m" => Some(Substitution::Macros),
        "post_replacements" | "p" => Some(Substitution::PostReplacements),
        "normal" | "n" => Some(Substitution::Normal),
        "verbatim" | "v" => Some(Substitution::Verbatim),
        "quotes" | "q" => Some(Substitution::Quotes),
        "callouts" => Some(Substitution::Callouts),
        "specialchars" | "specialcharacters" | "c" => Some(Substitution::SpecialChars),
        unknown => {
            tracing::error!(
                substitution = %unknown,
                "unknown substitution type, ignoring - check for typos"
            );
            None
        }
    }
}

/// Default substitutions for header content.
pub const HEADER: &[Substitution] = &[Substitution::SpecialChars, Substitution::Attributes];

/// Default substitutions for normal content (paragraphs, etc).
pub const NORMAL: &[Substitution] = &[
    Substitution::SpecialChars,
    Substitution::Attributes,
    Substitution::Quotes,
    Substitution::Replacements,
    Substitution::Macros,
    Substitution::PostReplacements,
];

/// Default substitutions for verbatim blocks (listing, literal).
pub const VERBATIM: &[Substitution] = &[Substitution::SpecialChars, Substitution::Callouts];

/// A substitution operation to apply to a default substitution list.
///
/// Used when the `subs` attribute contains modifier syntax (`+quotes`, `-callouts`, `quotes+`).
#[derive(Clone, Debug, Hash, Eq, PartialEq)]
pub enum SubstitutionOp {
    /// `+name` - append substitution to end of default list
    Append(Substitution),
    /// `name+` - prepend substitution to beginning of default list
    Prepend(Substitution),
    /// `-name` - remove substitution from default list
    Remove(Substitution),
}

impl std::fmt::Display for SubstitutionOp {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Append(sub) => write!(f, "+{sub}"),
            Self::Prepend(sub) => write!(f, "{sub}+"),
            Self::Remove(sub) => write!(f, "-{sub}"),
        }
    }
}

/// Specification for substitutions to apply to a block.
///
/// This type represents how substitutions are specified in a `subs` attribute:
///
/// - **Explicit**: A direct list of substitutions (e.g., `subs=specialchars,quotes`)
/// - **Modifiers**: Operations to apply to the block-type default substitutions
///   (e.g., `subs=+quotes,-callouts`)
///
/// The parser cannot know the block type when parsing attributes (metadata comes before
/// the block delimiter), so modifier operations are stored and the converter applies
/// them with the appropriate baseline (VERBATIM for listing/literal, NORMAL for paragraphs).
///
/// ## Serialization
///
/// Serializes to a flat array of strings matching document syntax:
/// - Explicit: `["special_chars", "quotes"]`
/// - Modifiers: `["+quotes", "-callouts", "macros+"]`
#[derive(Clone, Debug, Hash, Eq, PartialEq)]
pub enum SubstitutionSpec {
    /// Explicit list of substitutions to apply (replaces all defaults)
    Explicit(Vec<Substitution>),
    /// Modifier operations to apply to block-type defaults
    Modifiers(Vec<SubstitutionOp>),
}

impl Serialize for SubstitutionSpec {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let strings: Vec<String> = match self {
            Self::Explicit(subs) => subs.iter().map(ToString::to_string).collect(),
            Self::Modifiers(ops) => ops.iter().map(ToString::to_string).collect(),
        };
        strings.serialize(serializer)
    }
}

impl SubstitutionSpec {
    /// Apply modifier operations to a default substitution list.
    ///
    /// This is used by converters to resolve modifiers with the appropriate baseline.
    #[must_use]
    pub fn apply_modifiers(ops: &[SubstitutionOp], default: &[Substitution]) -> Vec<Substitution> {
        let mut result = default.to_vec();
        for op in ops {
            match op {
                SubstitutionOp::Append(sub) => append_substitution(&mut result, sub),
                SubstitutionOp::Prepend(sub) => prepend_substitution(&mut result, sub),
                SubstitutionOp::Remove(sub) => remove_substitution(&mut result, sub),
            }
        }
        result
    }

    /// Check if macros are disabled by this spec.
    /// - Explicit list without Macros → disabled
    /// - Modifiers with Remove(Macros) → disabled
    #[must_use]
    pub fn macros_disabled(&self) -> bool {
        match self {
            Self::Explicit(subs) => !subs.contains(&Substitution::Macros),
            Self::Modifiers(ops) => ops
                .iter()
                .any(|op| matches!(op, SubstitutionOp::Remove(Substitution::Macros))),
        }
    }

    /// Check if attribute substitution is disabled by this spec.
    /// - Explicit list without Attributes → disabled
    /// - Modifiers with Remove(Attributes) → disabled
    #[must_use]
    pub fn attributes_disabled(&self) -> bool {
        match self {
            Self::Explicit(subs) => !subs.contains(&Substitution::Attributes),
            Self::Modifiers(ops) => ops
                .iter()
                .any(|op| matches!(op, SubstitutionOp::Remove(Substitution::Attributes))),
        }
    }

    /// Resolve the substitution spec to a concrete list of substitutions.
    ///
    /// - For `Explicit`, returns the list directly
    /// - For `Modifiers`, applies the operations to the provided default
    #[must_use]
    pub fn resolve(&self, default: &[Substitution]) -> Vec<Substitution> {
        match self {
            SubstitutionSpec::Explicit(subs) => subs.clone(),
            SubstitutionSpec::Modifiers(ops) => Self::apply_modifiers(ops, default),
        }
    }
}

/// Modifier for a substitution in the `subs` attribute (internal parsing helper).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum SubsModifier {
    /// `+name` - append to end of default list
    Append,
    /// `name+` - prepend to beginning of default list
    Prepend,
    /// `-name` - remove from default list
    Remove,
}

/// Parse a single subs part into name and optional modifier.
fn parse_subs_part(part: &str) -> (&str, Option<SubsModifier>) {
    if let Some(name) = part.strip_prefix('+') {
        (name, Some(SubsModifier::Append))
    } else if let Some(name) = part.strip_suffix('+') {
        (name, Some(SubsModifier::Prepend))
    } else if let Some(name) = part.strip_prefix('-') {
        (name, Some(SubsModifier::Remove))
    } else {
        (part, None)
    }
}

/// Parse a `subs` attribute value into a substitution specification.
///
/// Returns either:
/// - `SubstitutionSpec::Explicit` for explicit lists (e.g., `subs=specialchars,quotes`)
/// - `SubstitutionSpec::Modifiers` for modifier syntax (e.g., `subs=+quotes,-callouts`)
///
/// Supports:
/// - `none` → Explicit empty list (no substitutions)
/// - `normal` → Explicit NORMAL list
/// - `verbatim` → Explicit VERBATIM list
/// - `a,q,c` → Explicit specific substitutions (comma-separated)
/// - `+quotes` → Modifiers: append to end of default list
/// - `quotes+` → Modifiers: prepend to beginning of default list
/// - `-specialchars` → Modifiers: remove from default list
/// - `specialchars,+quotes` → Modifiers: mixed modifier mode
///
/// Order matters: substitutions/modifiers are applied in sequence.
#[must_use]
pub(crate) fn parse_subs_attribute(value: &str) -> SubstitutionSpec {
    let value = value.trim();

    // Handle special cases
    if value.is_empty() || value == "none" {
        return SubstitutionSpec::Explicit(Vec::new());
    }

    // Parse all parts in one pass: O(n)
    let parts: Vec<_> = value
        .split(',')
        .map(str::trim)
        .filter(|p| !p.is_empty())
        .map(parse_subs_part)
        .collect();

    // Determine mode: if ANY part has a modifier, use modifier mode
    let has_modifiers = parts.iter().any(|(_, m)| m.is_some());

    if has_modifiers {
        // Modifier mode: collect operations for converter to apply
        let mut ops = Vec::new();

        for (name, modifier) in parts {
            // Parse the substitution name; skip if invalid
            let Some(sub) = parse_substitution(name) else {
                continue;
            };

            match modifier {
                Some(SubsModifier::Append) => {
                    ops.push(SubstitutionOp::Append(sub));
                }
                Some(SubsModifier::Prepend) => {
                    ops.push(SubstitutionOp::Prepend(sub));
                }
                Some(SubsModifier::Remove) => {
                    ops.push(SubstitutionOp::Remove(sub));
                }
                None => {
                    // Plain substitution name in modifier context - warn and treat as append
                    tracing::warn!(
                        substitution = %name,
                        "plain substitution in modifier context; consider +{name} for clarity"
                    );
                    ops.push(SubstitutionOp::Append(sub));
                }
            }
        }
        SubstitutionSpec::Modifiers(ops)
    } else {
        // No modifiers - parse as an explicit list of substitution names (in order)
        let mut result = Vec::new();
        for (name, _) in parts {
            if let Some(ref sub) = parse_substitution(name) {
                append_substitution(&mut result, sub);
            }
        }
        SubstitutionSpec::Explicit(result)
    }
}

/// Expand a substitution to its constituent list.
///
/// Groups (`Normal`, `Verbatim`) expand to their members; individual subs return themselves.
fn expand_substitution(sub: &Substitution) -> &[Substitution] {
    match sub {
        Substitution::Normal => NORMAL,
        Substitution::Verbatim => VERBATIM,
        Substitution::SpecialChars
        | Substitution::Attributes
        | Substitution::Replacements
        | Substitution::Macros
        | Substitution::PostReplacements
        | Substitution::Quotes
        | Substitution::Callouts => std::slice::from_ref(sub),
    }
}

/// Append a substitution (or group) to the end of the list.
pub(crate) fn append_substitution(result: &mut Vec<Substitution>, sub: &Substitution) {
    for s in expand_substitution(sub) {
        if !result.contains(s) {
            result.push(s.clone());
        }
    }
}

/// Prepend a substitution (or group) to the beginning of the list.
pub(crate) fn prepend_substitution(result: &mut Vec<Substitution>, sub: &Substitution) {
    // Insert in reverse order at position 0 to maintain group order
    for s in expand_substitution(sub).iter().rev() {
        if !result.contains(s) {
            result.insert(0, s.clone());
        }
    }
}

/// Remove a substitution (or group) from the list.
pub(crate) fn remove_substitution(result: &mut Vec<Substitution>, sub: &Substitution) {
    for s in expand_substitution(sub) {
        result.retain(|x| x != s);
    }
}

/// Apply a sequence of substitutions to text.
///
/// Iterates through the substitution list and applies each in order:
///
/// - `Attributes` - Expands `{name}` references using document attributes
/// - `Normal` / `Verbatim` - Recursively applies the corresponding substitution group
/// - All others (`SpecialChars`, `Quotes`, `Replacements`, `Macros`,
///   `PostReplacements`, `Callouts`) - No-op; handled by converters
///
/// # Example
///
/// ```
/// use acdc_parser::{DocumentAttributes, AttributeValue, Substitution, substitute};
///
/// let mut attrs = DocumentAttributes::default();
/// attrs.set("version".to_string(), AttributeValue::String("1.0".to_string()));
///
/// let result = substitute("Version {version}", &[Substitution::Attributes], &attrs);
/// assert_eq!(result, "Version 1.0");
/// ```
#[must_use]
pub fn substitute(
    text: &str,
    substitutions: &[Substitution],
    attributes: &DocumentAttributes,
) -> String {
    let mut result = text.to_string();
    for substitution in substitutions {
        match substitution {
            Substitution::Attributes => {
                // Expand {name} patterns with values from document attributes
                let mut expanded = String::with_capacity(result.len());
                let mut chars = result.chars().peekable();

                while let Some(ch) = chars.next() {
                    if ch == '{' {
                        let mut attr_name = String::new();
                        let mut found_closing_brace = false;

                        while let Some(&next_ch) = chars.peek() {
                            if next_ch == '}' {
                                chars.next();
                                found_closing_brace = true;
                                break;
                            }
                            attr_name.push(next_ch);
                            chars.next();
                        }

                        if found_closing_brace {
                            match attributes.get(&attr_name) {
                                Some(AttributeValue::Bool(true)) => {
                                    // Boolean true attributes expand to empty string
                                }
                                Some(AttributeValue::String(attr_value)) => {
                                    expanded.push_str(attr_value);
                                }
                                _ => {
                                    // Unknown attribute - keep reference as-is
                                    expanded.push('{');
                                    expanded.push_str(&attr_name);
                                    expanded.push('}');
                                }
                            }
                        } else {
                            // No closing brace - keep opening brace and collected chars
                            expanded.push('{');
                            expanded.push_str(&attr_name);
                        }
                    } else {
                        expanded.push(ch);
                    }
                }
                result = expanded;
            }
            // These substitutions are handled elsewhere (converter) or not yet implemented
            Substitution::SpecialChars
            | Substitution::Quotes
            | Substitution::Replacements
            | Substitution::Macros
            | Substitution::PostReplacements
            | Substitution::Callouts => {}
            // Group substitutions expand recursively
            Substitution::Normal => {
                result = substitute(&result, NORMAL, attributes);
            }
            Substitution::Verbatim => {
                result = substitute(&result, VERBATIM, attributes);
            }
        }
    }
    result
}

#[cfg(test)]
mod tests {
    use super::*;

    // Helper to extract explicit list from SubstitutionSpec
    #[allow(clippy::panic)]
    fn explicit(spec: &SubstitutionSpec) -> &Vec<Substitution> {
        match spec {
            SubstitutionSpec::Explicit(subs) => subs,
            SubstitutionSpec::Modifiers(_) => panic!("Expected Explicit, got Modifiers"),
        }
    }

    // Helper to extract modifiers from SubstitutionSpec
    #[allow(clippy::panic)]
    fn modifiers(spec: &SubstitutionSpec) -> &Vec<SubstitutionOp> {
        match spec {
            SubstitutionSpec::Modifiers(ops) => ops,
            SubstitutionSpec::Explicit(_) => panic!("Expected Modifiers, got Explicit"),
        }
    }

    #[test]
    fn test_parse_subs_none() {
        let result = parse_subs_attribute("none");
        assert!(explicit(&result).is_empty());
    }

    #[test]
    fn test_parse_subs_empty_string() {
        let result = parse_subs_attribute("");
        assert!(explicit(&result).is_empty());
    }

    #[test]
    fn test_parse_subs_none_with_whitespace() {
        let result = parse_subs_attribute("  none  ");
        assert!(explicit(&result).is_empty());
    }

    #[test]
    fn test_parse_subs_specialchars() {
        let result = parse_subs_attribute("specialchars");
        assert_eq!(explicit(&result), &vec![Substitution::SpecialChars]);
    }

    #[test]
    fn test_parse_subs_specialchars_shorthand() {
        let result = parse_subs_attribute("c");
        assert_eq!(explicit(&result), &vec![Substitution::SpecialChars]);
    }

    #[test]
    fn test_parse_subs_specialcharacters_alias() {
        let result = parse_subs_attribute("specialcharacters");
        assert_eq!(explicit(&result), &vec![Substitution::SpecialChars]);
    }

    #[test]
    fn test_parse_subs_normal_expands() {
        let result = parse_subs_attribute("normal");
        assert_eq!(explicit(&result), &NORMAL.to_vec());
    }

    #[test]
    fn test_parse_subs_verbatim_expands() {
        let result = parse_subs_attribute("verbatim");
        assert_eq!(explicit(&result), &VERBATIM.to_vec());
    }

    #[test]
    fn test_parse_subs_append_modifier() {
        let result = parse_subs_attribute("+quotes");
        let ops = modifiers(&result);
        assert_eq!(ops, &vec![SubstitutionOp::Append(Substitution::Quotes)]);

        // Verify resolved result with VERBATIM baseline
        let resolved = result.resolve(VERBATIM);
        assert!(resolved.contains(&Substitution::SpecialChars));
        assert!(resolved.contains(&Substitution::Callouts));
        assert!(resolved.contains(&Substitution::Quotes));
        assert_eq!(resolved.last(), Some(&Substitution::Quotes));
    }

    #[test]
    fn test_parse_subs_prepend_modifier() {
        let result = parse_subs_attribute("quotes+");
        let ops = modifiers(&result);
        assert_eq!(ops, &vec![SubstitutionOp::Prepend(Substitution::Quotes)]);

        // Verify resolved result with VERBATIM baseline
        let resolved = result.resolve(VERBATIM);
        assert_eq!(resolved.first(), Some(&Substitution::Quotes));
        assert!(resolved.contains(&Substitution::SpecialChars));
        assert!(resolved.contains(&Substitution::Callouts));
    }

    #[test]
    fn test_parse_subs_remove_modifier() {
        let result = parse_subs_attribute("-specialchars");
        let ops = modifiers(&result);
        assert_eq!(
            ops,
            &vec![SubstitutionOp::Remove(Substitution::SpecialChars)]
        );

        // Verify resolved result with VERBATIM baseline
        let resolved = result.resolve(VERBATIM);
        assert!(!resolved.contains(&Substitution::SpecialChars));
        assert!(resolved.contains(&Substitution::Callouts));
    }

    #[test]
    fn test_parse_subs_remove_all_verbatim() {
        let result = parse_subs_attribute("-specialchars,-callouts");
        let ops = modifiers(&result);
        assert_eq!(ops.len(), 2);

        // Verify resolved result with VERBATIM baseline
        let resolved = result.resolve(VERBATIM);
        assert!(resolved.is_empty());
    }

    #[test]
    fn test_parse_subs_combined_modifiers() {
        let result = parse_subs_attribute("+quotes,-callouts");
        let ops = modifiers(&result);
        assert_eq!(ops.len(), 2);

        // Verify resolved result with VERBATIM baseline
        let resolved = result.resolve(VERBATIM);
        assert!(resolved.contains(&Substitution::SpecialChars)); // from default
        assert!(resolved.contains(&Substitution::Quotes)); // added
        assert!(!resolved.contains(&Substitution::Callouts)); // removed
    }

    #[test]
    fn test_parse_subs_ordering_preserved() {
        let result = parse_subs_attribute("quotes,attributes,specialchars");
        assert_eq!(
            explicit(&result),
            &vec![
                Substitution::Quotes,
                Substitution::Attributes,
                Substitution::SpecialChars
            ]
        );
    }

    #[test]
    fn test_parse_subs_shorthand_list() {
        let result = parse_subs_attribute("q,a,c");
        assert_eq!(
            explicit(&result),
            &vec![
                Substitution::Quotes,
                Substitution::Attributes,
                Substitution::SpecialChars
            ]
        );
    }

    #[test]
    fn test_parse_subs_with_spaces() {
        let result = parse_subs_attribute(" quotes , attributes ");
        assert_eq!(
            explicit(&result),
            &vec![Substitution::Quotes, Substitution::Attributes]
        );
    }

    #[test]
    fn test_parse_subs_duplicates_ignored() {
        let result = parse_subs_attribute("quotes,quotes,quotes");
        assert_eq!(explicit(&result), &vec![Substitution::Quotes]);
    }

    #[test]
    fn test_parse_subs_normal_in_list_expands() {
        let result = parse_subs_attribute("normal");
        let subs = explicit(&result);
        // Should expand to all NORMAL substitutions
        assert_eq!(subs.len(), NORMAL.len());
        for sub in NORMAL {
            assert!(subs.contains(sub));
        }
    }

    #[test]
    fn test_parse_subs_append_normal_group() {
        let result = parse_subs_attribute("+normal");
        // This is modifier syntax, resolve with a baseline that has Callouts
        let resolved = result.resolve(&[Substitution::Callouts]);
        // Should have Callouts + all of NORMAL
        assert!(resolved.contains(&Substitution::Callouts));
        for sub in NORMAL {
            assert!(resolved.contains(sub));
        }
    }

    #[test]
    fn test_parse_subs_remove_normal_group() {
        let result = parse_subs_attribute("-normal");
        // This is modifier syntax, resolve with NORMAL baseline
        let resolved = result.resolve(NORMAL);
        // Removing normal group should leave empty
        assert!(resolved.is_empty());
    }

    #[test]
    fn test_parse_subs_unknown_is_skipped() {
        // Unknown substitution types are logged and skipped
        let result = parse_subs_attribute("unknown");
        assert!(explicit(&result).is_empty());
    }

    #[test]
    fn test_parse_subs_unknown_mixed_with_valid() {
        // Unknown substitution types are skipped, valid ones are kept
        let result = parse_subs_attribute("quotes,typo,attributes");
        assert_eq!(
            explicit(&result),
            &vec![Substitution::Quotes, Substitution::Attributes]
        );
    }

    #[test]
    fn test_parse_subs_all_individual_types() {
        // Test each substitution type can be parsed
        assert_eq!(
            explicit(&parse_subs_attribute("attributes")),
            &vec![Substitution::Attributes]
        );
        assert_eq!(
            explicit(&parse_subs_attribute("replacements")),
            &vec![Substitution::Replacements]
        );
        assert_eq!(
            explicit(&parse_subs_attribute("macros")),
            &vec![Substitution::Macros]
        );
        assert_eq!(
            explicit(&parse_subs_attribute("post_replacements")),
            &vec![Substitution::PostReplacements]
        );
        assert_eq!(
            explicit(&parse_subs_attribute("quotes")),
            &vec![Substitution::Quotes]
        );
        assert_eq!(
            explicit(&parse_subs_attribute("callouts")),
            &vec![Substitution::Callouts]
        );
    }

    #[test]
    fn test_parse_subs_shorthand_types() {
        assert_eq!(
            explicit(&parse_subs_attribute("a")),
            &vec![Substitution::Attributes]
        );
        assert_eq!(
            explicit(&parse_subs_attribute("r")),
            &vec![Substitution::Replacements]
        );
        assert_eq!(
            explicit(&parse_subs_attribute("m")),
            &vec![Substitution::Macros]
        );
        assert_eq!(
            explicit(&parse_subs_attribute("p")),
            &vec![Substitution::PostReplacements]
        );
        assert_eq!(
            explicit(&parse_subs_attribute("q")),
            &vec![Substitution::Quotes]
        );
        assert_eq!(
            explicit(&parse_subs_attribute("c")),
            &vec![Substitution::SpecialChars]
        );
    }

    #[test]
    fn test_parse_subs_mixed_modifier_list() {
        // Bug case: subs=specialchars,+quotes - modifier not at start of string
        let result = parse_subs_attribute("specialchars,+quotes");
        // Should be in modifier mode
        let ops = modifiers(&result);
        assert_eq!(ops.len(), 2); // specialchars (as append) and +quotes

        // Verify resolved result with VERBATIM baseline
        let resolved = result.resolve(VERBATIM);
        assert!(resolved.contains(&Substitution::SpecialChars));
        assert!(resolved.contains(&Substitution::Callouts)); // from VERBATIM default
        assert!(resolved.contains(&Substitution::Quotes)); // appended
    }

    #[test]
    fn test_parse_subs_modifier_in_middle() {
        // subs=attributes,+quotes,-callouts
        let result = parse_subs_attribute("attributes,+quotes,-callouts");
        let ops = modifiers(&result);
        assert_eq!(ops.len(), 3);

        // Verify resolved result with VERBATIM baseline
        let resolved = result.resolve(VERBATIM);
        assert!(resolved.contains(&Substitution::Attributes)); // plain name in modifier context
        assert!(resolved.contains(&Substitution::Quotes)); // appended
        assert!(!resolved.contains(&Substitution::Callouts)); // removed
    }

    #[test]
    fn test_parse_subs_asciidoctor_example() {
        // From asciidoctor docs: subs="attributes+,+replacements,-callouts"
        let result = parse_subs_attribute("attributes+,+replacements,-callouts");
        let ops = modifiers(&result);
        assert_eq!(ops.len(), 3);

        // Verify resolved result with VERBATIM baseline
        let resolved = result.resolve(VERBATIM);
        assert_eq!(resolved.first(), Some(&Substitution::Attributes)); // prepended
        assert!(resolved.contains(&Substitution::Replacements)); // appended
        assert!(!resolved.contains(&Substitution::Callouts)); // removed
    }

    #[test]
    fn test_parse_subs_modifier_only_at_end() {
        // Modifier at end of comma-separated list
        let result = parse_subs_attribute("quotes,-specialchars");
        // Should detect modifier mode from -specialchars
        let ops = modifiers(&result);
        assert_eq!(ops.len(), 2);

        // Verify resolved result with VERBATIM baseline
        let resolved = result.resolve(VERBATIM);
        assert!(resolved.contains(&Substitution::Quotes)); // plain name appended
        assert!(!resolved.contains(&Substitution::SpecialChars)); // removed
        assert!(resolved.contains(&Substitution::Callouts)); // from default
    }

    #[test]
    fn test_resolve_modifiers_with_normal_baseline() {
        // This is the key test for the bug fix:
        // -quotes on a paragraph should remove quotes from NORMAL baseline
        let result = parse_subs_attribute("-quotes");
        let resolved = result.resolve(NORMAL);

        // Should have all of NORMAL except Quotes
        assert!(resolved.contains(&Substitution::SpecialChars));
        assert!(resolved.contains(&Substitution::Attributes));
        assert!(!resolved.contains(&Substitution::Quotes)); // removed
        assert!(resolved.contains(&Substitution::Replacements));
        assert!(resolved.contains(&Substitution::Macros));
        assert!(resolved.contains(&Substitution::PostReplacements));
    }

    #[test]
    fn test_resolve_modifiers_with_verbatim_baseline() {
        // -quotes on a listing block: Quotes wasn't in VERBATIM, so no effect
        let result = parse_subs_attribute("-quotes");
        let resolved = result.resolve(VERBATIM);

        // Should still have all of VERBATIM (quotes wasn't there to remove)
        assert!(resolved.contains(&Substitution::SpecialChars));
        assert!(resolved.contains(&Substitution::Callouts));
        assert!(!resolved.contains(&Substitution::Quotes));
    }

    #[test]
    fn test_resolve_explicit_ignores_baseline() {
        // Explicit lists should ignore the baseline
        let result = parse_subs_attribute("quotes,attributes");
        let resolved_normal = result.resolve(NORMAL);
        let resolved_verbatim = result.resolve(VERBATIM);

        // Both should be the same
        assert_eq!(resolved_normal, resolved_verbatim);
        assert_eq!(
            resolved_normal,
            vec![Substitution::Quotes, Substitution::Attributes]
        );
    }

    #[test]
    fn test_resolve_attribute_references() {
        // These two are attributes we add to the attributes map.
        let attribute_weight = AttributeValue::String(String::from("weight"));
        let attribute_mass = AttributeValue::String(String::from("mass"));

        // This one is an attribute we do NOT add to the attributes map so it can never be
        // resolved.
        let attribute_volume_repeat = String::from("value {attribute_volume}");

        let mut attributes = DocumentAttributes::default();
        attributes.insert("weight".into(), attribute_weight.clone());
        attributes.insert("mass".into(), attribute_mass.clone());

        // Resolve an attribute that is in the attributes map.
        let resolved = substitute("{weight}", HEADER, &attributes);
        assert_eq!(resolved, "weight".to_string());

        // Resolve two attributes that are in the attributes map.
        let resolved = substitute("{weight} {mass}", HEADER, &attributes);
        assert_eq!(resolved, "weight mass".to_string());

        // Resolve without attributes in the map
        let resolved = substitute("value {attribute_volume}", HEADER, &attributes);
        assert_eq!(resolved, attribute_volume_repeat);
    }

    #[test]
    fn test_substitute_single_pass_expansion() {
        // Test that the substitute() function does single-pass expansion.
        // When foo's value is "{bar}", substitute("{foo}") returns the literal
        // "{bar}" string - it does NOT recursively resolve {bar}.
        //
        // This is correct behavior because:
        // 1. Definition-time resolution is handled separately (in the grammar parser)
        // 2. The substitute function just replaces one level of references
        let mut attributes = DocumentAttributes::default();
        attributes.insert("foo".into(), AttributeValue::String("{bar}".to_string()));
        attributes.insert(
            "bar".into(),
            AttributeValue::String("should-not-appear".to_string()),
        );

        let resolved = substitute("{foo}", HEADER, &attributes);
        assert_eq!(resolved, "{bar}");
    }

    #[test]
    fn test_utf8_boundary_handling() {
        // Regression test for fuzzer-found bug: UTF-8 multi-byte characters
        // should not cause panics during attribute substitution
        let attributes = DocumentAttributes::default();

        let values = [
            // Input with UTF-8 multi-byte character (Ô = 0xc3 0x94)
            ":J::~\x01\x00\x00Ô",
            // Test with various UTF-8 characters and attribute-like patterns
            "{attr}Ô{missing}日本語",
            // Test with multi-byte chars inside attribute name
            "{attrÔ}test",
        ];
        for value in values {
            let resolved = substitute(value, HEADER, &attributes);
            assert_eq!(resolved, value);
        }
    }

    #[test]
    fn test_macros_disabled_explicit_without_macros() {
        let spec = parse_subs_attribute("specialchars");
        assert!(spec.macros_disabled());
    }

    #[test]
    fn test_macros_disabled_explicit_with_macros() {
        let spec = parse_subs_attribute("macros");
        assert!(!spec.macros_disabled());
    }

    #[test]
    fn test_macros_disabled_explicit_normal_includes_macros() {
        let spec = parse_subs_attribute("normal");
        assert!(!spec.macros_disabled());
    }

    #[test]
    fn test_macros_disabled_modifier_remove() {
        let spec = parse_subs_attribute("-macros");
        assert!(spec.macros_disabled());
    }

    #[test]
    fn test_macros_disabled_modifier_add() {
        let spec = parse_subs_attribute("+macros");
        assert!(!spec.macros_disabled());
    }

    #[test]
    fn test_macros_disabled_explicit_none() {
        let spec = parse_subs_attribute("none");
        assert!(spec.macros_disabled());
    }

    #[test]
    fn test_attributes_disabled_explicit_without_attributes() {
        let spec = parse_subs_attribute("specialchars");
        assert!(spec.attributes_disabled());
    }

    #[test]
    fn test_attributes_disabled_explicit_with_attributes() {
        let spec = parse_subs_attribute("attributes");
        assert!(!spec.attributes_disabled());
    }

    #[test]
    fn test_attributes_disabled_explicit_normal_includes_attributes() {
        let spec = parse_subs_attribute("normal");
        assert!(!spec.attributes_disabled());
    }

    #[test]
    fn test_attributes_disabled_modifier_remove() {
        let spec = parse_subs_attribute("-attributes");
        assert!(spec.attributes_disabled());
    }

    #[test]
    fn test_attributes_disabled_modifier_add() {
        let spec = parse_subs_attribute("+attributes");
        assert!(!spec.attributes_disabled());
    }

    #[test]
    fn test_attributes_disabled_explicit_none() {
        let spec = parse_subs_attribute("none");
        assert!(spec.attributes_disabled());
    }
}