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
use std::{
borrow::Cow,
cell::{Cell, RefCell},
collections::{HashMap, HashSet},
num::NonZeroUsize,
ops::Range,
path::PathBuf,
rc::{Rc, Weak},
sync::Arc,
};
use bitflags::bitflags;
use bumpalo::Bump;
use crate::{
CalloutRef, CaptionKind, DocumentAttribute, DocumentAttributes, Error, Footnote, Location,
Options, Pass, SourceLocation, TocEntry, Warning, WarningKind, XrefCaptionLabel, XrefSignifier,
document_attribute::{AttributeDeclaration, RawAttributeValue},
grammar::LineMap,
model::{
DocumentAttributeStatus, LeveloffsetRange, REFSIG_ATTRIBUTES, SourceRange,
substitution::SubstitutionPlan,
},
};
#[derive(Clone, Copy, Debug)]
struct XrefCaptionLabelSnapshot<'a> {
example: XrefCaptionLabel<'a>,
listing: XrefCaptionLabel<'a>,
table: XrefCaptionLabel<'a>,
signifiers: &'a [XrefSignifier<'a>; REFSIG_ATTRIBUTES.len()],
}
#[derive(Debug, Default)]
struct XrefCaptionLabelSnapshots<'a> {
entries: Vec<XrefCaptionLabelSnapshot<'a>>,
// Attribute writes use `Rc::make_mut`, which invalidates this weak identity
// without forcing an attribute-map clone when there is only one owner.
last: Option<(Weak<DocumentAttributes<'a>>, NonZeroUsize)>,
}
#[derive(Debug)]
pub(crate) struct ParserState<'a> {
pub(crate) document_attributes: Rc<DocumentAttributes<'a>>,
/// Attributes inherited by the current nested document. Asciidoctor-style
/// table cells may read these values, but attribute entries in the cell
/// cannot replace or unset them.
pub(crate) nested_parent_attributes: Option<Rc<DocumentAttributes<'a>>>,
/// Tracks document hard-break changes that apply only to following blocks.
pub(crate) hardbreaks: bool,
/// Processed-text offsets where an empty attribute reference was removed.
pub(crate) empty_attribute_offsets: Vec<usize>,
/// Attribute-produced spans used to preserve substitution order in nested parsing.
pub(crate) attribute_value_ranges: Vec<Range<usize>>,
/// Original references for index labels and code boundaries checked before attributes.
pub(crate) late_attribute_sources: Vec<(Range<usize>, &'a str)>,
/// Boundary left by the last completed inline node in this parse.
pub(crate) last_url_boundary: Option<InlineUrlBoundary>,
pub(crate) line_map: Rc<LineMap>,
/// Parse options, shared via `Rc` so the per-inline-parse
/// `for_inline_parsing` sub-state is cheap to construct — the old
/// `Options` deep-clone (including its ~80-entry `DocumentAttributes`
/// default map) was a meaningful hot spot.
pub(crate) options: Rc<Options<'a>>,
/// The input being parsed. Borrowed from the caller's buffer so that
/// model nodes can hold `Cow::Borrowed` references into it without
/// allocating per-token strings.
pub(crate) input: &'a str,
/// Bump arena for transient strings that downstream inline parsing must
/// borrow from with lifetime `'a`. Used for substitution buffers, escape
/// unwrapping, and other grammar sites that historically built local
/// `String`s and then tried to hand them to the inline parser. Strings
/// are pushed via `arena.alloc_str(...)`, yielding `&'a str`.
pub(crate) arena: &'a Bump,
/// Shared via `Rc<RefCell>` so the sub-state built by `for_inline_parsing`
/// doesn't have to deep-clone the tracker on entry and on writeback. The
/// tracker is push-only and participates in no rollback semantics, so
/// sharing a single cell across the top-level state and every nested
/// inline sub-parse is equivalent to the old clone/writeback pattern for
/// all success paths and for every failure path the caller already fails
/// through. This matters because macro-heavy fixtures (footnotes +
/// bold/italic/mono/xref content) trigger hundreds of recursive
/// `process_inlines` calls, and the prior pattern produced O(N×M) work
/// where N is footnote count and M is the number of nested parses.
pub(crate) footnote_tracker: Rc<RefCell<FootnoteTracker<'a>>>,
xref_caption_label_snapshots: Rc<RefCell<XrefCaptionLabelSnapshots<'a>>>,
/// TOC entries collected during parsing, in document order. A section pushes its
/// [`TocEntry`] here as soon as its title is parsed; `numbered` is `false` for
/// special styles (`[bibliography]`, `[glossary]`, ...) that are not auto-numbered
/// under `sectnums`.
pub(crate) toc_entries: Vec<TocEntry<'a>>,
pub(crate) block_context: BlockContext,
/// Base offset of the input containing the active callout list.
/// Reparsed delimited-block content must not terminate that list.
pub(crate) callout_list_offset: Option<usize>,
/// Verbatim callout references collected since the previous callout list.
pub(crate) pending_callouts: Vec<CalloutRef>,
/// The current file being parsed (`None` for inline/string parsing). Used as the
/// fallback file for diagnostics (`create_error_source_location`) when an offset
/// isn't covered by a recorded source range.
///
/// Held as `Arc` for the **hot** clone: `for_inline_parsing` inherits it once per
/// inline sub-parse (and macro-heavy docs spawn hundreds), where the refcount bump
/// beats a `PathBuf` copy. The diagnostic sites instead deep-copy it into the public
/// [`SourceLocation::file`](crate::SourceLocation) (`Option<PathBuf>`) API so it's
/// left as a copy rather than widening the published API to `Option<Arc<PathBuf>>`.
pub(crate) current_file: Option<Arc<PathBuf>>,
/// Byte ranges where specific leveloffset values apply. Set by the preprocessor when
/// processing includes with `leveloffset=` attributes. Used by the parser to adjust
/// section levels.
pub(crate) leveloffset_ranges: Vec<LeveloffsetRange>,
/// Byte ranges mapping preprocessed output back to source files. Set by the
/// preprocessor when processing `include::` directives. Used to produce accurate
/// file/line info in warnings.
pub(crate) source_ranges: Vec<SourceRange>,
/// Full include names used by document-level cross-reference resolution.
pub(crate) included_files: HashSet<String>,
/// Warnings collected during PEG parsing. Shared across the top-level state and any
/// `for_inline_parsing` sub-states via `Rc`, so warnings raised during nested inline
/// parses (author lines, revision lines, substituted inline content) reach the
/// top-level `ParseResult` alongside everything else. The outer `parse_input` /
/// `parse_inline` keeps a clone of this `Rc` and recovers the final `Vec<Warning>`
/// after the self-cell builder closure drops the `ParserState`. Deduplicated on
/// insertion because PEG backtracking can re-fire the same warning multiple times.
pub(crate) warnings: Rc<RefCell<Vec<Warning>>>,
/// When true, inline parsing uses a reduced rule set that only matches formatting
/// markup (bold, italic, monospace, highlight, superscript, subscript, curved quotes)
/// and plain text. Used by `parse_text_for_quotes` to apply "quotes" substitution
/// without matching macros, xrefs, etc.
pub(crate) quotes_only: bool,
/// Profiled attribute placeholders available to this inline grammar. Consume
/// them in source order so their notes precede later literal references.
pub(crate) attribute_passthroughs: Rc<[Pass<'a>]>,
/// When parsing content extracted from a constrained formatting rule, holds
/// the delimiter byte of the outer formatting (e.g., `b'_'` for italic).
/// Used to correctly fail boundary checks when the outer delimiter is a
/// word character (only `_` among the formatting delimiters).
pub(crate) outer_constrained_delimiter: Option<u8>,
/// Whether this state parses document content or a nested inline segment.
pub(crate) scope: ParserScope,
/// Context set before entering the PEG inline parser. These fields are
/// constant within a single `inlines()` call, allowing rules to be
/// argument-free and thus cacheable by the PEG packrat memoizer.
pub(crate) inline_ctx: InlineContext,
/// Memoised `@`-lookahead covering `[.., scanned_up_to)` with the first
/// `@` in that range, if any. Without the `scanned_up_to` field, a cached
/// "no `@`" result at offset X is indistinguishable from "`@` is at X"
/// and can trigger the expensive email rule the cache was meant to avoid.
pub(crate) next_at_sign_cache: Cell<Option<AtLookahead>>,
}
#[derive(Debug, Clone, Copy)]
pub(crate) enum InlineUrlBoundary {
Formatted(usize),
Protected(usize),
Text(usize, Option<char>),
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct AtLookahead {
pub(crate) scanned_up_to: usize,
pub(crate) first_at: Option<usize>,
}
/// Inline parsing context — constant within a single `inlines()` call.
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct InlineContext {
/// Byte offset for location calculation in inline rules.
pub(crate) offset: usize,
/// Enabled substitutions and their source order.
pub(crate) substitutions: SubstitutionPlan,
/// Independent grammar capabilities for this parse.
pub(crate) rules: InlineRules,
}
bitflags! {
/// Independent grammar capabilities for one inline parse.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct InlineRules: u16 {
/// Match bare URLs and email addresses.
const AUTOLINKS = 1 << 0;
/// Match index-term macros.
const INDEX_TERMS = 1 << 1;
/// Apply the document or block hard-break option.
const HARD_BREAKS = 1 << 2;
/// Permit a trailing ` +` to end at end of input.
const EOI_HARD_BREAK = 1 << 3;
/// Restrict label parsing to substitutions that precede index registration.
const INDEX_CATALOG = 1 << 4;
/// Remove one closing-bracket escape inside a link, xref, or footnote label.
const BRACKET_LABEL = 1 << 5;
/// Remove escaped double quotes from a double-quoted link label.
const DOUBLE_QUOTED_LINK = 1 << 6;
/// Remove escaped single quotes from a single-quoted link label.
const SINGLE_QUOTED_LINK = 1 << 7;
/// Quote unescaping that applies to display text after macro registration.
const QUOTED_LINK = Self::DOUBLE_QUOTED_LINK.bits() | Self::SINGLE_QUOTED_LINK.bits();
/// Preserve square-bracket escapes that do not delimit this index label.
const INDEX_LABEL = 1 << 8;
/// Consume one closing-bracket escape for a named index macro's delimiter.
const NAMED_INDEX_LABEL = 1 << 9;
/// Keep empty verse lines inside the same inline content.
const PRESERVE_BLANK_LINES = 1 << 10;
}
}
impl Default for InlineRules {
fn default() -> Self {
Self::AUTOLINKS | Self::INDEX_TERMS
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ParserScope {
Document,
Inline,
}
/// Compound bodies admit discrete headings, while documents also admit sections.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum BlockContext {
Document,
Compound,
}
#[derive(Debug, Clone)]
struct NamedFootnote<'a> {
number: u32,
definition: Option<(&'a str, Location)>,
}
#[derive(Debug, Clone)]
pub(crate) struct FootnoteTracker<'a> {
/// All registered footnotes in the order they were encountered.
pub(crate) footnotes: Vec<Footnote<'a>>,
/// The last assigned footnote number (starts at 1)
last_footnote_position: u32,
named_footnotes: HashMap<&'a str, NamedFootnote<'a>>,
/// Footnote numbers whose stored entry has already had its location/content
/// finalized to document-absolute coordinates (see [`Self::finalize`]). The first
/// occurrence of a number wins, so a later bare reference of a named footnote does
/// not overwrite the defining occurrence.
location_finalized: HashSet<u32>,
}
impl<'a> FootnoteTracker<'a> {
pub(crate) fn new() -> Self {
Self {
footnotes: Vec::new(),
last_footnote_position: 1,
named_footnotes: HashMap::new(),
location_finalized: HashSet::new(),
}
}
/// Update the first definition after its locations become document-absolute.
/// Later occurrences keep that body and location. Return the first location
/// when a repeated definition has different captured text.
pub(crate) fn finalize(&mut self, footnote: &mut Footnote<'a>) -> Option<Location> {
let conflict = footnote.definition_source.take().and_then(|body| {
let entry = self.named_footnotes.get_mut(footnote.id?)?;
if let Some((original, location)) = &entry.definition {
(body != *original).then(|| location.clone())
} else {
entry.definition = Some((body, footnote.location.clone()));
None
}
});
if self.location_finalized.insert(footnote.number)
&& let Some(index) = footnote.number.checked_sub(1)
&& let Some(entry) = self.footnotes.get_mut(index as usize)
{
entry.location = footnote.location.clone();
entry.content.clone_from(&footnote.content);
entry.definition_source = None;
}
conflict
}
pub(crate) fn contains(&self, id: &str) -> bool {
self.named_footnotes.contains_key(id)
}
/// Assign a number, reusing named definitions. Return false for an undefined reference.
#[tracing::instrument(skip_all, fields(?footnote))]
pub(crate) fn push(&mut self, footnote: &mut Footnote<'a>) -> bool {
if let Some(id) = footnote.id
&& let Some(existing) = self.named_footnotes.get(id)
{
footnote.number = existing.number;
footnote.content.clear();
return true;
}
if footnote.content.is_empty() {
return false;
}
footnote.number = self.last_footnote_position;
if let Some(id) = footnote.id {
self.named_footnotes.insert(
id,
NamedFootnote {
number: self.last_footnote_position,
definition: None,
},
);
}
self.footnotes.push(footnote.clone());
self.last_footnote_position += 1;
true
}
}
impl<'a> ParserState<'a> {
/// Finalize a footnote only after its locations are document-absolute.
pub(crate) fn finalize_footnote(&self, footnote: &mut Footnote<'a>) {
if self.scope == ParserScope::Document
&& let Some(first) = self.footnote_tracker.borrow_mut().finalize(footnote)
&& let Some(id) = footnote.id
{
self.add_warning(Warning::new(
WarningKind::ConflictingFootnote {
id: id.to_owned(),
first: Box::new(self.create_error_source_location(first)),
},
Some(self.create_error_source_location(footnote.location.clone())),
));
}
}
/// Allocate `s` into the arena, returning a `&'a str` that lives for the
/// parse. Used by grammar rules that build a transient owned `String`
/// (attribute substitution, escape unwrapping, …) and need to hand the
/// result to the inline parser with the outer `'a` lifetime so that the
/// resulting `InlineNode`s can be returned.
pub(crate) fn intern_str(&self, s: &str) -> &'a str {
self.arena.alloc_str(s)
}
/// Promote a `Cow<'b, str>` to `&'a str`. `Owned` variants are interned
/// into the arena; `Borrowed` values pass through unchanged (no copy)
/// when their lifetime already outlives `'a`, which is the common case
/// for substitution results that borrowed from the grammar input.
pub(crate) fn intern_cow<'b>(&self, cow: Cow<'b, str>) -> &'a str
where
'b: 'a,
{
match cow {
Cow::Borrowed(s) => s,
Cow::Owned(s) => self.arena.alloc_str(&s),
}
}
/// Format `args` directly into the arena, returning `&'a str`. Avoids the
/// heap-`String` + `alloc_str`-copy pair that `intern_str(&format!(...))`
/// forces: a single write into `bumpalo::collections::String`.
pub(crate) fn intern_fmt(&self, args: std::fmt::Arguments<'_>) -> &'a str {
use std::fmt::Write as _;
let mut s = bumpalo::collections::String::new_in(self.arena);
// `BumpString::write_fmt` is infallible; the `Err` arm is unreachable.
let _ = s.write_fmt(args);
s.into_bump_str()
}
/// Concatenate `parts` into the arena separated by `sep`, returning
/// `&'a str`. Avoids the heap-`String` `.join(...)` followed by an
/// `alloc_str` copy.
pub(crate) fn intern_join<I, S>(&self, parts: I, sep: &str) -> &'a str
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
let mut s = bumpalo::collections::String::new_in(self.arena);
let mut first = true;
for p in parts {
if !first {
s.push_str(sep);
}
first = false;
s.push_str(p.as_ref());
}
s.into_bump_str()
}
pub(crate) fn capture_xref_caption_labels(&self) -> NonZeroUsize {
let mut snapshots = self.xref_caption_label_snapshots.borrow_mut();
if let Some((attributes, snapshot)) = &snapshots.last
&& attributes.ptr_eq(&Rc::downgrade(&self.document_attributes))
{
return *snapshot;
}
let label = |name| match self.document_attributes.get(name) {
Some(resolved) => match resolved.as_str() {
Some(value) => {
let value = self.intern_str(crate::strip_quotes(value));
if value.is_empty() {
XrefCaptionLabel::NumberOnly
} else {
XrefCaptionLabel::AtReference(value)
}
}
None if resolved.is_presence() => XrefCaptionLabel::NumberOnly,
None => {
let mut value = String::new();
let _ = resolved.write_text(&mut value);
if value.is_empty() {
XrefCaptionLabel::NumberOnly
} else {
XrefCaptionLabel::AtReference(self.intern_str(&value))
}
}
},
None => XrefCaptionLabel::AtTarget,
};
// `status` rather than `get`: an explicitly unset refsig drops the word
// entirely, whereas `get` would hand back the attribute's default.
let signifier = |(_, key)| match self.document_attributes.status(key) {
DocumentAttributeStatus::Set(value) => {
let mut word = String::new();
let _ = value.write_text(&mut word);
XrefSignifier::AtReference(self.intern_str(crate::strip_quotes(&word)))
}
DocumentAttributeStatus::Unset => XrefSignifier::Omitted,
DocumentAttributeStatus::Absent => XrefSignifier::Standard,
};
let signifiers = self.arena.alloc(REFSIG_ATTRIBUTES.map(signifier));
let snapshot = NonZeroUsize::MIN.saturating_add(snapshots.entries.len());
snapshots.entries.push(XrefCaptionLabelSnapshot {
example: label("example-caption"),
listing: label("listing-caption"),
table: label("table-caption"),
signifiers,
});
snapshots.last = Some((Rc::downgrade(&self.document_attributes), snapshot));
snapshot
}
pub(crate) fn xref_signifiers(
&self,
snapshot: NonZeroUsize,
) -> Option<&'a [XrefSignifier<'a>; REFSIG_ATTRIBUTES.len()]> {
self.xref_caption_label_snapshots
.borrow()
.entries
.get(snapshot.get() - 1)
.map(|labels| labels.signifiers)
}
pub(crate) fn xref_caption_label(
&self,
snapshot: NonZeroUsize,
kind: CaptionKind,
) -> XrefCaptionLabel<'a> {
let labels = self
.xref_caption_label_snapshots
.borrow()
.entries
.get(snapshot.get() - 1)
.copied();
labels.map_or(XrefCaptionLabel::AtTarget, |labels| match kind {
CaptionKind::Example => labels.example,
CaptionKind::Listing => labels.listing,
CaptionKind::Table => labels.table,
CaptionKind::Figure => XrefCaptionLabel::AtTarget,
})
}
/// Apply an attribute entry declared by document content: expand `{attr}`
/// references at definition time (matching `asciidoctor`), retain the result
/// for the parse, and store it unless the built-in policy, parser options, or
/// a nested parent lock the name against document changes.
///
/// Returns an AST event when the assignment was accepted.
pub(crate) fn apply_document_attribute(
&mut self,
declaration: &AttributeDeclaration<'a>,
in_header: bool,
location: Location,
) -> Option<DocumentAttribute<'a>> {
let AttributeDeclaration { name, value } = declaration;
let key = Cow::Borrowed(*name);
let set = !matches!(value, RawAttributeValue::Unset);
let (value, profile_warning) = value.resolve_with_warning(&self.document_attributes);
let force_locked = self
.nested_parent_attributes
.as_ref()
.is_some_and(|attributes| attributes.locks_nested_attribute(key.as_ref()));
let updates_hardbreaks = matches!(key.as_ref(), "hardbreaks" | "hardbreaks-option");
let result = Rc::make_mut(&mut self.document_attributes).assign_document_value(
key.clone(),
value,
in_header,
force_locked,
None,
);
let applied = match result {
Ok(Some(applied)) => applied,
Ok(None) => return None,
Err(Error::InvalidDocumentAttribute {
name,
value: invalid_value,
expected,
location: _,
}) => {
let source_location = self.create_error_source_location(location.clone());
self.add_warning(Warning::new(
WarningKind::InvalidDocumentAttribute {
name,
value: invalid_value,
expected,
},
Some(source_location),
));
return None;
}
Err(error) => {
self.add_generic_warning(error.to_string());
return None;
}
};
// A locked or invalid assignment must not warn about a value that was ignored.
if let Some(message) = profile_warning {
self.add_warning(Warning::new(
WarningKind::Other(message.into()),
Some(self.create_error_source_location(location.clone())),
));
}
if updates_hardbreaks {
self.hardbreaks = set;
}
Some(DocumentAttribute::accepted(key, applied, location))
}
/// Initialize hard-break state from attributes supplied by the parser API.
pub(crate) fn initialize_hardbreaks(&mut self) {
let hardbreaks = match self.document_attributes.status("hardbreaks-option") {
DocumentAttributeStatus::Absent => self.document_attributes.status("hardbreaks"),
status @ (DocumentAttributeStatus::Set(_) | DocumentAttributeStatus::Unset) => status,
};
self.hardbreaks = matches!(hardbreaks, DocumentAttributeStatus::Set(_));
}
/// Testing helper: constructs a `ParserState` backed by a leaked `Bump`.
/// One leak per call, bounded by the number of test cases executed —
/// acceptable because `cargo test` tears down the process afterwards.
/// Do **not** use from production code paths (use `new` with an explicit
/// arena owned by the caller instead).
#[cfg(test)]
pub(crate) fn new_for_test(input: &'a str) -> Self {
let arena: &'a Bump = Box::leak(Box::new(Bump::new()));
Self::new(input, arena)
}
pub(crate) fn new(input: &'a str, arena: &'a Bump) -> Self {
Self {
options: Rc::new(Options::default()),
document_attributes: Rc::new(DocumentAttributes::default()),
nested_parent_attributes: None,
hardbreaks: false,
empty_attribute_offsets: Vec::new(),
attribute_value_ranges: Vec::new(),
late_attribute_sources: Vec::new(),
last_url_boundary: None,
line_map: Rc::new(LineMap::new(input)),
input,
arena,
footnote_tracker: Rc::new(RefCell::new(FootnoteTracker::new())),
xref_caption_label_snapshots: Rc::default(),
toc_entries: Vec::new(),
block_context: BlockContext::Document,
callout_list_offset: None,
pending_callouts: Vec::new(),
current_file: None,
leveloffset_ranges: Vec::new(),
source_ranges: Vec::new(),
included_files: HashSet::new(),
warnings: Rc::new(RefCell::new(Vec::new())),
quotes_only: false,
attribute_passthroughs: Rc::default(),
outer_constrained_delimiter: None,
scope: ParserScope::Document,
inline_ctx: InlineContext::default(),
next_at_sign_cache: Cell::new(None),
}
}
/// Minimal constructor for quotes-only parsing where document attributes aren't needed.
pub(crate) fn new_quotes_only(input: &'a str, arena: &'a Bump) -> Self {
use std::sync::LazyLock;
// Cache empty options to avoid creating default DocumentAttributes (~80 HashMap
// entries) on every call. Quotes-only parsing doesn't use document attributes.
static EMPTY_OPTIONS: LazyLock<Options<'static>> = LazyLock::new(|| Options {
document_attributes: DocumentAttributes::empty(),
..Options::default()
});
Self {
options: Rc::new(EMPTY_OPTIONS.clone()),
document_attributes: Rc::new(DocumentAttributes::empty()),
nested_parent_attributes: None,
hardbreaks: false,
empty_attribute_offsets: Vec::new(),
attribute_value_ranges: Vec::new(),
late_attribute_sources: Vec::new(),
last_url_boundary: None,
line_map: Rc::new(LineMap::new(input)),
input,
arena,
footnote_tracker: Rc::new(RefCell::new(FootnoteTracker::new())),
xref_caption_label_snapshots: Rc::default(),
toc_entries: Vec::new(),
block_context: BlockContext::Document,
callout_list_offset: None,
pending_callouts: Vec::new(),
current_file: None,
leveloffset_ranges: Vec::new(),
source_ranges: Vec::new(),
included_files: HashSet::new(),
warnings: Rc::new(RefCell::new(Vec::new())),
quotes_only: true,
attribute_passthroughs: Rc::default(),
outer_constrained_delimiter: None,
scope: ParserScope::Document,
inline_ctx: InlineContext {
substitutions: SubstitutionPlan::only(&crate::Substitution::Quotes),
..InlineContext::default()
},
next_at_sign_cache: Cell::new(None),
}
}
/// Lightweight constructor for inline parsing that reuses parent state fields
/// instead of creating expensive defaults that get immediately overwritten.
pub(crate) fn for_inline_parsing(
input: &'a str,
parent: &ParserState<'a>,
inline_ctx: InlineContext,
) -> Self {
Self {
options: parent.options.clone(),
document_attributes: Rc::clone(&parent.document_attributes),
nested_parent_attributes: parent.nested_parent_attributes.clone(),
hardbreaks: parent.hardbreaks,
empty_attribute_offsets: Vec::new(),
attribute_value_ranges: Vec::new(),
late_attribute_sources: Vec::new(),
last_url_boundary: None,
line_map: Rc::new(LineMap::new(input)),
input,
arena: parent.arena,
footnote_tracker: Rc::clone(&parent.footnote_tracker),
xref_caption_label_snapshots: Rc::clone(&parent.xref_caption_label_snapshots),
toc_entries: Vec::new(),
block_context: BlockContext::Document,
callout_list_offset: None,
pending_callouts: Vec::new(),
// Inherit the file so inline sub-parse nodes are stamped with the correct
// origin file by `create_location` (cheap `Arc` clone).
current_file: parent.current_file.clone(),
leveloffset_ranges: Vec::new(),
source_ranges: Vec::new(),
included_files: HashSet::new(),
// Share the parent's warnings vec so anything raised during a
// nested inline sub-parse reaches the top-level `ParseResult`
// without a separate drain step.
warnings: Rc::clone(&parent.warnings),
quotes_only: parent.quotes_only,
attribute_passthroughs: Rc::clone(&parent.attribute_passthroughs),
outer_constrained_delimiter: parent.outer_constrained_delimiter,
scope: ParserScope::Inline,
inline_ctx,
next_at_sign_cache: Cell::new(None),
}
}
/// Warn about unexpected trailing content after a block macro's attribute list.
pub(crate) fn warn_trailing_macro_content(
&mut self,
macro_name: &str,
trailing: &str,
end: usize,
offset: usize,
) {
if !trailing.trim().is_empty() {
let start_abs = end + offset;
let location = self.create_location(start_abs, start_abs + trailing.len());
self.add_generic_warning_at(
format!("unexpected content after {macro_name} macro: '{trailing}'"),
location,
);
}
}
/// Collect an ad-hoc string warning with no source location. Prefer
/// [`Self::add_generic_warning_at`] whenever the call site has a
/// `Location`; untethered warnings are still useful (e.g. document-
/// wide conditions) but callers that can place the warning should.
pub(crate) fn add_generic_warning(&self, message: String) {
self.add_warning(Warning::new(WarningKind::Other(Cow::Owned(message)), None));
}
/// Collect an ad-hoc string warning anchored to a grammar `Location`.
/// Converts through `create_error_source_location` so the resulting
/// `SourceLocation` carries the correct file, including the mapping
/// through `source_ranges` for included content.
pub(crate) fn add_generic_warning_at(&self, message: String, location: Location) {
let source_location = self.create_error_source_location(location);
self.add_warning(Warning::new(
WarningKind::Other(Cow::Owned(message)),
Some(source_location),
));
}
/// Collect a typed warning. Deduplicates against previously collected
/// warnings (PEG backtracking can fire the same warning repeatedly).
pub(crate) fn add_warning(&self, warning: Warning) {
let mut warnings = self.warnings.borrow_mut();
if !warnings.contains(&warning) {
warnings.push(warning);
}
}
/// Collect a warning raised by the inline preprocessor, first resolving its
/// preprocessed location to the originating file + source line (the same
/// mapping the error path uses). The inline preprocessor builds locations with
/// `file: None` and post-splice line numbers; this brings warnings from
/// `include::`d content and after preprocessor edits in line with the resolved
/// AST node locations and the PEG-error path.
pub(crate) fn add_inline_preprocessor_warning(&self, mut warning: Warning) {
if let Some(source_location) = warning.location.take() {
warning.location = Some(self.create_error_source_location(source_location.location));
}
self.add_warning(warning);
}
/// Emit all collected warnings via tracing. Call after parsing
/// completes. Acts as a belt-and-suspenders fallback for callers that
/// ignore the warnings slice on `ParseResult`.
pub(crate) fn emit_warnings(&self) {
for warning in self.warnings.borrow().iter() {
tracing::warn!("{warning}");
}
}
/// Create a `SourceLocation` for an error/warning, resolving the correct
/// file and adjusting line numbers for included content.
pub(crate) fn create_error_source_location(&self, location: Location) -> SourceLocation {
if let Some(range) =
SourceRange::find_containing(&self.source_ranges, location.absolute_start)
{
let file = range.file.clone();
let adjusted_start_line =
self.line_map
.source_line(range, self.input, location.absolute_start);
let adjusted_end_line = self.line_map.source_line(
range,
self.input,
location.absolute_end.min(self.input.len()),
);
SourceLocation {
file,
location: Location {
absolute_start: location.absolute_start,
absolute_end: location.absolute_end,
// The authoritative file for a diagnostic lives on the enclosing
// `SourceLocation`; these positions don't carry it.
start: crate::Position::new(adjusted_start_line, location.start.column),
end: crate::Position::new(adjusted_end_line, location.end.column),
},
}
} else {
SourceLocation {
// Cold path: deep-copy the `Arc<PathBuf>` into the public `Option<PathBuf>`
// (one clone per diagnostic). See `current_file` for why the API isn't widened.
file: self.current_file.as_deref().cloned(),
location,
}
}
}
/// Create a Location from raw byte offsets.
///
/// This method enforces UTF-8 character boundaries:
/// - Clamps offsets to input bounds
/// - Rounds both start and end backward to nearest char boundary
/// - Ensures start <= end
///
/// We round end backward (not forward) because `absolute_end` has inclusive
/// semantics - it represents the last byte of the range, not one past it.
/// When a byte lands mid-character, rounding backward includes that character.
pub(crate) fn create_location(&self, start: usize, end: usize) -> Location {
use crate::grammar::utf8_utils::ensure_char_boundary;
// Clamp to input bounds first
let clamped_start = start.min(self.input.len());
let clamped_end = end.min(self.input.len());
// Ensure UTF-8 boundaries (both round backward for inclusive semantics)
let safe_start = ensure_char_boundary(self.input, clamped_start);
let safe_end = ensure_char_boundary(self.input, clamped_end);
// Ensure start <= end
let safe_end = safe_end.max(safe_start);
let start_pos = self.line_map.offset_to_position(safe_start, self.input);
let end_pos = self.line_map.offset_to_position(safe_end, self.input);
// Positions carry no `file` at construction (the ASG omits the primary file).
// The post-parse remap pass stamps the originating file on `include::`d nodes;
// it only runs when the preprocessor recorded source ranges, which never happens
// without an include/edit, so leaving `file` `None` is correct for the common
// single-file document.
Location {
absolute_start: safe_start,
absolute_end: safe_end,
start: start_pos,
end: end_pos,
}
}
/// Helper to create block location with standard offset calculation.
///
/// Adds `offset` to both start and end, then decrements end by one character
/// (to exclude trailing delimiter/newline). UTF-8 safety is handled by `create_location`.
pub(crate) fn create_block_location(
&self,
start: usize,
end: usize,
offset: usize,
) -> Location {
use crate::grammar::utf8_utils::safe_decrement_offset;
let adjusted_start = start + offset;
let adjusted_end = end + offset;
// Decrement end by one character (safely handling UTF-8)
let final_end = if adjusted_end == 0 {
0
} else {
safe_decrement_offset(self.input, adjusted_end)
};
// create_location handles all UTF-8 boundary enforcement
self.create_location(adjusted_start, final_end)
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
#[allow(clippy::indexing_slicing)]
#[allow(clippy::panic)]
mod tests {
use super::*;
#[test]
fn xref_snapshots_share_unchanged_attributes() {
let arena = Bump::new();
let parent = ParserState::new("", &arena);
let snapshot = parent.capture_xref_caption_labels();
let child = ParserState::for_inline_parsing("", &parent, parent.inline_ctx);
assert_eq!(child.capture_xref_caption_labels(), snapshot);
assert_eq!(parent.capture_xref_caption_labels(), snapshot);
assert!(std::ptr::eq(
parent.xref_signifiers(snapshot).unwrap(),
child.xref_signifiers(snapshot).unwrap(),
));
assert_eq!(
parent.xref_caption_label_snapshots.borrow().entries.len(),
1
);
assert_eq!(Rc::strong_count(&parent.document_attributes), 2);
}
#[test]
fn xref_snapshots_survive_attribute_mutations_and_scope_restoration() {
let arena = Bump::new();
let mut state = ParserState::new("", &arena);
let initial = state.capture_xref_caption_labels();
assert_eq!(Rc::strong_count(&state.document_attributes), 1);
let set_caption = |state: &mut ParserState<'_>, value| {
state
.apply_document_attribute(
&AttributeDeclaration {
name: "example-caption",
value: RawAttributeValue::Text(Cow::Borrowed(value)),
},
false,
state.create_location(0, 0),
)
.unwrap();
};
// Exercise both mutation paths: one owner, then a saved outer scope.
set_caption(&mut state, "Outer");
let outer = state.capture_xref_caption_labels();
assert_ne!(initial, outer);
assert_eq!(state.capture_xref_caption_labels(), outer);
let outer_attributes = Rc::clone(&state.document_attributes);
set_caption(&mut state, "Inner");
let inner = state.capture_xref_caption_labels();
assert_ne!(outer, inner);
state.document_attributes = outer_attributes;
let restored = state.capture_xref_caption_labels();
assert_eq!(state.capture_xref_caption_labels(), restored);
for (snapshot, word) in [
(initial, "Example"),
(outer, "Outer"),
(inner, "Inner"),
(restored, "Outer"),
] {
assert_eq!(
state.xref_caption_label(snapshot, CaptionKind::Example),
XrefCaptionLabel::AtReference(word),
);
}
}
fn warning_kinds(state: &ParserState<'_>) -> Vec<WarningKind> {
state
.warnings
.borrow()
.iter()
.map(|w| w.kind.clone())
.collect()
}
fn other_kind(msg: &'static str) -> WarningKind {
WarningKind::Other(Cow::Borrowed(msg))
}
#[test]
fn add_warning_deduplicates_identical_messages() {
let state = ParserState::new_for_test("test");
state.add_generic_warning("duplicate warning".to_string());
state.add_generic_warning("duplicate warning".to_string());
state.add_generic_warning("duplicate warning".to_string());
let warnings = state.warnings.borrow();
assert_eq!(warnings.len(), 1);
assert_eq!(warnings[0].kind, other_kind("duplicate warning"));
}
#[test]
fn add_warning_preserves_distinct_messages() {
let state = ParserState::new_for_test("test");
state.add_generic_warning("first".to_string());
state.add_generic_warning("second".to_string());
state.add_generic_warning("third".to_string());
assert_eq!(state.warnings.borrow().len(), 3);
}
#[test]
fn add_warning_preserves_insertion_order() {
let state = ParserState::new_for_test("test");
state.add_generic_warning("beta".to_string());
state.add_generic_warning("alpha".to_string());
state.add_generic_warning("beta".to_string());
state.add_generic_warning("gamma".to_string());
assert_eq!(
warning_kinds(&state),
vec![other_kind("beta"), other_kind("alpha"), other_kind("gamma"),],
);
}
#[test]
fn add_warning_is_shared_across_inline_subparses() {
// `for_inline_parsing` must share the parent's warnings store so
// a warning raised inside a substituted author/revision/inline
// sub-parse reaches the outer `ParseResult`.
let parent = ParserState::new_for_test("parent input");
parent.add_generic_warning("from parent".to_string());
{
let child = ParserState::for_inline_parsing("child input", &parent, parent.inline_ctx);
child.add_generic_warning("from child".to_string());
}
let kinds = warning_kinds(&parent);
assert_eq!(kinds.len(), 2);
assert!(kinds.contains(&other_kind("from parent")));
assert!(kinds.contains(&other_kind("from child")));
}
#[test]
#[tracing_test::traced_test]
fn emit_warnings_outputs_via_tracing() {
let state = ParserState::new_for_test("test");
state.add_generic_warning("warning one".to_string());
state.add_generic_warning("warning two".to_string());
state.emit_warnings();
assert!(logs_contain("warning one"));
assert!(logs_contain("warning two"));
}
#[test]
fn create_error_source_location_resolves_included_file() {
use crate::model::SourceRange;
// Simulate: main file "line1\n", included file "inc_line1\ninc_line2\n"
let input = "line1\ninc_line1\ninc_line2\n";
let mut state = ParserState::new_for_test(input);
state.current_file = Some(PathBuf::from("main.adoc").into());
state.source_ranges.push(SourceRange {
start_offset: 6, // "inc_line1\n..." starts at byte 6
end_offset: 25,
file: Some(PathBuf::from("/tmp/included.adoc")),
file_chain: vec!["included.adoc".to_string()],
start_line: 1,
source_start_offset: 0,
column_shift: 0,
});
// Location inside the included range (second line of include: "inc_line2")
let loc = state.create_location(16, 24); // "inc_line2"
let src_loc = state.create_error_source_location(loc);
assert_eq!(src_loc.file, Some(PathBuf::from("/tmp/included.adoc")));
// From start_offset=6 to absolute_start=16, there's 1 newline ("inc_line1\n")
// So start_line = 1 + 1 = 2
assert_eq!(src_loc.location.start.line, 2);
}
#[test]
fn create_error_source_location_falls_back_to_current_file() {
let input = "main content\n";
let mut state = ParserState::new_for_test(input);
state.current_file = Some(PathBuf::from("main.adoc").into());
// No source ranges
let loc = state.create_location(0, 11);
let src_loc = state.create_error_source_location(loc.clone());
assert_eq!(src_loc.file, Some(PathBuf::from("main.adoc")));
assert_eq!(src_loc.location.start.line, loc.start.line);
assert_eq!(src_loc.location.end.line, loc.end.line);
}
}