Skip to main content

asciidoc_parser/parser/
parser.rs

1use std::{
2    borrow::Cow,
3    cell::{Cell, RefCell},
4    collections::{HashMap, HashSet},
5    rc::Rc,
6    sync::{Arc, LazyLock},
7};
8
9use regex::Regex;
10
11use crate::{
12    Document, HasSpan,
13    blocks::{SectionNumber, SectionType},
14    document::{Attribute, Catalog, InterpretedValue, RefType},
15    parser::{
16        AllowableValue, AttributeValue, DatetimeContext, DefaultPathResolver, DocinfoFileHandler,
17        HtmlSubstitutionRenderer, ImageFileHandler, IncludeFileHandler, InlineSubstitutionRenderer,
18        ModificationContext, PathResolver, ReferenceTime, ResolvedAttributes, SafeMode, SourceLine,
19        SourceMap, SvgFileHandler,
20        built_in_attrs::{
21            built_in_attr, built_in_default_values, derived_backend_value,
22            is_derived_backend_value, max_attribute_value_size_default, synthesized_attr,
23            user_home_default,
24        },
25        is_datetime_attribute,
26        preprocessor::preprocess,
27        safe_mode::masked_doc_path,
28    },
29    warnings::{Warning, WarningType},
30};
31
32/// The [`Parser`] struct and its related structs allow a caller to configure
33/// how AsciiDoc parsing occurs and then to initiate the parsing process.
34#[derive(Clone, Debug)]
35pub struct Parser {
36    /// Per-parser attribute values: **only** the attributes this parser has
37    /// defined, overridden, or explicitly unset. The large set of built-in
38    /// defaults is *not* copied in here; [`attribute_value`] falls back to the
39    /// shared built-in table (see [`built_in_attrs`]) on a lookup miss, so
40    /// creating or cloning a parser allocates nothing per built-in attribute.
41    ///
42    /// A per-parser entry always shadows the built-in default of the same name,
43    /// including an [`Unset`](InterpretedValue::Unset) tombstone that records a
44    /// built-in having been unset. The map is wrapped in an [`Arc`] so a parser
45    /// clone (e.g. for a nested AsciiDoc table cell) shares it copy-on-write
46    /// and only copies these (few) entries when it next modifies an
47    /// attribute.
48    ///
49    /// [`attribute_value`]: Self::attribute_value
50    /// [`built_in_attrs`]: super::built_in_attrs
51    pub(crate) attribute_values: Arc<HashMap<String, AttributeValue>>,
52
53    /// The configured baseline of [`attribute_values`](Self::attribute_values):
54    /// a snapshot of the API-established attributes as of the last builder
55    /// call, with none of the attributes a document discovers during
56    /// parsing.
57    ///
58    /// [`parse_deferred`](Self::parse_deferred) restores
59    /// [`attribute_values`](Self::attribute_values) from this at the start of
60    /// every parse, so a `Parser` reused across documents returns to its
61    /// configured baseline between parses rather than leaking one document's
62    /// header assignments into the next. It is refreshed (by
63    /// [`capture_attribute_baseline`](Self::capture_attribute_baseline)) after
64    /// each attribute-configuring builder call, so reconfiguring a `Parser`
65    /// between parses is honored. Shared via [`Arc`] copy-on-write for the same
66    /// reason as [`attribute_values`](Self::attribute_values), so tracking it
67    /// costs only an `Arc` clone.
68    ///
69    /// [`attribute_values`]: Self::attribute_values
70    pub(crate) baseline_attribute_values: Arc<HashMap<String, AttributeValue>>,
71
72    /// Default values for attributes if "set." Immutable after construction and
73    /// shared via [`Arc`] (never copied per parser).
74    default_attribute_values: Arc<HashMap<String, String>>,
75
76    /// Specifies how the basic raw text of a simple block will be converted to
77    /// the format which will ultimately be presented in the final output.
78    ///
79    /// Typically this is an [`HtmlSubstitutionRenderer`] but clients may
80    /// provide alternative implementations.
81    pub(crate) renderer: Rc<dyn InlineSubstitutionRenderer>,
82
83    /// Specifies the name of the primary file to be parsed.
84    pub(crate) primary_file_name: Option<String>,
85
86    /// Specifies how to generate clean and secure paths relative to the parsing
87    /// context.
88    ///
89    /// Defaults to [`DefaultPathResolver`]; a host can substitute custom
90    /// path/URL rewriting via
91    /// [`with_path_resolver`](Self::with_path_resolver).
92    pub(crate) path_resolver: Rc<dyn PathResolver>,
93
94    /// Handler for resolving include:: directives.
95    pub(crate) include_file_handler: Option<Rc<dyn IncludeFileHandler>>,
96
97    /// Handler for resolving docinfo files. If absent, no docinfo content is
98    /// resolved.
99    pub(crate) docinfo_file_handler: Option<Rc<dyn DocinfoFileHandler>>,
100
101    /// Handler for reading the contents of an SVG file requested by an inline
102    /// image with the `inline` option. If absent, inline SVG images fall back
103    /// to rendering their alt text.
104    pub(crate) svg_file_handler: Option<Rc<dyn SvgFileHandler>>,
105
106    /// Handler for reading the bytes of an image file that must be embedded as
107    /// a `data:` URI (when the `data-uri` attribute is set below
108    /// [`SafeMode::Secure`]). If absent, such images fall back to an ordinary
109    /// web path.
110    pub(crate) image_file_handler: Option<Rc<dyn ImageFileHandler>>,
111
112    /// Whether referenced images are recorded in the document catalog as they
113    /// are encountered (Asciidoctor's `catalog_assets` API option). When
114    /// `false` (the default), the `image:`/`image::` macros do not populate
115    /// [`Catalog::images`](crate::document::Catalog::images).
116    pub(crate) catalog_assets: bool,
117
118    /// The safe mode under which the document is parsed and rendered. Controls
119    /// security-sensitive rendering behavior (such as whether an interactive
120    /// SVG image is rendered as an `<object>` element). Defaults to
121    /// [`SafeMode::Secure`].
122    pub(crate) safe: SafeMode,
123
124    /// Document catalog for tracking referenceable elements during parsing.
125    /// This is created during parsing and transferred to the Document when
126    /// complete.
127    ///
128    /// Wrapped in a [`RefCell`] so that anchors and references discovered deep
129    /// inside inline substitution (where only a shared `&Parser` is available,
130    /// e.g. within a regex [`Replacer`](regex::Replacer)) can still be
131    /// registered.
132    catalog: RefCell<Catalog>,
133
134    /// Most recently-assigned section number.
135    pub(crate) last_section_number: SectionNumber,
136
137    /// Most recently-assigned appendix section number.
138    pub(crate) last_appendix_section_number: SectionNumber,
139
140    /// Saved copy of sectnumlevels at end of document header.
141    pub(crate) sectnumlevels: usize,
142
143    /// Section type of outermost section. (Used to determine whether to number
144    /// child sections as a normal section or appendix.)
145    pub(crate) topmost_section_type: SectionType,
146
147    /// True while parsing the direct block children of a section that carries
148    /// the `bibliography` style.
149    ///
150    /// A top-level unordered list parsed in this scope implicitly inherits the
151    /// `bibliography` style (matching Asciidoctor), even without its own
152    /// `[bibliography]` attribute. The flag is saved and restored around each
153    /// section body, so a non-bibliography subsection clears it for its own
154    /// children (the style does not propagate into subsections).
155    pub(crate) parsing_bibliography_section_body: bool,
156
157    /// True while parsing the body of a delimited block (an example, sidebar,
158    /// or open block, a quote block, or a Markdown-style blockquote).
159    ///
160    /// A section heading is only recognized at the document top level or within
161    /// another section's body. Inside a delimited block a `== …` line is
162    /// literal content – a paragraph – not a section (matching Asciidoctor,
163    /// which only creates sections when the parent context is the document
164    /// or a section). A discrete heading, by contrast, is an ordinary block
165    /// and remains valid in these contexts, so it is not suppressed by this
166    /// flag. The flag is saved and restored around each delimited-block body so
167    /// nesting is handled correctly. An AsciiDoc table cell is a nested
168    /// document
169    /// (see [`nested_document_depth`](Self::nested_document_depth)) where
170    /// sections are again allowed, so the cell parse clears this flag (also
171    /// saved and restored) rather than inheriting a delimited-block context
172    /// from a table that happens to sit inside one.
173    pub(crate) in_delimited_block: bool,
174
175    /// True while the principal text of a bibliography list item is being
176    /// substituted.
177    ///
178    /// Read through a shared `&Parser` by the macros substitution step so it
179    /// recognizes a leading bibliography anchor (`[[[id]]]`). It is wrapped in
180    /// a [`Cell`] because the substitution code paths (e.g. a regex
181    /// [`Replacer`](regex::Replacer)) only hold a shared reference to the
182    /// parser.
183    pub(crate) in_bibliography_list_item: Cell<bool>,
184
185    /// True while a section title is being substituted, so each `footnote:[…]`
186    /// macro's rendered marker is bracketed with
187    /// [`FOOTNOTE_MARKER_START`](crate::content::FOOTNOTE_MARKER_START) /
188    /// [`FOOTNOTE_MARKER_END`](crate::content::FOOTNOTE_MARKER_END) sentinels.
189    /// The footnote is still defined and numbered in document order; the
190    /// sentinels merely let the marker be excised from the section's reference
191    /// text and auto-generated ID without a second substitution pass (see
192    /// `SectionBlock::parse`).
193    ///
194    /// Wrapped in a [`Cell`] for the same reason as
195    /// [`in_bibliography_list_item`](Self::in_bibliography_list_item): the
196    /// substitution code paths hold only a shared reference to the parser.
197    pub(crate) mark_footnote_spans: Cell<bool>,
198
199    /// A block title carried over from a section heading to the first block
200    /// parsed after it.
201    ///
202    /// A block title above a section heading does not title the section; it is
203    /// carried over to the first block inside the section (matching
204    /// Asciidoctor, where the block-attribute hash holding the title is passed
205    /// through to the section body's first block). `SectionBlock::parse`
206    /// stashes the rendered title here and the next block parsed claims it –
207    /// which may be a nested section, re-stashing it for *its* first block, or
208    /// (when the section body is empty) a sibling section reached after the
209    /// stashing section ends. A block with a title of its own wins over the
210    /// carried title, which is then discarded.
211    ///
212    /// The title is carried as an owned snapshot (this struct is lifetime-free
213    /// and cannot hold the `.Title` line's source span), so a block claiming a
214    /// carried title has no `title_source` – the same shape as a title
215    /// supplied via a `title=` attribute. The snapshot keeps any deferred
216    /// cross-references, so an embedded `<<id>>` in a carried title still
217    /// resolves once the catalog is complete.
218    pub(crate) pending_block_title: Option<crate::content::OwnedTitle>,
219
220    /// Live values of [counter] attributes, keyed by counter name (e.g.
221    /// `index`, `example-number`, `table-number`).
222    ///
223    /// A counter is a specialized document attribute: its value is *also* the
224    /// value of the document attribute of the same name. Counters are resolved
225    /// (and advanced) deep inside the attribute-reference substitution step,
226    /// where only a shared `&Parser` is available, so the new value is recorded
227    /// here through a [`RefCell`] and read back as an attribute by
228    /// [`attribute_value()`]. An explicit attribute assignment to a counter's
229    /// name supersedes this overlay (and is what allows `:!name:` to reset a
230    /// counter), so every attribute setter clears the matching entry.
231    ///
232    /// Captioned blocks (example, table, …) are numbered with this same
233    /// mechanism: each context's caption number is the counter named
234    /// `<context>-number`, mirroring Asciidoctor's `Document#counter`.
235    ///
236    /// [counter]: https://docs.asciidoctor.org/asciidoc/latest/attributes/counters/
237    /// [`attribute_value()`]: Self::attribute_value
238    pub(crate) counter_values: RefCell<HashMap<String, String>>,
239
240    /// Running state for inline `{counter:…}` / `{counter2:…}` counters whose
241    /// target attribute is *locked* (API-set or a locked built-in).
242    ///
243    /// Such a counter must keep advancing across repeated references, but it
244    /// must not overwrite the locked attribute's readable value – so its
245    /// sequence is tracked here rather than in the readable
246    /// [`counter_values`](Self::counter_values) overlay. This mirrors
247    /// Asciidoctor's `Document#counter`, which advances `@counters` while
248    /// leaving `@attributes` untouched for a locked attribute (see
249    /// [`counter_impl`](Self::counter_impl)). A captioning counter is exempt:
250    /// its value is committed to the readable overlay even when locked.
251    ///
252    /// Accepted limitation: a locked inline counter tracks its sequence here
253    /// while a captioning counter tracks it in
254    /// [`counter_values`](Self::counter_values), so the two sequences diverge
255    /// when the *same* locked attribute is advanced both ways in one document
256    /// (e.g. an API-locked `example-number` driven by both example blocks and
257    /// inline `{counter:example-number}` references) – Asciidoctor keeps a
258    /// single `@counters` sequence shared across both. This is left unmatched
259    /// deliberately. The scenario – API-locking a `<context>-number` attribute
260    /// *and* mixing caption and inline use – is pathological, and exact parity
261    /// is unreachable regardless: this crate resolves inline counters during
262    /// parsing, whereas Asciidoctor advances captions during parsing but inline
263    /// references during conversion, so the two sequences interleave
264    /// differently no matter how the state is stored. Unifying the maps would
265    /// therefore add read-path complexity (the gate would have to be threaded
266    /// through [`ResolvedAttributes`] too) without actually matching
267    /// Asciidoctor's output here.
268    pub(crate) locked_counter_values: RefCell<HashMap<String, String>>,
269
270    /// Canonical names of attributes that are locked against modification from
271    /// the document body for the current scope.
272    ///
273    /// An AsciiDoc table cell creates a nested document that inherits the
274    /// parent document's attributes. An attribute that is *set* in the
275    /// parent _cannot_ be modified inside the cell (matching Asciidoctor,
276    /// which here diverges from the spec's "set or explicitly unset" wording),
277    /// so while a cell is being parsed every inherited attribute name
278    /// (other than a handful of exceptions) is recorded here and a body
279    /// attribute assignment to such a name is silently ignored. The set is
280    /// saved and restored around each cell, so the lock applies only within
281    /// the cell (and nests correctly).
282    ///
283    /// The overwhelming majority of locked names are built-in attributes, whose
284    /// names are already `&'static str`, so entries are stored as
285    /// [`Cow<'static, str>`]: a built-in is locked with a borrowed static name
286    /// (no allocation), and only a genuinely dynamic (parent-defined) name is
287    /// owned. This keeps the per-cell rebuild – which runs once for every
288    /// AsciiDoc cell – from allocating a `String` per built-in attribute.
289    pub(crate) locked_attribute_names: HashSet<Cow<'static, str>>,
290
291    /// Number of AsciiDoc table cells currently being parsed in the call stack.
292    ///
293    /// An AsciiDoc table cell creates a nested, standalone AsciiDoc document.
294    /// While that document is being parsed this counter is greater than zero,
295    /// which (matching Asciidoctor's `Document#nested?`) changes the default
296    /// cell separator of any table found inside from the vertical bar (`|`) to
297    /// the exclamation mark (`!`), so a nested table needs no explicit
298    /// `separator` attribute. The counter is incremented and decremented around
299    /// each AsciiDoc cell, so it nests correctly.
300    pub(crate) nested_document_depth: usize,
301
302    /// Number of privately-owned sub-sources currently being parsed in the call
303    /// stack.
304    ///
305    /// A Markdown-style blockquote and an AsciiDoc table cell parse their
306    /// blocks from an owned source string whose byte offsets do not map to
307    /// the primary document source. A footnote defined while such a
308    /// sub-source is being substituted therefore cannot record a
309    /// document-relative location for its cross-reference warning;
310    /// `define_footnote` reads this counter to detect that case and leave
311    /// the location unset (see
312    /// [`Footnote::location`](crate::document::Footnote)). It is incremented
313    /// and decremented around each owned sub-source parse, so it nests
314    /// correctly.
315    ///
316    /// Unlike [`nested_document_depth`](Self::nested_document_depth), this also
317    /// counts Markdown-style blockquotes (which are not nested documents), so
318    /// the two cannot be merged.
319    pub(crate) owned_subsource_depth: usize,
320
321    /// Number of nested block-parsing scopes currently open on the call stack.
322    ///
323    /// Every level of block nesting – a delimited block's body, a section body,
324    /// an AsciiDoc table cell, a nested list – is parsed by a fresh recursive
325    /// descent (through [`parse_blocks_until`] or
326    /// [`ListBlock::parse_inside_list`]) that consumes native stack. Without a
327    /// bound, a small crafted document (strictly-increasing delimiters, or
328    /// deeply-nested list markers) drives arbitrarily deep recursion and
329    /// overflows the stack – an *uncatchable* abort that takes down the whole
330    /// host process, not just the parse. This counter is incremented on entry
331    /// to each such scope and decremented on exit; when it would exceed
332    /// [`max_block_nesting`](Self::max_block_nesting) the over-nested content
333    /// is truncated with a [`MaxBlockNestingExceeded`] warning instead of
334    /// being descended into (see issue #885).
335    ///
336    /// [`parse_blocks_until`]: crate::blocks::parse_utils::parse_blocks_until
337    /// [`ListBlock::parse_inside_list`]: crate::blocks::ListBlock
338    /// [`MaxBlockNestingExceeded`]:
339    /// crate::warnings::WarningType::MaxBlockNestingExceeded
340    pub(crate) block_nesting_depth: usize,
341
342    /// The block-nesting cap ([`max_block_nesting`](Self::max_block_nesting))
343    /// resolved once per document, so the guard consulted on *every*
344    /// [`parse_blocks_until`] scope entry is a plain integer compare rather
345    /// than a document-attribute lookup (a `RefCell` borrow, several map
346    /// lookups, a string clone, and a parse) on that hot path.
347    ///
348    /// `max-block-nesting` is API-only, so its value cannot change mid-parse;
349    /// [`parse_deferred`](Self::parse_deferred) refreshes this from the
350    /// resolved attribute at the start of each parse. It is seeded with the
351    /// built-in default so a block parser invoked directly in a unit test
352    /// (bypassing `parse_deferred`) still sees the right cap.
353    ///
354    /// [`parse_blocks_until`]: crate::blocks::parse_utils::parse_blocks_until
355    pub(crate) block_nesting_limit: usize,
356
357    /// Source map of the document currently being parsed, populated by
358    /// [`Document::parse`] for the duration of the parse (and `None` outside
359    /// it).
360    ///
361    /// Block parsing works from the *preprocessed* source, so a span's line
362    /// number is relative to that flattened source rather than to the original
363    /// input file(s). An AsciiDoc table cell whose first line is an `include::`
364    /// directive re-runs the preprocessor over the cell's content: to report an
365    /// unresolved directive against the file and line where it *originally*
366    /// appeared (rather than "(root file)"), the cell must map its position in
367    /// the preprocessed source back through this map. It is only consulted
368    /// while parsing the top-level document (`nested_document_depth == 0`),
369    /// where a cell's span still refers to that source.
370    ///
371    /// [`Document::parse`]: crate::Document
372    pub(crate) source_map: Option<Rc<SourceMap>>,
373
374    /// Stack of source maps for the include-expanded (owned) AsciiDoc table
375    /// cells currently being parsed in the call stack (innermost last).
376    ///
377    /// An AsciiDoc cell whose first line is an `include::` directive is parsed
378    /// from a private, preprocessor-expanded copy of its content rather than
379    /// from the document source. While that owned copy is being parsed a span's
380    /// line number no longer indexes the document
381    /// [`source_map`](Self::source_map); it indexes the owned copy instead.
382    /// Each owned cell's own source map (produced by re-running the
383    /// preprocessor over its content) is pushed here for the duration of
384    /// its parse, so a directive buried inside the owned content can still
385    /// be mapped back to the file and line it *originally* came from –
386    /// needed to name that file in the "Unresolved directive" message and
387    /// to report the warning's true cursor via
388    /// [`Warning::origin`](crate::warnings::Warning::origin).
389    ///
390    /// The stack is empty while parsing the top-level document (and while
391    /// parsing a *borrowed* cell, which keeps document spans). It is non-empty
392    /// exactly when a span's line indexes an owned copy rather than the
393    /// document, which the source-map lookup uses to decide which map to
394    /// consult. It is pushed and popped around each owned-cell parse, so it
395    /// nests correctly.
396    pub(crate) owned_cell_source_maps: Vec<Rc<SourceMap>>,
397
398    /// Warnings raised by an `include::` directive buried inside an owned
399    /// (include-expanded) AsciiDoc table cell, each already resolved to the
400    /// `(file, line)` where the directive originally appeared.
401    ///
402    /// Such a warning is raised deep inside the owned cell's parse, where the
403    /// only spans available borrow the owned copy and cannot escape it, and no
404    /// document span maps to the directive. It is therefore recorded here (in a
405    /// lifetime-free, pre-resolved form) and drained once an enclosing
406    /// document-level cell can anchor it to a real document span while carrying
407    /// its true origin (see
408    /// [`Warning::origin`](crate::warnings::Warning::origin)).
409    ///
410    /// Wrapped in a [`RefCell`] only for symmetry with the other deferred
411    /// warning buffers; it is mutated through `&mut self`-free helpers so the
412    /// owned-cell parse (which holds the parser mutably) can still record into
413    /// it from within a `self_cell` construction closure.
414    owned_cell_warnings: RefCell<Vec<ResolvedWarning>>,
415
416    /// Catalog of callout numbers registered by verbatim blocks, used to
417    /// validate the callout lists that annotate them.
418    ///
419    /// Wrapped in a [`RefCell`] because callouts are registered deep inside the
420    /// callouts substitution step, where only a shared `&Parser` is available.
421    callouts: RefCell<CalloutCatalog>,
422
423    /// Warnings produced while replacing attribute references (e.g. a reference
424    /// to a missing attribute when `attribute-missing` is `warn`).
425    ///
426    /// Wrapped in a [`RefCell`] because attribute references are replaced deep
427    /// inside the attributes substitution step, where only a shared `&Parser`
428    /// is available. Each entry stores the byte offset and length of the source
429    /// span the warning refers to (rather than a borrowed
430    /// [`Span`](crate::Span), which the lifetime-free `Parser` cannot
431    /// hold), so the warnings can be turned into
432    /// spanned [`Warning`]s once the document's owned source is available.
433    substitution_warnings: RefCell<Vec<DeferredWarning>>,
434
435    /// An optional fixed reference time that pins the clock used to compute the
436    /// time-dependent document attributes (`docdate`, `doctime`, `docdatetime`,
437    /// `docyear`, and their `local*` siblings), for reproducible output.
438    ///
439    /// When set, it supersedes both the real wall clock and the
440    /// `SOURCE_DATE_EPOCH` environment variable as the value of "now" (which
441    /// drives the `local*` attributes and, absent an [`input_mtime`], the
442    /// `doc*` attributes too). See [`with_reference_time`] and
443    /// [`resolve_datetime_attribute`].
444    ///
445    /// [`input_mtime`]: Self::input_mtime
446    /// [`with_reference_time`]: Self::with_reference_time
447    /// [`resolve_datetime_attribute`]: Self::resolve_datetime_attribute
448    reference_time: Option<ReferenceTime>,
449
450    /// An optional fixed modification time of the source document, pinning the
451    /// clock that drives the `doc*` attributes (`docdate`, `doctime`,
452    /// `docdatetime`, `docyear`) specifically.
453    ///
454    /// This mirrors Asciidoctor's `input_mtime` option: the `local*` attributes
455    /// continue to track "now", while the `doc*` attributes reflect this source
456    /// modification time. See [`with_input_mtime`] and
457    /// [`resolve_datetime_attribute`].
458    ///
459    /// [`with_input_mtime`]: Self::with_input_mtime
460    /// [`resolve_datetime_attribute`]: Self::resolve_datetime_attribute
461    input_mtime: Option<ReferenceTime>,
462
463    /// The reference instants used to compute the time-dependent document
464    /// attributes, captured lazily the first time one of those attributes is
465    /// read during a parse (and reset at the start of each parse).
466    ///
467    /// The time-dependent attributes are *not* materialized into
468    /// [`attribute_values`](Self::attribute_values); instead they are resolved
469    /// on demand from this context (see
470    /// [`resolve_datetime_attribute`](Self::resolve_datetime_attribute)). A
471    /// parse that never references one therefore does no clock, environment, or
472    /// allocation work for them, and repeated reads within a parse observe a
473    /// single consistent instant.
474    ///
475    /// Wrapped in a [`RefCell`] because the capture happens through the shared
476    /// `&Parser` attribute readers (which the substitution code paths reach
477    /// with only a shared reference).
478    datetime_context: RefCell<Option<DatetimeContext>>,
479}
480
481/// A warning recorded in a form that does not borrow the source so it can live
482/// on the [`Parser`] (or be returned from preprocessing), to be reconstituted
483/// into a spanned [`Warning`] once the document's owned source is available.
484///
485/// This is used both for warnings raised while replacing attribute references
486/// and for warnings raised during preprocessing (e.g. an unresolved include
487/// directive). The `offset`/`len` pair locates the relevant text within the
488/// (preprocessed) document source.
489#[derive(Clone, Debug)]
490pub(crate) struct DeferredWarning {
491    /// Byte offset into the document source of the span this warning refers to.
492    pub(crate) offset: usize,
493
494    /// Byte length of the span this warning refers to.
495    pub(crate) len: usize,
496
497    /// The type of warning, already carrying any owned data it needs (such as
498    /// the missing attribute's name).
499    pub(crate) warning: WarningType,
500
501    /// A pre-resolved originating `(file, line)` for this warning, carried
502    /// through to [`Warning::origin`].
503    ///
504    /// This is `None` for warnings that point at real (emitted) output: their
505    /// [`offset`](Self::offset)/[`len`](Self::len) span resolves the location
506    /// through the document source map. It is `Some` for a preprocessor
507    /// directive that produces no output of its own – a malformed or
508    /// unterminated conditional directive – where there is no output span to
509    /// resolve against, so the directive's own file and line are recorded here
510    /// directly (the `offset`/`len` span is then only a best-effort anchor).
511    ///
512    /// [`Warning::origin`]: crate::warnings::Warning::origin
513    pub(crate) origin: Option<SourceLine>,
514}
515
516/// A warning whose location is already resolved to an originating
517/// `(file, line)`, independent of any source map.
518///
519/// Used for a warning raised inside an owned (include-expanded) AsciiDoc table
520/// cell, whose directive never appears in the document source: it is resolved
521/// against the owning cell's own source map when raised, then carried in this
522/// form until an enclosing document-level cell can surface it (see
523/// [`Parser::owned_cell_warnings`]).
524#[derive(Clone, Debug)]
525pub(crate) struct ResolvedWarning {
526    /// The originating file and line where the directive appeared.
527    pub(crate) origin: SourceLine,
528
529    /// The type of warning, already carrying any owned data it needs (such as
530    /// the missing include target).
531    pub(crate) warning: WarningType,
532}
533
534/// Tracks the callout numbers defined by verbatim blocks so that a callout list
535/// can be validated against the callouts it annotates.
536///
537/// This mirrors the relevant behavior of Asciidoctor's `Callouts` catalog: each
538/// verbatim block registers the callout numbers it defines into the current
539/// list, and each callout list checks its items against that list (warning
540/// about any item with no matching callout) before the list is closed.
541#[derive(Clone, Debug, Default)]
542struct CalloutCatalog {
543    /// Callout numbers registered (in document order) since the last callout
544    /// list was closed.
545    current: Vec<u32>,
546}
547
548impl Default for Parser {
549    fn default() -> Self {
550        Self {
551            // Starts empty: built-in defaults are resolved on the fly via the
552            // shared table (see `attribute_value`), not copied in per parser.
553            attribute_values: Arc::new(HashMap::new()),
554            baseline_attribute_values: Arc::new(HashMap::new()),
555            default_attribute_values: built_in_default_values(),
556            renderer: Rc::new(HtmlSubstitutionRenderer {}),
557            primary_file_name: None,
558            path_resolver: Rc::new(DefaultPathResolver::default()),
559            include_file_handler: None,
560            docinfo_file_handler: None,
561            svg_file_handler: None,
562            image_file_handler: None,
563            catalog_assets: false,
564            safe: SafeMode::default(),
565            catalog: RefCell::new(Catalog::new()),
566            last_section_number: SectionNumber::default(),
567            last_appendix_section_number: SectionNumber {
568                section_type: SectionType::Appendix,
569                components: vec![],
570                appendix_letter: None,
571            },
572            sectnumlevels: 3,
573            topmost_section_type: SectionType::Normal,
574            parsing_bibliography_section_body: false,
575            in_delimited_block: false,
576            in_bibliography_list_item: Cell::new(false),
577            mark_footnote_spans: Cell::new(false),
578            pending_block_title: None,
579            counter_values: RefCell::new(HashMap::new()),
580            locked_counter_values: RefCell::new(HashMap::new()),
581            locked_attribute_names: HashSet::new(),
582            nested_document_depth: 0,
583            owned_subsource_depth: 0,
584            block_nesting_depth: 0,
585            block_nesting_limit: Self::DEFAULT_MAX_BLOCK_NESTING,
586            source_map: None,
587            owned_cell_source_maps: vec![],
588            owned_cell_warnings: RefCell::new(vec![]),
589            callouts: RefCell::new(CalloutCatalog::default()),
590            substitution_warnings: RefCell::new(vec![]),
591            reference_time: None,
592            input_mtime: None,
593            datetime_context: RefCell::new(None),
594        }
595    }
596}
597
598impl Parser {
599    /// The default value of [`max_block_nesting`](Self::max_block_nesting),
600    /// mirroring the `max-block-nesting` built-in default (see
601    /// [`built_in_attrs`](super::built_in_attrs)).
602    pub(crate) const DEFAULT_MAX_BLOCK_NESTING: usize = 32;
603
604    /// Creates a new [`Parser`] with the default configuration.
605    ///
606    /// This is equivalent to [`Parser::default()`](Self::default) and is
607    /// provided for discoverability. Configure the parser by chaining the
608    /// `with_*` builder methods, then call [`parse()`](Self::parse).
609    #[must_use]
610    pub fn new() -> Self {
611        Self::default()
612    }
613
614    /// Parse a UTF-8 string as an AsciiDoc document.
615    ///
616    /// The [`Document`] data structure returned by this call has a '`static`
617    /// lifetime; this is an implementation detail. It retains a copy of the
618    /// `source` string that was passed in, but it is not tied to the lifetime
619    /// of that string.
620    ///
621    /// Nearly all of the data structures contained within the [`Document`]
622    /// structure are tied to the lifetime of the document and have a `'src`
623    /// lifetime to signal their dependency on the source document.
624    ///
625    /// **IMPORTANT:** The AsciiDoc language documentation states that UTF-16
626    /// encoding is allowed if a byte-order-mark (BOM) is present at the
627    /// start of a file. This format is not directly supported by the
628    /// `asciidoc-parser` crate. Any UTF-16 content must be re-encoded as
629    /// UTF-8 prior to parsing.
630    ///
631    /// The `Parser` struct will be updated with document attribute values
632    /// discovered during parsing. These values may be inspected using
633    /// [`attribute_value()`] after this call returns.
634    ///
635    /// # Reusing a `Parser` across documents
636    ///
637    /// A single `Parser` may be reused to parse many documents (in a loop, for
638    /// example). Each parse begins from the `Parser`'s configured baseline –
639    /// the attributes established through the builder API (e.g.
640    /// [`with_intrinsic_attribute()`]) – with the document attributes
641    /// discovered while parsing the *previous* document cleared.
642    /// Header/body assignments (`:foo: bar`) therefore do not leak from one
643    /// document into the next, so output does not depend on parse order.
644    /// (Attributes discovered by a parse remain inspectable per the paragraph
645    /// above only until the next parse, which clears them back to the
646    /// baseline.) Reconfiguring the `Parser` with a builder method between
647    /// parses updates that baseline for all subsequent parses.
648    ///
649    /// [`with_intrinsic_attribute()`]: Self::with_intrinsic_attribute
650    ///
651    /// # Warnings, not errors
652    ///
653    /// Any UTF-8 string is a valid AsciiDoc document, so this function does not
654    /// return an [`Option`] or [`Result`] data type. There may be any number of
655    /// character sequences that have ambiguous or potentially unintended
656    /// meanings. For that reason, a caller is advised to review the warnings
657    /// provided via the [`warnings()`] iterator.
658    ///
659    /// [`warnings()`]: Document::warnings
660    /// [`attribute_value()`]: Self::attribute_value
661    #[must_use]
662    pub fn parse(&mut self, source: &str) -> Document<'static> {
663        let mut document = self.parse_deferred(source);
664
665        // Resolve cross-references against this document's own catalog. For
666        // multi-document workflows, use `parse_deferred` and resolve later with
667        // a caller-supplied resolver via `Document::resolve_references`.
668        document.resolve_against_own_catalog(&*self.renderer);
669
670        document
671    }
672
673    /// Parse a UTF-8 string as an AsciiDoc document, leaving cross-references
674    /// unresolved.
675    ///
676    /// This behaves like [`parse()`], except it does not resolve
677    /// cross-references (`<<id>>`, `xref:id[…]`). The returned [`Document`]
678    /// carries its references in a deferred state; resolve them later with
679    /// [`Document::resolve_references`].
680    ///
681    /// This is the entry point for multi-document workflows (e.g. Antora-style
682    /// site generation): parse every document with this method, build a
683    /// combined index from each document's [`catalog()`], then resolve each
684    /// document against that index. This crate does not merge catalogs
685    /// itself.
686    ///
687    /// [`parse()`]: Self::parse
688    /// [`catalog()`]: Document::catalog
689    #[must_use]
690    pub fn parse_deferred(&mut self, source: &str) -> Document<'static> {
691        // Restore the configured attribute baseline so a `Parser` reused across
692        // documents does not carry one document's header/body assignments into
693        // the next (which would make conditional-include, substitution, and
694        // section-numbering behavior order-dependent). This must precede front-
695        // matter handling and preprocessing below, both of which read document
696        // attributes. See `baseline_attribute_values`.
697        self.attribute_values = Arc::clone(&self.baseline_attribute_values);
698
699        // The time-dependent document attributes (docdate, doctime, docdatetime,
700        // docyear, and their local* siblings) are resolved lazily from a
701        // reference instant captured the first time one is read (see
702        // `resolve_datetime_attribute`). Reset that capture so each parse sees a
703        // fresh "now"; a parse that never references one does no datetime work.
704        *self.datetime_context.borrow_mut() = None;
705
706        // Strip a leading UTF-8 byte-order mark (U+FEFF), which is valid but
707        // non-content in a UTF-8 document. Left in place it becomes the first
708        // character of the first line and defeats header, front-matter, and
709        // section recognition (e.g. a leading `= ` title), silently misparsing
710        // the document. Asciidoctor strips it likewise. This is independent of
711        // UTF-16 transcoding, which remains out of scope; it handles only the
712        // UTF-8 encoding of the mark. This must precede front-matter handling
713        // and preprocessing, both of which key off the first line.
714        let source = source.strip_prefix('\u{feff}').unwrap_or(source);
715
716        // Drop leading YAML-style front matter (and record it in the
717        // `front-matter` attribute) when `skip-front-matter` is set, before the
718        // source reaches the preprocessor or header parser.
719        let stripped_source = self.skip_front_matter(source);
720        let source = stripped_source.as_deref().unwrap_or(source);
721
722        let (preprocessed_source, source_map, preprocessor_warnings, includes) =
723            preprocess(source, self);
724
725        // NOTE: `Document::parse` will transfer the catalog to itself at the end of the
726        // parsing operation. Start each parse with a fresh catalog.
727        *self.catalog.borrow_mut() = Catalog::new();
728
729        // Seed the fresh catalog with the files the preprocessor just expanded,
730        // so an inter-document cross reference to an included file can resolve
731        // to an internal anchor while the document is parsed. Replaying each
732        // event lets the catalog resolve a file that was included both fully and
733        // partially to a full include.
734        {
735            let mut catalog = self.catalog.borrow_mut();
736            for (key, full) in includes {
737                catalog.register_include(&key, full);
738            }
739        }
740
741        // Start each parse with an empty callout catalog.
742        *self.callouts.borrow_mut() = CalloutCatalog::default();
743
744        // Start each parse with no pending substitution warnings.
745        self.substitution_warnings.borrow_mut().clear();
746
747        // Reset section numbering for each new document.
748        self.last_section_number = SectionNumber::default();
749
750        // Start each parse with no block title carried over from a section
751        // heading.
752        self.pending_block_title = None;
753
754        // Reset counter (and captioned-block) numbering for each new document.
755        self.counter_values.borrow_mut().clear();
756        self.locked_counter_values.borrow_mut().clear();
757
758        // Start each parse at the outermost block-nesting level. The counter is
759        // otherwise kept balanced by matched increment/decrement pairs, so this
760        // only matters if a prior parse was abandoned mid-flight; it is reset
761        // here (rather than in the recursive cell/blockquote paths) because
762        // `parse_deferred` runs only for the top-level document.
763        self.block_nesting_depth = 0;
764
765        // Resolve the block-nesting cap once, now, so the guard on the hot
766        // `parse_blocks_until` path is a plain integer compare. The attribute is
767        // API-only and so cannot change mid-parse.
768        self.block_nesting_limit = self.max_block_nesting();
769
770        Document::parse(
771            &preprocessed_source,
772            source_map,
773            preprocessor_warnings,
774            self,
775        )
776    }
777
778    /// Drops leading YAML-style front matter from `source`, mirroring
779    /// Asciidoctor's `Reader#skip_front_matter!`.
780    ///
781    /// Front matter is a block opened by a line of exactly `---` at the very
782    /// start of the document and closed by a matching `---` line. Only this
783    /// `---` fence (the YAML convention) is recognized – a `+++` TOML fence is
784    /// not – and the captured content is stored verbatim, never parsed. It is
785    /// only removed when the `skip-front-matter` attribute is set
786    /// (typically via the API); otherwise `---` retains its ordinary
787    /// meaning and this is a no-op. When a well-formed block is found, its
788    /// content (the lines between the delimiters, joined by LF and with the
789    /// delimiters excluded) is stored in the `front-matter` document
790    /// attribute, and a rewritten copy of the source is returned in which
791    /// every removed line – both delimiters and the content – is replaced
792    /// by a blank line. Preserving the line *count* keeps every following
793    /// line at its original line number, matching Asciidoctor (whose reader
794    /// advances `lineno` past the skipped block); the leading blank lines
795    /// are ignored by the header parser.
796    ///
797    /// Returns `None` (leaving the source untouched and setting no attribute)
798    /// when `skip-front-matter` is not set, when the first line is not `---`,
799    /// or when no closing `---` delimiter is found.
800    fn skip_front_matter(&mut self, source: &str) -> Option<String> {
801        if !self.is_attribute_set("skip-front-matter") {
802            return None;
803        }
804
805        // Strip a line's trailing end-of-line sequence (LF or CRLF) so the
806        // delimiter comparison and the captured content match Asciidoctor's
807        // chomped lines.
808        fn line_content(line: &str) -> &str {
809            let line = line.strip_suffix('\n').unwrap_or(line);
810            line.strip_suffix('\r').unwrap_or(line)
811        }
812
813        let mut lines = source.split_inclusive('\n');
814
815        // Front matter must open on the very first line, which must be exactly
816        // `---`.
817        let first = lines.next()?;
818        if line_content(first) != "---" {
819            return None;
820        }
821
822        // Byte offset just past the region being consumed, and the number of
823        // physical lines consumed (starting with the opening delimiter).
824        let mut consumed_end = first.len();
825        let mut consumed_lines = 1usize;
826
827        let mut front_matter = String::new();
828        let mut closed = false;
829
830        for line in lines {
831            consumed_end += line.len();
832            consumed_lines += 1;
833
834            if line_content(line) == "---" {
835                closed = true;
836                break;
837            }
838
839            if !front_matter.is_empty() {
840                front_matter.push('\n');
841            }
842
843            front_matter.push_str(line_content(line));
844        }
845
846        // Without a closing delimiter the block is malformed; leave the source
847        // (and attributes) untouched, matching Asciidoctor.
848        if !closed {
849            return None;
850        }
851
852        self.set_attribute_by_value_from_header("front-matter", &front_matter);
853
854        // Replace the consumed region with one blank line per removed physical
855        // line so the remaining content keeps its original line numbers.
856        let mut rewritten = String::with_capacity(source.len());
857        for _ in 0..consumed_lines {
858            rewritten.push('\n');
859        }
860
861        rewritten.push_str(&source[consumed_end..]);
862
863        Some(rewritten)
864    }
865
866    /// Retrieves the current interpreted value of a [document attribute].
867    ///
868    /// Each document holds a set of name-value pairs called document
869    /// attributes. These attributes provide a means of configuring the AsciiDoc
870    /// processor, declaring document metadata, and defining reusable content.
871    /// This page introduces document attributes and answers some questions
872    /// about the terminology used when referring to them.
873    ///
874    /// ## What are document attributes?
875    ///
876    /// Document attributes are effectively document-scoped variables for the
877    /// AsciiDoc language. The AsciiDoc language defines a set of built-in
878    /// attributes, and also allows the author (or extensions) to define
879    /// additional document attributes, which may replace built-in attributes
880    /// when permitted.
881    ///
882    /// Built-in attributes either provide access to read-only information about
883    /// the document and its environment or allow the author to configure
884    /// behavior of the AsciiDoc processor for a whole document or select
885    /// regions. Built-in attributes are effectively unordered. User-defined
886    /// attribute serve as a powerful text replacement tool. User-defined
887    /// attributes are stored in the order in which they are defined.
888    ///
889    /// [document attribute]: https://docs.asciidoctor.org/asciidoc/latest/attributes/document-attributes/
890    pub fn attribute_value<N: AsRef<str>>(&self, name: N) -> InterpretedValue {
891        let name = name.as_ref();
892
893        // A counter's current value lives in the overlay and supersedes any
894        // earlier value of the attribute of the same name (see
895        // [`counter_values`](Self::counter_values)).
896        if let Some(value) = self.counter_values.borrow().get(name) {
897            return InterpretedValue::Value(value.clone());
898        }
899
900        // An unset `relfilesuffix` reads as the *effective* value of
901        // `outfilesuffix` – routed through this same reader so an
902        // `outfilesuffix` counter overlay is honored too (see
903        // [`tracks_outfilesuffix`](Self::tracks_outfilesuffix)).
904        if self.tracks_outfilesuffix(name) {
905            return self.attribute_value("outfilesuffix");
906        }
907
908        // Under `SafeMode::Server` or greater, `docdir` reads as empty and
909        // `docfile` is relativized (its `docdir` prefix stripped), matching
910        // Ruby Asciidoctor's document-init masking. Resolved here at read time
911        // (like `relfilesuffix` above and `max-attribute-value-size`) so the
912        // API-provided values are never rewritten and builder-call order does
913        // not matter (see [`masked_doc_path`]).
914        //
915        // [`masked_doc_path`]: crate::parser::safe_mode::masked_doc_path
916        if self.safe >= SafeMode::Server
917            && let Some(masked) = masked_doc_path(name, |n| self.raw_set_value(n))
918        {
919            return masked;
920        }
921
922        // `basebackend` / `filetype` are derived on the fly from the current
923        // `backend` (see [`derived_backend_value`]) rather than stored; they are
924        // read-only intrinsics, so no per-parser entry ever shadows this.
925        if let Some(value) = derived_backend_value(name, &self.attribute_values) {
926            return value;
927        }
928
929        match self.effective_attribute(name) {
930            Some(av) => {
931                if let InterpretedValue::Set = av.value
932                    && let Some(default) = self.default_attribute_values.get(name)
933                {
934                    InterpretedValue::Value(default.clone())
935                } else {
936                    av.value.clone()
937                }
938            }
939
940            // A time-dependent attribute is not materialized in either table; it
941            // is resolved on demand from the captured reference instant.
942            None => self
943                .resolve_datetime_attribute(name)
944                .unwrap_or(InterpretedValue::Unset),
945        }
946    }
947
948    /// Returns the raw stored string value of `name` if it currently resolves
949    /// to a plain [`Value`](InterpretedValue::Value), *before* any
950    /// safe-mode masking is applied. Returns `None` when the attribute is unset
951    /// or resolves to a non-value form.
952    ///
953    /// This feeds [`masked_doc_path`], which must compute the `docfile`
954    /// relativization from the *original* API-provided `docdir` rather than its
955    /// masked (blanked) form.
956    fn raw_set_value(&self, name: &str) -> Option<String> {
957        match self.effective_attribute(name)?.value {
958            InterpretedValue::Value(ref v) => Some(v.clone()),
959            _ => None,
960        }
961    }
962
963    /// Returns the effective attribute definition for `name`: a per-parser
964    /// entry (an override or an explicit [unset] tombstone) shadows the
965    /// shared built-in default, which in turn shadows an on-the-fly
966    /// synthesized attribute (the active `backend-html5-doctype-*` and
967    /// `safe-mode-*` flags). The synthesized attributes are never
968    /// materialized in either table.
969    ///
970    /// This is the *raw* lookup used by the attribute writers to decide whether
971    /// a name is locked against modification. The attribute *readers*
972    /// additionally resolve the read-only default of `relfilesuffix` (see
973    /// [`tracks_outfilesuffix`](Self::tracks_outfilesuffix)).
974    ///
975    /// [unset]: https://docs.asciidoctor.org/asciidoc/latest/attributes/unset-attributes/
976    pub(crate) fn effective_attribute(&self, name: &str) -> Option<&AttributeValue> {
977        if let Some(av) = self.attribute_values.get(name) {
978            return Some(av);
979        }
980
981        // `max-attribute-value-size` carries its `4096` default only under
982        // Secure, so it is resolved as a mode-aware synthesized attribute rather
983        // than a fixed built-in. It is consulted here *after* the per-parser map
984        // so a caller-supplied value (always API-only, hence always in that map)
985        // wins regardless of builder-call order, and a `with_safe_mode` change
986        // never rewrites it.
987        if name == "max-attribute-value-size" {
988            return Some(max_attribute_value_size_default(
989                self.safe == SafeMode::Secure,
990            ));
991        }
992
993        // `user-home` is the user's home directory below `SafeMode::Server` and
994        // the masking `.` at `Server`/`Secure`, so it too is resolved as a
995        // mode-aware synthesized attribute. Consulted here *after* the
996        // per-parser map so a caller-supplied `user-home` (always API-only,
997        // hence always in that map) wins regardless of builder-call order.
998        if name == "user-home" {
999            return Some(user_home_default(self.safe < SafeMode::Server));
1000        }
1001        if let Some(av) = built_in_attr(name) {
1002            return Some(av);
1003        }
1004        synthesized_attr(name, &self.attribute_values)
1005    }
1006
1007    /// Reports whether `name` is `relfilesuffix` in its unset state, in which
1008    /// case a *read* resolves it to the current value of `outfilesuffix` (the
1009    /// two diverge for non-HTML backends, e.g. `.xml` for DocBook – see
1010    /// [issue #657](https://github.com/asciidoc-rs/asciidoc-parser/issues/657)).
1011    ///
1012    /// Returns `false` once `relfilesuffix` is explicitly set or unset (an
1013    /// entry – a value or an [unset] tombstone – then lives in the
1014    /// per-parser map), and for every other name. The redirect is
1015    /// deliberately confined to the value *readers*: the attribute
1016    /// *writers* consult [`effective_attribute`](Self::effective_attribute)
1017    /// directly, so `relfilesuffix` stays modifiable anywhere rather than
1018    /// inheriting the header-only modification context of `outfilesuffix`.
1019    /// Callers must apply a like-named counter overlay first, so a
1020    /// `{counter:relfilesuffix}` still wins over the tracked default.
1021    ///
1022    /// [unset]: https://docs.asciidoctor.org/asciidoc/latest/attributes/unset-attributes/
1023    pub(crate) fn tracks_outfilesuffix(&self, name: &str) -> bool {
1024        name == "relfilesuffix" && !self.attribute_values.contains_key(name)
1025    }
1026
1027    /// Returns `true` if the parser has a [document attribute] by this name.
1028    ///
1029    /// [document attribute]: https://docs.asciidoctor.org/asciidoc/latest/attributes/document-attributes/
1030    pub fn has_attribute<N: AsRef<str>>(&self, name: N) -> bool {
1031        let name = name.as_ref();
1032        if self.counter_values.borrow().contains_key(name) {
1033            return true;
1034        }
1035        if self.tracks_outfilesuffix(name) {
1036            return self.has_attribute("outfilesuffix");
1037        }
1038
1039        // A derived `basebackend` / `filetype` is present only while `backend`
1040        // resolves to a non-empty value (see [`derived_backend_value`]).
1041        if derived_backend_value(name, &self.attribute_values).is_some() {
1042            return true;
1043        }
1044        self.effective_attribute(name).is_some() || self.resolve_datetime_attribute(name).is_some()
1045    }
1046
1047    /// Returns `true` if the parser has a [document attribute] by this name
1048    /// which has been set (i.e. is present and not [unset]).
1049    ///
1050    /// [document attribute]: https://docs.asciidoctor.org/asciidoc/latest/attributes/document-attributes/
1051    /// [unset]: https://docs.asciidoctor.org/asciidoc/latest/attributes/unset-attributes/
1052    pub fn is_attribute_set<N: AsRef<str>>(&self, name: N) -> bool {
1053        let name = name.as_ref();
1054
1055        // A counter always holds a concrete (set) value.
1056        if self.counter_values.borrow().contains_key(name) {
1057            return true;
1058        }
1059
1060        if self.tracks_outfilesuffix(name) {
1061            return self.is_attribute_set("outfilesuffix");
1062        }
1063
1064        // A derived `basebackend` / `filetype` holds a concrete (set) value
1065        // whenever it is present, i.e. while `backend` is non-empty (see
1066        // [`derived_backend_value`]).
1067        if derived_backend_value(name, &self.attribute_values).is_some() {
1068            return true;
1069        }
1070
1071        self.effective_attribute(name)
1072            .map(|a| a.value != InterpretedValue::Unset)
1073            .unwrap_or_else(|| self.resolve_datetime_attribute(name).is_some())
1074    }
1075
1076    /// Returns the current `leveloffset` document attribute as a signed
1077    /// integer.
1078    ///
1079    /// The `leveloffset` attribute shifts the effective level of every section
1080    /// heading in scope (see the include directive's `leveloffset` option and
1081    /// the `:leveloffset:` attribute entry). Relative assignments (`+N` / `-N`)
1082    /// are resolved to an absolute value when the attribute is set (see
1083    /// [`resolve_leveloffset_assignment`](Self::resolve_leveloffset_assignment)),
1084    /// so the stored value is always a plain integer; a non-integer or unset
1085    /// value yields an offset of `0`.
1086    pub(crate) fn level_offset(&self) -> i32 {
1087        match self.attribute_value("leveloffset") {
1088            InterpretedValue::Value(v) => v.trim().parse::<i32>().unwrap_or(0),
1089            _ => 0,
1090        }
1091    }
1092
1093    /// Resolves the maximum block-nesting depth in effect from the
1094    /// `max-block-nesting` attribute (default
1095    /// [`DEFAULT_MAX_BLOCK_NESTING`](Self::DEFAULT_MAX_BLOCK_NESTING)). See
1096    /// [`block_nesting_depth`](Self::block_nesting_depth).
1097    ///
1098    /// This walks the document-attribute machinery, so it is resolved once per
1099    /// parse into [`block_nesting_limit`](Self::block_nesting_limit) rather
1100    /// than consulted on the hot [`parse_blocks_until`] path; use
1101    /// [`block_nesting_limit_reached`](Self::block_nesting_limit_reached)
1102    /// there.
1103    ///
1104    /// The attribute is API-only, so a hostile document cannot raise its own
1105    /// limit. The value is coerced as Ruby's `String#to_i` would (matching how
1106    /// `max-include-depth` is read): a non-positive result yields `0` – which
1107    /// permits only the outermost, document-level block scope – while a
1108    /// positive value too large for `usize` saturates rather than wrapping to
1109    /// the "disabled" sentinel.
1110    ///
1111    /// [`parse_blocks_until`]: crate::blocks::parse_utils::parse_blocks_until
1112    pub(crate) fn max_block_nesting(&self) -> usize {
1113        match self.attribute_value("max-block-nesting") {
1114            InterpretedValue::Value(value) => {
1115                let depth = super::preprocessor::ruby_to_i(&value);
1116                if depth <= 0 {
1117                    0
1118                } else {
1119                    usize::try_from(depth).unwrap_or(usize::MAX)
1120                }
1121            }
1122
1123            // An explicit empty `Set` coerces to 0; an explicit unset falls back
1124            // to the built-in default.
1125            InterpretedValue::Set => 0,
1126            InterpretedValue::Unset => Self::DEFAULT_MAX_BLOCK_NESTING,
1127        }
1128    }
1129
1130    /// Reports whether descending into another nested block scope would exceed
1131    /// the block-nesting limit, so the caller must stop nesting and truncate
1132    /// instead. See [`block_nesting_depth`](Self::block_nesting_depth).
1133    ///
1134    /// This compares against the per-parse cached
1135    /// [`block_nesting_limit`](Self::block_nesting_limit), so it stays cheap on
1136    /// the hot [`parse_blocks_until`] path.
1137    ///
1138    /// [`parse_blocks_until`]: crate::blocks::parse_utils::parse_blocks_until
1139    pub(crate) fn block_nesting_limit_reached(&self) -> bool {
1140        self.block_nesting_depth > self.block_nesting_limit
1141    }
1142
1143    /// Records a [`MaxBlockNestingExceeded`] warning anchored at `source`,
1144    /// reporting the [`max_block_nesting`](Self::max_block_nesting) limit in
1145    /// effect.
1146    ///
1147    /// [`MaxBlockNestingExceeded`]:
1148    /// crate::warnings::WarningType::MaxBlockNestingExceeded
1149    pub(crate) fn warn_block_nesting_exceeded<'src>(
1150        &self,
1151        source: crate::Span<'src>,
1152        warnings: &mut Vec<Warning<'src>>,
1153    ) {
1154        warnings.push(Warning {
1155            source,
1156            warning: WarningType::MaxBlockNestingExceeded(self.block_nesting_limit),
1157            origin: None,
1158        });
1159    }
1160
1161    /// Returns the effective `max-attribute-value-size`: the byte limit applied
1162    /// to a resolved attribute-entry value, or `None` when no limit is in
1163    /// force.
1164    ///
1165    /// The value is coerced as Ruby's `String#to_i` would (matching
1166    /// Asciidoctor); a non-positive result – including an explicit unset or `0`
1167    /// – disables the limit. The `4096` default only exists under
1168    /// `SafeMode::Secure` (see
1169    /// [`apply_safe_mode_attributes`](Self::apply_safe_mode_attributes)), so in
1170    /// a relaxed safe mode this resolves to `None` unless the caller sets an
1171    /// explicit positive value.
1172    fn max_attribute_value_size(&self) -> Option<usize> {
1173        match self.attribute_value("max-attribute-value-size") {
1174            InterpretedValue::Value(value) => {
1175                let size = super::preprocessor::ruby_to_i(&value);
1176                (size > 0).then(|| usize::try_from(size).unwrap_or(usize::MAX))
1177            }
1178            _ => None,
1179        }
1180    }
1181
1182    /// Applies the [`max-attribute-value-size`](Self::max_attribute_value_size)
1183    /// limit to a freshly resolved attribute-entry `value`, truncating it (on a
1184    /// character boundary, so a multibyte character is never split) when it
1185    /// exceeds the limit. Values that already fit, and non-`Value` variants,
1186    /// are returned unchanged.
1187    fn limit_attribute_value_size(&self, value: InterpretedValue) -> InterpretedValue {
1188        let Some(max) = self.max_attribute_value_size() else {
1189            return value;
1190        };
1191
1192        let InterpretedValue::Value(text) = value else {
1193            return value;
1194        };
1195
1196        if text.len() <= max {
1197            return InterpretedValue::Value(text);
1198        }
1199
1200        // Back up to the nearest character boundary at or below `max` so a
1201        // multibyte character straddling the limit is dropped whole rather than
1202        // split (which would otherwise yield invalid UTF-8).
1203        let mut end = max;
1204        while end > 0 && !text.is_char_boundary(end) {
1205            end -= 1;
1206        }
1207
1208        let mut text = text;
1209        text.truncate(end);
1210        InterpretedValue::Value(text)
1211    }
1212
1213    /// Resolves a `leveloffset` assignment value, converting a relative form
1214    /// (`+N` / `-N`) into the absolute value it produces given the
1215    /// `leveloffset` currently in effect. Absolute values, and values that
1216    /// aren't a signed integer, are returned unchanged.
1217    ///
1218    /// This mirrors Asciidoctor, where a relative `leveloffset` accumulates on
1219    /// top of the offset already in effect. That accumulation is what lets the
1220    /// offsets of nested includes compose: each `include::[leveloffset=+1]`
1221    /// (and its `:leveloffset: +1` wrapper) shifts headings one level further
1222    /// down relative to wherever the surrounding content already sits.
1223    fn resolve_leveloffset_assignment(&self, value: InterpretedValue) -> InterpretedValue {
1224        let InterpretedValue::Value(ref v) = value else {
1225            return value;
1226        };
1227
1228        // Only a leading `+`/`-` marks a relative assignment; anything else
1229        // (an absolute value, or a non-numeric value) is stored unchanged.
1230        let trimmed = v.trim();
1231        if !trimmed.starts_with(['+', '-']) {
1232            return value;
1233        }
1234
1235        // Parse the whole signed value as `i64` so the extreme relative delta
1236        // `-2147483648` (whose magnitude exceeds `i32::MAX`) is still read as
1237        // itself rather than failing and being stored as an absolute value.
1238        match trimmed.parse::<i64>() {
1239            // The running offset is a valid `i32`, so widening it to `i64`
1240            // makes the accumulation itself infallible; `saturating_add` then
1241            // guards the (already absurd) case of a delta near `i64::MIN/MAX`,
1242            // and the result is clamped back into the `i32` the attribute
1243            // stores. This keeps a pathological offset from overflowing –
1244            // which would panic in debug builds and wrap in release builds –
1245            // rather than imposing a real bound the syntax does not otherwise
1246            // impose.
1247            Ok(delta) => InterpretedValue::Value(
1248                (self.level_offset() as i64)
1249                    .saturating_add(delta)
1250                    .clamp(i32::MIN as i64, i32::MAX as i64)
1251                    .to_string(),
1252            ),
1253            Err(_) => value,
1254        }
1255    }
1256
1257    /// Resolves a `leveloffset` assignment (see
1258    /// [`resolve_leveloffset_assignment`](Self::resolve_leveloffset_assignment))
1259    /// and, if the resulting absolute offset is so large or small that *every*
1260    /// heading would be shifted outside the supported 1..=5 section-level
1261    /// range, records a [`LeveloffsetExcludesAllHeadingLevels`] warning
1262    /// against `span`.
1263    ///
1264    /// [`LeveloffsetExcludesAllHeadingLevels`]:
1265    /// crate::warnings::WarningType::LeveloffsetExcludesAllHeadingLevels
1266    fn resolve_leveloffset_and_warn<'src>(
1267        &self,
1268        value: InterpretedValue,
1269        span: crate::Span<'src>,
1270        warnings: &mut Vec<Warning<'src>>,
1271    ) -> InterpretedValue {
1272        let value = self.resolve_leveloffset_assignment(value);
1273
1274        if let InterpretedValue::Value(ref v) = value
1275            && let Ok(offset) = v.trim().parse::<i32>()
1276            && !leveloffset_admits_any_heading(offset)
1277        {
1278            warnings.push(Warning {
1279                source: span,
1280                warning: WarningType::LeveloffsetExcludesAllHeadingLevels(offset),
1281                origin: None,
1282            });
1283        }
1284
1285        value
1286    }
1287
1288    /// Captures the parser's fully-resolved document-attribute state so it can
1289    /// outlive the parser – for example, retained on a [`Document`] to answer
1290    /// [`attribute_value`]/[`has_attribute`]/[`is_attribute_set`] without a
1291    /// parser in hand (the embed path a renderer uses for `convert_document`).
1292    ///
1293    /// This shares the parser's attribute tables by [`Arc`] rather than copying
1294    /// them, so it is cheap to take on every parse (the large built-in table is
1295    /// never deep-cloned). The time-dependent attributes are not materialized;
1296    /// the snapshot carries the reference-time configuration so it can resolve
1297    /// them on demand exactly as the parser does. See [`ResolvedAttributes`].
1298    ///
1299    /// [`Document`]: crate::Document
1300    /// [`attribute_value`]: Self::attribute_value
1301    /// [`has_attribute`]: Self::has_attribute
1302    /// [`is_attribute_set`]: Self::is_attribute_set
1303    pub(crate) fn snapshot_attributes(&self) -> ResolvedAttributes {
1304        ResolvedAttributes::new(
1305            Arc::clone(&self.attribute_values),
1306            Arc::clone(&self.default_attribute_values),
1307            self.counter_values.borrow().clone(),
1308            self.safe,
1309            self.reference_time.clone(),
1310            self.input_mtime.clone(),
1311        )
1312    }
1313
1314    /// Resolves whether a document title should be displayed, from the
1315    /// `showtitle`/`notitle` attribute pair (which are complements).
1316    ///
1317    /// `showtitle` takes precedence: if present, the title shows precisely when
1318    /// it is set. Otherwise `notitle`, if present, hides the title when set.
1319    /// When neither attribute is present, `default_shown` decides – a
1320    /// standalone document (such as a nested AsciiDoc table cell) shows its
1321    /// title, while an embedded document does not.
1322    pub(crate) fn resolve_show_title(&self, default_shown: bool) -> bool {
1323        if self.has_attribute("showtitle") {
1324            self.is_attribute_set("showtitle")
1325        } else if self.has_attribute("notitle") {
1326            !self.is_attribute_set("notitle")
1327        } else {
1328            default_shown
1329        }
1330    }
1331
1332    /// Applies the `notitle` ⇔ `showtitle` inverse-toggle linkage
1333    /// (Asciidoctor asciidoctor/asciidoctor#3804).
1334    ///
1335    /// `notitle` and `showtitle` are two spellings of a single "show the
1336    /// document title" switch, wired as opposites: assigning either attribute
1337    /// updates the other so the resolved document reflects one consistent
1338    /// toggle. This yields last-assignment-wins semantics for free, since each
1339    /// assignment rewrites the partner left by the previous one.
1340    ///
1341    /// `attr_name` is the attribute just assigned and `value` its stored value;
1342    /// the call is a no-op for any other name. Turning the toggle *off* (an
1343    /// explicit [unset], e.g. `:!notitle:`) turns the partner *on* – it is
1344    /// stored [set] with the same `modification_context` and
1345    /// `silent_when_locked` flag as the triggering assignment. Turning the
1346    /// toggle *on* (an empty `Set` or an explicit value, e.g. `:notitle:`)
1347    /// *removes* the partner entirely.
1348    ///
1349    /// The partner is removed – rather than left as an explicit unset
1350    /// tombstone – to mirror Asciidoctor's attribute-hash semantics, where an
1351    /// "off" attribute is simply absent. That keeps every observer consistent:
1352    /// `has_attribute`, `ifdef`/`ifndef`, and `{partner}` reference
1353    /// substitution all see the same absence Asciidoctor does (so, e.g., a
1354    /// `{showtitle}` reference stays literal after `:notitle:` rather than
1355    /// silently resolving to an empty string).
1356    ///
1357    /// [set]: https://docs.asciidoctor.org/asciidoc/latest/attributes/set-attributes/
1358    /// [unset]: https://docs.asciidoctor.org/asciidoc/latest/attributes/unset-attributes/
1359    fn apply_title_visibility_linkage(
1360        &mut self,
1361        attr_name: &str,
1362        value: &InterpretedValue,
1363        modification_context: ModificationContext,
1364        silent_when_locked: bool,
1365    ) {
1366        let partner = match attr_name {
1367            "notitle" => "showtitle",
1368            "showtitle" => "notitle",
1369            _ => return,
1370        };
1371
1372        // Either way the partner supersedes (and resets) any counter of the
1373        // same name, mirroring a direct assignment.
1374        self.counter_values.borrow_mut().remove(partner);
1375
1376        if let InterpretedValue::Unset = value {
1377            // The toggle is off, so the partner turns on.
1378            Arc::make_mut(&mut self.attribute_values).insert(
1379                partner.to_string(),
1380                AttributeValue {
1381                    allowable_value: AllowableValue::Any,
1382                    modification_context,
1383                    silent_when_locked,
1384                    value: InterpretedValue::Set,
1385                },
1386            );
1387        } else if self.attribute_values.contains_key(partner) {
1388            // The toggle is on, so the partner turns off – and, matching
1389            // Asciidoctor, "off" means absent. (Guarded so the common case of
1390            // no prior partner entry does not clone the shared map.)
1391            Arc::make_mut(&mut self.attribute_values).remove(partner);
1392        }
1393    }
1394
1395    /// Forces the `doctype` attribute to `value`.
1396    ///
1397    /// Used when a nested AsciiDoc table cell resets its doctype to the default
1398    /// (a cell does not inherit the parent's doctype). The value stays
1399    /// modifiable from the document body so the cell may still set its own
1400    /// doctype.
1401    ///
1402    /// The derived `backend-html5-doctype-{doctype}` attribute needs no
1403    /// explicit refresh: it is synthesized on the fly for whatever
1404    /// `doctype` currently resolves to (see
1405    /// [`attribute_value`](Self::attribute_value)).
1406    pub(crate) fn force_doctype(&mut self, value: &str) {
1407        Arc::make_mut(&mut self.attribute_values).insert(
1408            "doctype".to_string(),
1409            AttributeValue {
1410                allowable_value: AllowableValue::Any,
1411                modification_context: ModificationContext::ApiOrDocumentBody,
1412                silent_when_locked: false,
1413                value: InterpretedValue::Value(value.to_string()),
1414            },
1415        );
1416    }
1417
1418    /// Records the current [`attribute_values`](Self::attribute_values) as the
1419    /// configured baseline restored at the start of each parse.
1420    ///
1421    /// Called at the end of every attribute-configuring builder method, once
1422    /// all of that call's effects (including any
1423    /// [title-visibility](Self::apply_title_visibility_linkage) partner or
1424    /// safe-mode attributes) have been applied. The snapshot is an [`Arc`]
1425    /// clone, so it captures exactly the post-call state and stays cheap; see
1426    /// [`baseline_attribute_values`](Self::baseline_attribute_values).
1427    fn capture_attribute_baseline(&mut self) {
1428        self.baseline_attribute_values = Arc::clone(&self.attribute_values);
1429    }
1430
1431    /// Sets the value of an [intrinsic attribute].
1432    ///
1433    /// Intrinsic attributes are set automatically by the processor. These
1434    /// attributes provide information about the document being processed (e.g.,
1435    /// `docfile`), the security mode under which the processor is running
1436    /// (e.g., `safe-mode-name`), and information about the user’s environment
1437    /// (e.g., `user-home`).
1438    ///
1439    /// The [`modification_context`](ModificationContext) establishes whether
1440    /// the value can be subsequently modified by the document header and/or in
1441    /// the document body.
1442    ///
1443    /// Subsequent calls to this function or [`with_intrinsic_attribute_bool()`]
1444    /// are always permitted. The last such call for any given attribute name
1445    /// takes precendence.
1446    ///
1447    /// [intrinsic attribute]: https://docs.asciidoctor.org/asciidoc/latest/attributes/document-attributes-ref/#intrinsic-attributes
1448    ///
1449    /// [`with_intrinsic_attribute_bool()`]: Self::with_intrinsic_attribute_bool
1450    #[must_use]
1451    pub fn with_intrinsic_attribute<N: AsRef<str>, V: AsRef<str>>(
1452        mut self,
1453        name: N,
1454        value: V,
1455        modification_context: ModificationContext,
1456    ) -> Self {
1457        let name = alias_attr_name(name.as_ref().to_lowercase());
1458        let value = InterpretedValue::Value(value.as_ref().to_string());
1459        let attribute_value = AttributeValue {
1460            allowable_value: AllowableValue::Any,
1461            modification_context,
1462            silent_when_locked: false,
1463            value: value.clone(),
1464        };
1465
1466        Arc::make_mut(&mut self.attribute_values).insert(name.clone(), attribute_value);
1467
1468        self.apply_title_visibility_linkage(&name, &value, modification_context, false);
1469
1470        self.capture_attribute_baseline();
1471
1472        self
1473    }
1474
1475    /// Sets the value of an [intrinsic attribute], rejecting any disallowed
1476    /// subsequent write *silently*.
1477    ///
1478    /// This behaves exactly like [`with_intrinsic_attribute()`] except that a
1479    /// document header or body assignment that the
1480    /// [`modification_context`](ModificationContext) does not permit is dropped
1481    /// with **no** `AttributeValueIsLocked` warning, instead of recording one.
1482    /// The rejected write is otherwise handled identically (the value is left
1483    /// unchanged).
1484    ///
1485    /// This reproduces Asciidoctor's *silent* safe-mode attribute restrictions:
1486    /// under `SERVER`/`SECURE`, a document assignment of a restricted
1487    /// conversion attribute (`backend`, `doctype`, `docinfo`,
1488    /// `source-highlighter`) is simply dropped, with no diagnostic. Seed
1489    /// such an attribute as an [`ApiOnly`](ModificationContext::ApiOnly)
1490    /// silent intrinsic to lock it against document assignment without
1491    /// warning.
1492    ///
1493    /// Subsequent calls to this function or the other
1494    /// `with_intrinsic_attribute` variants are always permitted. The last
1495    /// such call for any given attribute name takes precedence.
1496    ///
1497    /// [intrinsic attribute]: https://docs.asciidoctor.org/asciidoc/latest/attributes/document-attributes-ref/#intrinsic-attributes
1498    ///
1499    /// [`with_intrinsic_attribute()`]: Self::with_intrinsic_attribute
1500    #[must_use]
1501    pub fn with_intrinsic_attribute_silent<N: AsRef<str>, V: AsRef<str>>(
1502        mut self,
1503        name: N,
1504        value: V,
1505        modification_context: ModificationContext,
1506    ) -> Self {
1507        let name = alias_attr_name(name.as_ref().to_lowercase());
1508        let value = InterpretedValue::Value(value.as_ref().to_string());
1509        let attribute_value = AttributeValue {
1510            allowable_value: AllowableValue::Any,
1511            modification_context,
1512            silent_when_locked: true,
1513            value: value.clone(),
1514        };
1515
1516        Arc::make_mut(&mut self.attribute_values).insert(name.clone(), attribute_value);
1517
1518        self.apply_title_visibility_linkage(&name, &value, modification_context, true);
1519
1520        self.capture_attribute_baseline();
1521
1522        self
1523    }
1524
1525    /// Register a referenceable element (anchor, section, bibliography entry)
1526    /// in the document catalog.
1527    ///
1528    /// This takes `&self` (rather than `&mut self`) so that it can be called
1529    /// from inline-substitution code paths that only hold a shared reference to
1530    /// the parser, such as a regex [`Replacer`](regex::Replacer).
1531    pub(crate) fn register_ref(
1532        &self,
1533        id: &str,
1534        reftext: Option<&str>,
1535        ref_type: RefType,
1536    ) -> Result<(), crate::document::DuplicateIdError> {
1537        self.catalog
1538            .borrow_mut()
1539            .register_ref(id, reftext, ref_type)
1540    }
1541
1542    /// Attaches an [`XrefSignifier`](crate::parser::XrefSignifier) to an
1543    /// already-registered catalog element, so a cross-reference to it can build
1544    /// `full`/`short` [`xrefstyle`](crate::parser::XrefStyle) text.
1545    ///
1546    /// Takes `&self` for the same reason as
1547    /// [`register_ref`](Self::register_ref).
1548    pub(crate) fn set_ref_signifier(&self, id: &str, signifier: crate::parser::XrefSignifier) {
1549        self.catalog.borrow_mut().set_signifier(id, signifier);
1550    }
1551
1552    /// Records a referenced image in the document catalog when
1553    /// [`catalog_assets`](Self::with_catalog_assets) is enabled. A no-op
1554    /// otherwise.
1555    ///
1556    /// `target` is the (already attribute-substituted) image target as written
1557    /// in the macro; `imagesdir` is the value of the document `imagesdir`
1558    /// attribute at the point of reference, or `None` when it is unset.
1559    ///
1560    /// Takes `&self` so it can be called from the macros substitution step,
1561    /// which only holds a shared reference to the parser.
1562    pub(crate) fn register_image(&self, target: String, imagesdir: Option<String>) {
1563        if self.catalog_assets {
1564            self.catalog.borrow_mut().register_image(target, imagesdir);
1565        }
1566    }
1567
1568    /// Records a referenced link target in the document catalog when
1569    /// [`catalog_assets`](Self::with_catalog_assets) is enabled. A no-op
1570    /// otherwise.
1571    ///
1572    /// `target` is the final link target as it appears in the rendered `href`
1573    /// (e.g. `https://example.org`, `mailto:fred@example.com`).
1574    ///
1575    /// Takes `&self` so it can be called from the macros substitution step,
1576    /// which only holds a shared reference to the parser.
1577    pub(crate) fn register_link(&self, target: String) {
1578        if self.catalog_assets {
1579            self.catalog.borrow_mut().register_link(target);
1580        }
1581    }
1582
1583    /// Registers a callout number defined by a verbatim block.
1584    ///
1585    /// Takes `&self` so it can be called from the callouts substitution step,
1586    /// which only holds a shared reference to the parser.
1587    pub(crate) fn register_callout(&self, number: u32) {
1588        self.callouts.borrow_mut().current.push(number);
1589    }
1590
1591    /// Returns `true` if a callout numbered `number` was registered for the
1592    /// current (not-yet-closed) callout list.
1593    pub(crate) fn callout_defined(&self, number: u32) -> bool {
1594        self.callouts.borrow().current.contains(&number)
1595    }
1596
1597    /// Closes the current callout list, so callouts registered afterward belong
1598    /// to the next list.
1599    pub(crate) fn close_callout_list(&self) {
1600        self.callouts.borrow_mut().current.clear();
1601    }
1602
1603    /// Returns the number of an already-defined footnote with the given ID, if
1604    /// one exists in the current document's footnote registry.
1605    ///
1606    /// Takes `&self` so it can be called from the macros substitution step,
1607    /// which only holds a shared reference to the parser.
1608    pub(crate) fn footnote_index_for_id(&self, id: &str) -> Option<String> {
1609        self.catalog
1610            .borrow()
1611            .footnote_with_id(id)
1612            .map(|f| f.index.clone())
1613    }
1614
1615    /// Defines a new footnote, advancing the `footnote-number` counter and
1616    /// registering the footnote in the current document's registry. Returns the
1617    /// number assigned to the footnote.
1618    ///
1619    /// `source` is the span of the content the defining `footnote:[…]` macro
1620    /// was written in; its offset into the document source is recorded so a
1621    /// cross-reference warning can be anchored at the footnote rather than at
1622    /// the whole document. When the footnote is defined while substituting a
1623    /// privately-owned sub-source (a Markdown-style blockquote or an AsciiDoc
1624    /// table cell – see
1625    /// [`owned_subsource_depth`](Self::owned_subsource_depth)), that offset
1626    /// does not map to the document, so no location is recorded and
1627    /// resolution falls back to the whole-document span.
1628    ///
1629    /// Takes `&self` so it can be called from the macros substitution step.
1630    pub(crate) fn define_footnote(
1631        &self,
1632        id: Option<&str>,
1633        text: String,
1634        xrefs: Vec<crate::content::XrefSegment>,
1635        source: crate::Span<'_>,
1636    ) -> String {
1637        // A footnote's text is extracted out of the block during macro
1638        // substitution, so any cross-reference inside it never reaches the
1639        // document-level resolution pass over block content. Those
1640        // cross-references are captured (as placeholders in `text` plus the
1641        // `xrefs` segments) so they can be resolved alongside the block
1642        // references. The stored `text` is the unresolved fallback rendering
1643        // until then, so it is always clean.
1644        let (text, deferred) = if xrefs.is_empty() {
1645            (text, None)
1646        } else {
1647            let deferred = crate::content::FootnoteDeferred::new(text, xrefs);
1648            let rendered = deferred.render(&*self.renderer);
1649            (rendered, Some(Box::new(deferred)))
1650        };
1651
1652        // Footnotes are numbered consecutively throughout the document via the
1653        // `footnote-number` counter, which is seeded to `0` so the first
1654        // footnote is numbered `1`. The counter is a document-wide attribute, so
1655        // numbering continues across nested documents (AsciiDoc table cells)
1656        // even though the footnote *list* does not. The counter honors any seed
1657        // the document sets, so a non-integer seed yields a non-integer number
1658        // (matching Asciidoctor); the value is therefore kept as a string.
1659        let index = self.counter("footnote-number", None);
1660
1661        // Record the defining occurrence's location only when it is locatable in
1662        // the document source. A footnote defined inside an owned sub-source
1663        // indexes that private source, whose offset would misplace the warning,
1664        // so it is left unrecorded (resolution then falls back to the
1665        // whole-document span).
1666        let location = if self.owned_subsource_depth == 0 {
1667            Some((source.byte_offset(), source.data().len()))
1668        } else {
1669            None
1670        };
1671
1672        self.catalog
1673            .borrow_mut()
1674            .register_footnote(crate::document::Footnote {
1675                index: index.clone(),
1676                id: id.map(|s| s.to_owned()),
1677                text,
1678                deferred,
1679                location,
1680            });
1681
1682        index
1683    }
1684
1685    /// Removes and returns the current document's footnote list, leaving an
1686    /// empty list behind. Used to give a nested document (an AsciiDoc table
1687    /// cell) its own footnote registry; see [`restore_footnotes`].
1688    ///
1689    /// [`restore_footnotes`]: Self::restore_footnotes
1690    pub(crate) fn take_footnotes(&self) -> Vec<crate::document::Footnote> {
1691        self.catalog.borrow_mut().take_footnotes()
1692    }
1693
1694    /// Restores a previously-[taken](Self::take_footnotes) footnote list,
1695    /// discarding any footnotes registered in the meantime (i.e. those defined
1696    /// inside the nested document).
1697    pub(crate) fn restore_footnotes(&self, footnotes: Vec<crate::document::Footnote>) {
1698        self.catalog.borrow_mut().restore_footnotes(footnotes);
1699    }
1700
1701    /// Records a warning produced while replacing attribute references.
1702    ///
1703    /// Takes `&self` so it can be called from the attributes substitution step,
1704    /// which only holds a shared reference to the parser. `source` locates the
1705    /// text the warning refers to; its byte offset and length are stored so a
1706    /// spanned [`Warning`] can be reconstructed later (see
1707    /// [`take_substitution_warnings`](Self::take_substitution_warnings)).
1708    pub(crate) fn record_substitution_warning(
1709        &self,
1710        source: crate::Span<'_>,
1711        warning: WarningType,
1712    ) {
1713        self.substitution_warnings
1714            .borrow_mut()
1715            .push(DeferredWarning {
1716                offset: source.byte_offset(),
1717                len: source.len(),
1718                warning,
1719                origin: None,
1720            });
1721    }
1722
1723    /// Returns the number of substitution warnings recorded so far.
1724    ///
1725    /// Used together with [`truncate_substitution_warnings`] to discard
1726    /// warnings recorded while parsing an owned (e.g. include-expanded) source,
1727    /// whose offsets do not refer to the primary document source.
1728    ///
1729    /// [`truncate_substitution_warnings`]: Self::truncate_substitution_warnings
1730    pub(crate) fn substitution_warnings_len(&self) -> usize {
1731        self.substitution_warnings.borrow().len()
1732    }
1733
1734    /// Discards any substitution warnings recorded since the buffer held `len`
1735    /// entries.
1736    pub(crate) fn truncate_substitution_warnings(&self, len: usize) {
1737        self.substitution_warnings.borrow_mut().truncate(len);
1738    }
1739
1740    /// Removes and returns any substitution warnings recorded since the buffer
1741    /// held `len` entries.
1742    pub(crate) fn drain_substitution_warnings_since(&self, len: usize) -> Vec<DeferredWarning> {
1743        self.substitution_warnings.borrow_mut().split_off(len)
1744    }
1745
1746    /// Takes the substitution warnings recorded during parsing, leaving the
1747    /// buffer empty.
1748    pub(crate) fn take_substitution_warnings(&self) -> Vec<DeferredWarning> {
1749        std::mem::take(&mut *self.substitution_warnings.borrow_mut())
1750    }
1751
1752    /// Returns `true` while the parser is parsing the content of an owned
1753    /// (include-expanded) AsciiDoc table cell, i.e. when a span's line indexes
1754    /// an owned copy rather than the document source.
1755    pub(crate) fn is_in_owned_cell_source(&self) -> bool {
1756        !self.owned_cell_source_maps.is_empty()
1757    }
1758
1759    /// Pushes an owned cell's source map for the duration of its parse. Paired
1760    /// with [`pop_owned_cell_source_map`](Self::pop_owned_cell_source_map).
1761    pub(crate) fn push_owned_cell_source_map(&mut self, source_map: Rc<SourceMap>) {
1762        self.owned_cell_source_maps.push(source_map);
1763    }
1764
1765    /// Pops the source map pushed by the matching
1766    /// [`push_owned_cell_source_map`](Self::push_owned_cell_source_map).
1767    pub(crate) fn pop_owned_cell_source_map(&mut self) {
1768        self.owned_cell_source_maps.pop();
1769    }
1770
1771    /// Resolves a line number in the innermost owned cell's source back to the
1772    /// file and line it originally came from, using that cell's source map.
1773    ///
1774    /// Returns `None` when not inside an owned cell source.
1775    pub(crate) fn owned_cell_original_file_and_line(&self, line: usize) -> Option<SourceLine> {
1776        self.owned_cell_source_maps
1777            .last()
1778            .and_then(|sm| sm.original_file_and_line(line))
1779    }
1780
1781    /// Records a warning raised by a directive at `line` in the innermost owned
1782    /// cell's source, resolving `line` to the file and line it originally came
1783    /// from so the warning can be surfaced later with a real cursor (see
1784    /// [`take_owned_cell_warnings`]).
1785    ///
1786    /// A no-op when not inside an owned cell source (the line does not resolve
1787    /// to an owned origin) – the caller only reaches this from an owned-cell
1788    /// parse, but the guard keeps a stray call from recording an unanchorable
1789    /// warning.
1790    ///
1791    /// Takes `&self`: an owned-cell parse holds the parser mutably behind a
1792    /// `self_cell` construction closure, so recording goes through interior
1793    /// mutability.
1794    ///
1795    /// [`take_owned_cell_warnings`]: Self::take_owned_cell_warnings
1796    pub(crate) fn record_owned_cell_warning(
1797        &self,
1798        line: usize,
1799        warning: WarningType,
1800        origin_override: Option<SourceLine>,
1801    ) {
1802        // A no-output directive that originated in a file the cell *included*
1803        // carries a true `(file, line)` origin already; prefer it. Otherwise
1804        // resolve the cell's own directive line through the enclosing owned
1805        // cell's source map.
1806        let origin = origin_override.or_else(|| self.owned_cell_original_file_and_line(line));
1807        if let Some(origin) = origin {
1808            self.owned_cell_warnings
1809                .borrow_mut()
1810                .push(ResolvedWarning { origin, warning });
1811        }
1812    }
1813
1814    /// Takes the owned-cell warnings recorded during parsing, leaving the
1815    /// buffer empty.
1816    pub(crate) fn take_owned_cell_warnings(&self) -> Vec<ResolvedWarning> {
1817        std::mem::take(&mut *self.owned_cell_warnings.borrow_mut())
1818    }
1819
1820    /// Generate a unique ID derived from `base_id` and register it in the
1821    /// document catalog, returning the ID that was assigned.
1822    pub(crate) fn generate_and_register_unique_id(
1823        &self,
1824        base_id: &str,
1825        reftext: Option<&str>,
1826        ref_type: RefType,
1827    ) -> String {
1828        // A synthetic ID that collides with an existing one is enumerated using
1829        // the `idseparator` (e.g. `_section_one`, `_section_one_2`), matching
1830        // Ruby Asciidoctor – not a hardcoded hyphen. Mirrors the separator
1831        // resolution in `generate_section_id`.
1832        let separator = self
1833            .attribute_value("idseparator")
1834            .as_maybe_str()
1835            .unwrap_or_default()
1836            .chars()
1837            .next()
1838            .map(|c| c.to_string())
1839            .unwrap_or_default();
1840
1841        self.catalog
1842            .borrow_mut()
1843            .generate_and_register_unique_id(base_id, reftext, ref_type, &separator)
1844    }
1845
1846    /// Takes the catalog from the parser, transferring ownership and leaving an
1847    /// empty catalog in its place.
1848    ///
1849    /// This is used by `Document::parse` to transfer the catalog from the
1850    /// parser to the document at the end of parsing.
1851    pub(crate) fn take_catalog(&mut self) -> Catalog {
1852        std::mem::take(&mut *self.catalog.borrow_mut())
1853    }
1854
1855    /* Comment out until we're prepared to use and test this.
1856        /// Sets the default value for an [intrinsic attribute].
1857        ///
1858        /// Default values for attributes are provided automatically by the
1859        /// processor. These values provide a falllback textual value for an
1860        /// attribute when it is merely "set" by the document via API, header, or
1861        /// document body.
1862        ///
1863        /// Calling this does not imply that the value is set automatically by
1864        /// default, nor does it establish any policy for where the value may be
1865        /// modified. For that, please use [`with_intrinsic_attribute`].
1866        ///
1867        /// [intrinsic attribute]: https://docs.asciidoctor.org/asciidoc/latest/attributes/document-attributes-ref/#intrinsic-attributes
1868        /// [`with_intrinsic_attribute`]: Self::with_intrinsic_attribute
1869        pub fn with_default_attribute_value<N: AsRef<str>, V: AsRef<str>>(
1870            mut self,
1871            name: N,
1872            value: V,
1873        ) -> Self {
1874            self.default_attribute_values
1875                .insert(name.as_ref().to_string(), value.as_ref().to_string());
1876
1877            self
1878        }
1879    */
1880
1881    /// Sets the value of an [intrinsic attribute] from a boolean flag.
1882    ///
1883    /// A boolean `true` is interpreted as "set." A boolean `false` is
1884    /// interpreted as "unset."
1885    ///
1886    /// Intrinsic attributes are set automatically by the processor. These
1887    /// attributes provide information about the document being processed (e.g.,
1888    /// `docfile`), the security mode under which the processor is running
1889    /// (e.g., `safe-mode-name`), and information about the user’s environment
1890    /// (e.g., `user-home`).
1891    ///
1892    /// The [`modification_context`](ModificationContext) establishes whether
1893    /// the value can be subsequently modified by the document header and/or in
1894    /// the document body.
1895    ///
1896    /// Subsequent calls to this function or [`with_intrinsic_attribute()`] are
1897    /// always permitted. The last such call for any given attribute name takes
1898    /// precendence.
1899    ///
1900    /// [intrinsic attribute]: https://docs.asciidoctor.org/asciidoc/latest/attributes/document-attributes-ref/#intrinsic-attributes
1901    ///
1902    /// [`with_intrinsic_attribute()`]: Self::with_intrinsic_attribute
1903    #[must_use]
1904    pub fn with_intrinsic_attribute_bool<N: AsRef<str>>(
1905        mut self,
1906        name: N,
1907        value: bool,
1908        modification_context: ModificationContext,
1909    ) -> Self {
1910        let name = alias_attr_name(name.as_ref().to_lowercase());
1911        let value = if value {
1912            InterpretedValue::Set
1913        } else {
1914            InterpretedValue::Unset
1915        };
1916        let attribute_value = AttributeValue {
1917            allowable_value: AllowableValue::Any,
1918            modification_context,
1919            silent_when_locked: false,
1920            value: value.clone(),
1921        };
1922
1923        Arc::make_mut(&mut self.attribute_values).insert(name.clone(), attribute_value);
1924
1925        self.apply_title_visibility_linkage(&name, &value, modification_context, false);
1926
1927        self.capture_attribute_baseline();
1928
1929        self
1930    }
1931
1932    /// Sets the value of an [intrinsic attribute] from a boolean flag,
1933    /// rejecting any disallowed subsequent write *silently*.
1934    ///
1935    /// This behaves exactly like [`with_intrinsic_attribute_bool()`] except
1936    /// that a document header or body assignment that the
1937    /// [`modification_context`](ModificationContext) does not permit is dropped
1938    /// with **no** `AttributeValueIsLocked` warning, instead of recording one.
1939    /// See [`with_intrinsic_attribute_silent()`] for the motivating use case
1940    /// (Asciidoctor's silent safe-mode attribute restrictions).
1941    ///
1942    /// A boolean `true` is interpreted as "set." A boolean `false` is
1943    /// interpreted as "unset."
1944    ///
1945    /// Subsequent calls to this function or the other
1946    /// `with_intrinsic_attribute` variants are always permitted. The last
1947    /// such call for any given attribute name takes precedence.
1948    ///
1949    /// [intrinsic attribute]: https://docs.asciidoctor.org/asciidoc/latest/attributes/document-attributes-ref/#intrinsic-attributes
1950    ///
1951    /// [`with_intrinsic_attribute_bool()`]: Self::with_intrinsic_attribute_bool
1952    /// [`with_intrinsic_attribute_silent()`]: Self::with_intrinsic_attribute_silent
1953    #[must_use]
1954    pub fn with_intrinsic_attribute_bool_silent<N: AsRef<str>>(
1955        mut self,
1956        name: N,
1957        value: bool,
1958        modification_context: ModificationContext,
1959    ) -> Self {
1960        let name = alias_attr_name(name.as_ref().to_lowercase());
1961        let value = if value {
1962            InterpretedValue::Set
1963        } else {
1964            InterpretedValue::Unset
1965        };
1966        let attribute_value = AttributeValue {
1967            allowable_value: AllowableValue::Any,
1968            modification_context,
1969            silent_when_locked: true,
1970            value: value.clone(),
1971        };
1972
1973        Arc::make_mut(&mut self.attribute_values).insert(name.clone(), attribute_value);
1974
1975        self.apply_title_visibility_linkage(&name, &value, modification_context, true);
1976
1977        self.capture_attribute_baseline();
1978
1979        self
1980    }
1981
1982    /// Pins the reference time (the value of "now") used to compute the
1983    /// time-dependent document attributes, for reproducible output.
1984    ///
1985    /// AsciiDoc derives `localdate`, `localtime`, `localdatetime`, and
1986    /// `localyear` from the current wall-clock time, and `docdate`, `doctime`,
1987    /// `docdatetime`, and `docyear` from the source file's modification time
1988    /// (falling back to "now" when no modification time is known). Because
1989    /// those values change from run to run, any output that embeds them is
1990    /// not reproducible. Supplying a [`ReferenceTime`] pins "now" to a
1991    /// fixed instant so the computed attributes are stable.
1992    ///
1993    /// This is the API counterpart of the `SOURCE_DATE_EPOCH` environment
1994    /// variable; a value set here takes precedence over that variable. To pin
1995    /// only the source-modification time that drives the `doc*` attributes
1996    /// (leaving `local*` on the real clock), use [`with_input_mtime`] instead;
1997    /// an [`with_input_mtime`] value takes precedence over this one for the
1998    /// `doc*` attributes.
1999    ///
2000    /// A value set via the document header or body (e.g. an explicit
2001    /// `:docdate:`) still wins over the computed default.
2002    ///
2003    /// [`with_input_mtime`]: Self::with_input_mtime
2004    #[must_use]
2005    pub fn with_reference_time(mut self, reference_time: ReferenceTime) -> Self {
2006        self.reference_time = Some(reference_time);
2007        self
2008    }
2009
2010    /// Pins the modification time of the source document, which drives the
2011    /// `docdate`, `doctime`, `docdatetime`, and `docyear` attributes.
2012    ///
2013    /// This mirrors Asciidoctor's `input_mtime` option: the `local*` attributes
2014    /// continue to reflect "now" (the real clock, a [`with_reference_time`]
2015    /// value, or `SOURCE_DATE_EPOCH`), while the `doc*` attributes reflect the
2016    /// supplied source modification time. A value set here takes precedence
2017    /// over a [`with_reference_time`] value for the `doc*` attributes.
2018    ///
2019    /// A value set via the document header or body (e.g. an explicit
2020    /// `:docdate:`) still wins over the computed default.
2021    ///
2022    /// [`with_reference_time`]: Self::with_reference_time
2023    #[must_use]
2024    pub fn with_input_mtime(mut self, input_mtime: ReferenceTime) -> Self {
2025        self.input_mtime = Some(input_mtime);
2026        self
2027    }
2028
2029    /// Resolves a time-dependent document attribute (`docdate`, `doctime`,
2030    /// `docdatetime`, `docyear`, or a `local*` sibling) on demand, returning
2031    /// `None` for any other name (or when the attribute resolves to no value,
2032    /// as `docyear` / `localyear` do for an explicit date without a `YYYY-`
2033    /// prefix).
2034    ///
2035    /// The reference instant is captured lazily on the first such read of a
2036    /// parse and cached (see [`datetime_context`](Self::datetime_context)), so
2037    /// a parse that never references a time-dependent attribute does no
2038    /// clock, environment, or allocation work, and repeated reads observe
2039    /// one consistent instant. An explicit value assigned via the API,
2040    /// header, or body always wins; the derived `*year` / `*datetime` are
2041    /// computed from whichever value each sibling resolves to. See
2042    /// [`DatetimeContext`].
2043    ///
2044    /// Takes `&self` so it can be called from the shared-reference attribute
2045    /// readers (which the substitution code paths reach with only a `&Parser`);
2046    /// the lazy capture goes through the [`RefCell`].
2047    fn resolve_datetime_attribute(&self, name: &str) -> Option<InterpretedValue> {
2048        if !is_datetime_attribute(name) {
2049            return None;
2050        }
2051
2052        let context = {
2053            let mut slot = self.datetime_context.borrow_mut();
2054            slot.get_or_insert_with(|| {
2055                DatetimeContext::capture(self.reference_time.as_ref(), self.input_mtime.as_ref())
2056            })
2057            .clone()
2058        };
2059
2060        context
2061            .resolve(name, |sibling| self.stored_datetime_override(sibling))
2062            .map(InterpretedValue::Value)
2063    }
2064
2065    /// Returns the *explicitly-set* value of `name` from the per-parser
2066    /// attribute map, as an owned string (a value-less "set" reads as an empty
2067    /// string), or `None` when it has no such entry.
2068    ///
2069    /// This reads only the stored overrides – never the on-the-fly datetime
2070    /// resolution – so it can supply the explicit sibling values
2071    /// [`resolve_datetime_attribute`](Self::resolve_datetime_attribute) needs
2072    /// without recursing. It mirrors the Ruby truthiness the datetime
2073    /// computation relies on (`attrs['docdate']`), where any present value –
2074    /// including an empty string – counts as explicitly supplied.
2075    fn stored_datetime_override(&self, name: &str) -> Option<String> {
2076        self.attribute_values
2077            .get(name)
2078            .and_then(|av| match &av.value {
2079                InterpretedValue::Value(value) => Some(value.clone()),
2080                InterpretedValue::Set => Some(String::new()),
2081                InterpretedValue::Unset => None,
2082            })
2083    }
2084
2085    /// Replace the default [`InlineSubstitutionRenderer`] for this parser.
2086    ///
2087    /// The default implementation of [`InlineSubstitutionRenderer`] that is
2088    /// provided is suitable for HTML5 rendering. If you are targeting a
2089    /// different back-end rendering, you will need to provide your own
2090    /// implementation and set it using this call before parsing.
2091    #[must_use]
2092    pub fn with_inline_substitution_renderer<ISR: InlineSubstitutionRenderer + 'static>(
2093        mut self,
2094        renderer: ISR,
2095    ) -> Self {
2096        self.renderer = Rc::new(renderer);
2097        self
2098    }
2099
2100    /// Sets the name of the primary file to be parsed when [`parse()`] is
2101    /// called.
2102    ///
2103    /// This name will be used for any error messages detected in this file and
2104    /// also will be passed to [`IncludeFileHandler::resolve_target()`] as the
2105    /// `source` argument for any `include::` file resolution requests from this
2106    /// file.
2107    ///
2108    /// [`parse()`]: Self::parse
2109    /// [`IncludeFileHandler::resolve_target()`]: crate::parser::IncludeFileHandler::resolve_target
2110    #[must_use]
2111    pub fn with_primary_file_name<S: AsRef<str>>(mut self, name: S) -> Self {
2112        self.primary_file_name = Some(name.as_ref().to_owned());
2113        self
2114    }
2115
2116    /// Sets the [`IncludeFileHandler`] for this parser.
2117    ///
2118    /// The include file handler is responsible for resolving `include::`
2119    /// directives encountered during preprocessing. If no handler is provided,
2120    /// include directives will be ignored.
2121    ///
2122    /// [`IncludeFileHandler`]: crate::parser::IncludeFileHandler
2123    #[must_use]
2124    pub fn with_include_file_handler<IFH: IncludeFileHandler + 'static>(
2125        mut self,
2126        handler: IFH,
2127    ) -> Self {
2128        self.include_file_handler = Some(Rc::new(handler));
2129        self
2130    }
2131
2132    /// Sets the [`DocinfoFileHandler`] for this parser.
2133    ///
2134    /// The docinfo file handler is responsible for providing the content of
2135    /// [docinfo files] requested while resolving a document's docinfo (see the
2136    /// `docinfo` attribute). If no handler is provided, no docinfo content is
2137    /// resolved and [`Document::docinfo`] returns an empty string for every
2138    /// location.
2139    ///
2140    /// [`DocinfoFileHandler`]: crate::parser::DocinfoFileHandler
2141    /// [docinfo files]: https://docs.asciidoctor.org/asciidoc/latest/docinfo/
2142    /// [`Document::docinfo`]: crate::Document::docinfo
2143    #[must_use]
2144    pub fn with_docinfo_file_handler<DFH: DocinfoFileHandler + 'static>(
2145        mut self,
2146        handler: DFH,
2147    ) -> Self {
2148        self.docinfo_file_handler = Some(Rc::new(handler));
2149        self
2150    }
2151
2152    /// Sets the [`SvgFileHandler`] for this parser.
2153    ///
2154    /// The SVG file handler is responsible for providing the raw contents of an
2155    /// SVG file requested by an inline image with the `inline` option (e.g.
2156    /// `image:diagram.svg[opts=inline]`). If no handler is provided, inline SVG
2157    /// images fall back to rendering their alt text.
2158    ///
2159    /// [`SvgFileHandler`]: crate::parser::SvgFileHandler
2160    #[must_use]
2161    pub fn with_svg_file_handler<SFH: SvgFileHandler + 'static>(mut self, handler: SFH) -> Self {
2162        self.svg_file_handler = Some(Rc::new(handler));
2163        self
2164    }
2165
2166    /// Sets the [`ImageFileHandler`] for this parser.
2167    ///
2168    /// The image file handler is responsible for providing the raw bytes of an
2169    /// image that must be embedded as a `data:` URI – i.e. when the `data-uri`
2170    /// document attribute is set and the safe mode is below
2171    /// [`SafeMode::Secure`]. If no handler is provided (or it cannot find the
2172    /// file), such images fall back to an ordinary web path, exactly as if
2173    /// `data-uri` were not set.
2174    ///
2175    /// [`ImageFileHandler`]: crate::parser::ImageFileHandler
2176    #[must_use]
2177    pub fn with_image_file_handler<IFH: ImageFileHandler + 'static>(
2178        mut self,
2179        handler: IFH,
2180    ) -> Self {
2181        self.image_file_handler = Some(Rc::new(handler));
2182        self
2183    }
2184
2185    /// Sets the [`PathResolver`] for this parser.
2186    ///
2187    /// The path resolver turns an asset target (an image `src`, a stylesheet
2188    /// href, and so on) into the clean, resolved path that appears in the
2189    /// rendered output. The default is [`DefaultPathResolver`], which mirrors
2190    /// Ruby Asciidoctor. A host that needs custom path or URL rewriting – a
2191    /// virtual filesystem, a content root, URL slugs – can supply its own
2192    /// implementation here.
2193    ///
2194    /// [`PathResolver`]: crate::parser::PathResolver
2195    /// [`DefaultPathResolver`]: crate::parser::DefaultPathResolver
2196    #[must_use]
2197    pub fn with_path_resolver<PR: PathResolver + 'static>(mut self, path_resolver: PR) -> Self {
2198        self.path_resolver = Rc::new(path_resolver);
2199        self
2200    }
2201
2202    /// Enables or disables cataloging of referenced image assets.
2203    ///
2204    /// When enabled (Asciidoctor's `catalog_assets` API option), each image
2205    /// referenced by an `image:`/`image::` macro is recorded in the document
2206    /// catalog and can be retrieved afterward via
2207    /// [`Catalog::images`](crate::document::Catalog::images). The default is
2208    /// disabled, in which case no image references are recorded.
2209    #[must_use]
2210    pub fn with_catalog_assets(mut self, catalog_assets: bool) -> Self {
2211        self.catalog_assets = catalog_assets;
2212        self
2213    }
2214
2215    /// Sets the [`SafeMode`] under which the document is parsed and rendered.
2216    ///
2217    /// The default is [`SafeMode::Secure`], the most conservative setting.
2218    /// Relaxing the safe mode enables security-sensitive rendering behavior,
2219    /// such as rendering an interactive SVG image as an `<object>` element.
2220    ///
2221    /// [`SafeMode`]: crate::SafeMode
2222    #[must_use]
2223    pub fn with_safe_mode(mut self, safe: SafeMode) -> Self {
2224        self.safe = safe;
2225        self.apply_safe_mode_attributes();
2226
2227        self.capture_attribute_baseline();
2228
2229        self
2230    }
2231
2232    /// Overrides the `safe-mode-*` family of [intrinsic attributes] from the
2233    /// current safe mode.
2234    ///
2235    /// These attributes let a document (or a downstream converter) inspect the
2236    /// security mode under which it is being processed:
2237    ///
2238    /// * `safe-mode-level` – the numeric level (`0`, `1`, `10`, or `20`).
2239    /// * `safe-mode-name` – the lowercase mode name (`unsafe`, `safe`,
2240    ///   `server`, or `secure`).
2241    /// * `safe-mode-<name>` – a single flag attribute (set to an empty value)
2242    ///   naming the active mode; the flags for the other modes are absent so
2243    ///   that a reference to them resolves literally.
2244    ///
2245    /// Only `safe-mode-level` and `safe-mode-name` are stored here (shadowing
2246    /// their built-in Secure-mode defaults). The active `safe-mode-<name>` flag
2247    /// is synthesized on the fly from `safe-mode-name` (see
2248    /// [`synthesized_attr`]), so exactly one flag is ever defined and the
2249    /// inactive flags stay absent without any per-mode bookkeeping here.
2250    ///
2251    /// All of these are read-only from the document's perspective (they can
2252    /// only be established via the API), matching Ruby Asciidoctor.
2253    ///
2254    /// [intrinsic attributes]: https://docs.asciidoctor.org/asciidoc/latest/attributes/document-attributes-ref/#intrinsic-attributes
2255    fn apply_safe_mode_attributes(&mut self) {
2256        let intrinsic = |value: InterpretedValue| AttributeValue {
2257            allowable_value: AllowableValue::Any,
2258            modification_context: ModificationContext::ApiOnly,
2259            silent_when_locked: false,
2260            value,
2261        };
2262
2263        let attrs = Arc::make_mut(&mut self.attribute_values);
2264        attrs.insert(
2265            "safe-mode-level".to_string(),
2266            intrinsic(InterpretedValue::Value(self.safe.level().to_string())),
2267        );
2268        attrs.insert(
2269            "safe-mode-name".to_string(),
2270            intrinsic(InterpretedValue::Value(self.safe.name().to_string())),
2271        );
2272
2273        // NOTE: `max-attribute-value-size` is deliberately *not* touched here.
2274        // Its Secure-only default is resolved as a mode-aware synthesized
2275        // attribute in [`effective_attribute`](Self::effective_attribute), so a
2276        // caller's explicit limit (which lives in `attribute_values`) is never
2277        // clobbered by a safe-mode change, whatever the builder-call order.
2278    }
2279
2280    /// Returns the [`SafeMode`] under which this parser operates.
2281    ///
2282    /// [`SafeMode`]: crate::SafeMode
2283    pub fn safe_mode(&self) -> SafeMode {
2284        self.safe
2285    }
2286
2287    /// Returns the [`ImageFileHandler`] registered on this parser, if any.
2288    ///
2289    /// A custom [`InlineSubstitutionRenderer`] that resolves image URIs itself
2290    /// (rather than inheriting [`image_uri`]'s default `data-uri` embedding)
2291    /// can use this to read an image's bytes through the same handler the
2292    /// built-in HTML renderer uses. Returns `None` when no handler was
2293    /// registered via [`with_image_file_handler`], in which case there is
2294    /// no way to embed images and a web path should be used instead.
2295    ///
2296    /// [`ImageFileHandler`]: crate::parser::ImageFileHandler
2297    /// [`InlineSubstitutionRenderer`]: crate::parser::InlineSubstitutionRenderer
2298    /// [`image_uri`]: crate::parser::InlineSubstitutionRenderer::image_uri
2299    /// [`with_image_file_handler`]: Self::with_image_file_handler
2300    pub fn image_file_handler(&self) -> Option<&dyn ImageFileHandler> {
2301        self.image_file_handler.as_deref()
2302    }
2303
2304    /// Returns the [`SvgFileHandler`] registered on this parser, if any.
2305    ///
2306    /// A custom [`InlineSubstitutionRenderer`] that renders inline SVG images
2307    /// itself (rather than inheriting [`render_image`]'s `opts=inline`
2308    /// handling) can use this to read an SVG's contents through the same
2309    /// handler the built-in HTML renderer uses. Returns `None` when no
2310    /// handler was registered via [`with_svg_file_handler`], in which case
2311    /// inline SVG contents are unavailable and the alt text should be used
2312    /// instead.
2313    ///
2314    /// [`SvgFileHandler`]: crate::parser::SvgFileHandler
2315    /// [`InlineSubstitutionRenderer`]: crate::parser::InlineSubstitutionRenderer
2316    /// [`render_image`]: crate::parser::InlineSubstitutionRenderer::render_image
2317    /// [`with_svg_file_handler`]: Self::with_svg_file_handler
2318    pub fn svg_file_handler(&self) -> Option<&dyn SvgFileHandler> {
2319        self.svg_file_handler.as_deref()
2320    }
2321
2322    /// Returns the document name (`docname`): the base name of the primary
2323    /// file, stripped of its directory and final extension.
2324    ///
2325    /// This is the `<docname>` used to build private docinfo file names (e.g.
2326    /// `mydoc-docinfo.html` for `mydoc.adoc`). Returns `None` when no primary
2327    /// file name has been set, in which case private docinfo files cannot be
2328    /// resolved.
2329    pub(crate) fn docname(&self) -> Option<String> {
2330        let primary = self.primary_file_name.as_deref()?;
2331
2332        // Strip the directory portion (handling both separators, since the
2333        // primary file name may have been supplied on either platform).
2334        let base = primary.rsplit(['/', '\\']).next().unwrap_or(primary);
2335
2336        // Strip a single trailing extension, if present. A leading-dot name
2337        // (e.g. `.adoc`) is treated as having no extension and is kept whole as
2338        // the stem, matching Ruby's `File.basename(".adoc", ".*")`.
2339        let stem = match base.rfind('.') {
2340            Some(0) | None => base,
2341            Some(idx) => &base[..idx],
2342        };
2343
2344        if stem.is_empty() {
2345            None
2346        } else {
2347            Some(stem.to_string())
2348        }
2349    }
2350
2351    /// Returns `true` if the AsciiDoc file named by `key` (an inter-document
2352    /// xref path – relative to this document, AsciiDoc extension removed) was
2353    /// included into this document *in full* by the preprocessor.
2354    ///
2355    /// A cross reference to such a file collapses to a same-document reference,
2356    /// since the file's anchors are now part of this document. Takes `&self` so
2357    /// it can be called from an inline-substitution
2358    /// [`Replacer`](regex::Replacer) that holds only a shared reference to
2359    /// the parser. See
2360    /// [`Catalog::include_is_full`](crate::document::Catalog::include_is_full).
2361    pub(crate) fn catalog_include_is_full(&self, key: &str) -> bool {
2362        self.catalog.borrow().include_is_full(key)
2363    }
2364
2365    /// Records an included AsciiDoc file in the document catalog's include
2366    /// registry, mid-parse.
2367    ///
2368    /// `Parser::parse_deferred` seeds the registry with the outermost
2369    /// document's own includes before parsing begins; this entry point is for
2370    /// an include performed while a nested scope with a shared catalog – an
2371    /// AsciiDoc table cell – is parsed. Takes `&self` for the same reason as
2372    /// [`catalog_include_is_full`](Self::catalog_include_is_full). See
2373    /// [`Catalog::register_include`](crate::document::Catalog::register_include).
2374    pub(crate) fn register_include(&self, key: &str, full: bool) {
2375        self.catalog.borrow_mut().register_include(key, full);
2376    }
2377
2378    /// Called from [`Header::parse()`] to accept or reject an attribute value.
2379    ///
2380    /// [`Header::parse()`]: crate::document::Header::parse
2381    pub(crate) fn set_attribute_from_header<'src>(
2382        &mut self,
2383        attr: &Attribute<'src>,
2384        warnings: &mut Vec<Warning<'src>>,
2385    ) {
2386        let attr_name = remap_attr_name(attr.name().data());
2387
2388        // The derived backend-family namespace is a read-only synthesized
2389        // intrinsic; a document must not write any of it (see
2390        // [`is_reserved_derived_attr`]).
2391        if is_reserved_derived_attr(&attr_name) {
2392            return;
2393        }
2394
2395        // Verify that we have permission to overwrite any existing attribute
2396        // value, considering both a per-parser entry and the shared built-in
2397        // default it would shadow (a built-in such as `sp` is `ApiOnly`).
2398        if let Some(existing_attr) = self.effective_attribute(&attr_name)
2399            && (existing_attr.modification_context == ModificationContext::ApiOnly
2400                || existing_attr.modification_context == ModificationContext::ApiOrDocumentBody)
2401        {
2402            // A silently-locked intrinsic rejects the write without recording a
2403            // warning (see `AttributeValue::silent_when_locked`).
2404            if !existing_attr.silent_when_locked {
2405                warnings.push(Warning {
2406                    source: attr.span(),
2407                    warning: WarningType::AttributeValueIsLocked(attr_name),
2408                    origin: None,
2409                });
2410            }
2411            return;
2412        }
2413
2414        let mut value = attr.value().clone();
2415
2416        if let InterpretedValue::Set = value
2417            && let Some(default_value) = self.default_attribute_values.get(&attr_name)
2418        {
2419            value = InterpretedValue::Value(default_value.clone());
2420        }
2421
2422        // A relative `leveloffset` (`+N` / `-N`) accumulates on top of the
2423        // offset already in effect; resolve it to an absolute value so the
2424        // stored attribute is always a plain integer, and warn if the result is
2425        // so extreme that no heading could ever land in the valid level range.
2426        if attr_name == "leveloffset" {
2427            value = self.resolve_leveloffset_and_warn(value, attr.span(), warnings);
2428        }
2429
2430        // Cap the resolved value at `max-attribute-value-size` bytes (a no-op
2431        // unless that limit is in force – by default, only under Secure).
2432        value = self.limit_attribute_value_size(value);
2433
2434        // `notitle` and `showtitle` are inverse spellings of one title-
2435        // visibility toggle; keep the partner in sync (see
2436        // [`apply_title_visibility_linkage`](Self::apply_title_visibility_linkage)).
2437        self.apply_title_visibility_linkage(
2438            &attr_name,
2439            &value,
2440            ModificationContext::Anywhere,
2441            false,
2442        );
2443
2444        let attribute_value = AttributeValue {
2445            allowable_value: AllowableValue::Any,
2446            modification_context: ModificationContext::Anywhere,
2447            silent_when_locked: false,
2448            value,
2449        };
2450
2451        // An explicit assignment supersedes (and resets) any counter of the same
2452        // name.
2453        self.counter_values.borrow_mut().remove(&attr_name);
2454
2455        // The derived `backend-html5-doctype-*` attribute tracks `doctype`
2456        // automatically (it is synthesized on lookup), so no refresh is needed.
2457        Arc::make_mut(&mut self.attribute_values).insert(attr_name, attribute_value);
2458    }
2459
2460    /// Called from [`Header::parse()`] for a value that is derived from parsing
2461    /// the header (except for attribute lines).
2462    ///
2463    /// [`Header::parse()`]: crate::document::Header::parse
2464    pub(crate) fn set_attribute_by_value_from_header<N: AsRef<str>, V: AsRef<str>>(
2465        &mut self,
2466        name: N,
2467        value: V,
2468    ) {
2469        let attr_name = remap_attr_name(name);
2470
2471        let attribute_value = AttributeValue {
2472            allowable_value: AllowableValue::Any,
2473            modification_context: ModificationContext::Anywhere,
2474            silent_when_locked: false,
2475            value: InterpretedValue::Value(value.as_ref().to_owned()),
2476        };
2477
2478        self.counter_values.borrow_mut().remove(&attr_name);
2479        Arc::make_mut(&mut self.attribute_values).insert(attr_name, attribute_value);
2480    }
2481
2482    /// Applies the `imagesdir`-relative default for the `iconsdir` attribute.
2483    ///
2484    /// The `iconsdir` attribute defaults to `{imagesdir}/icons`; when
2485    /// `imagesdir` is left empty this resolves to the built-in
2486    /// [`DEFAULT_ICONSDIR`] (`./images/icons`). When `imagesdir` is set to a
2487    /// non-empty value and `iconsdir` was left at its built-in default, the
2488    /// icons directory is derived as `{imagesdir}/icons`.
2489    ///
2490    /// The derivation is skipped – so an explicit `iconsdir` wins – when either
2491    /// the attribute was set in the header (`iconsdir_set_in_header`) or its
2492    /// resolved value differs from [`DEFAULT_ICONSDIR`] (which is how an
2493    /// override applied any other way, e.g. via the API, is detected). The one
2494    /// case this cannot detect is a non-header override whose value happens to
2495    /// equal the built-in default (e.g. an API caller setting `iconsdir` to
2496    /// exactly `./images/icons`): it is indistinguishable from the default and
2497    /// so is re-derived. That combination is contradictory in practice (it
2498    /// pins `iconsdir` to the value it would take were `imagesdir` unset) and
2499    /// is not worth a dedicated provenance flag.
2500    ///
2501    /// This is called once, after the document header is parsed, mirroring
2502    /// Asciidoctor's document-initialization timing (a later `imagesdir` change
2503    /// in the document body does not retroactively re-derive `iconsdir`). See
2504    /// icons-image.adoc.
2505    ///
2506    /// [`DEFAULT_ICONSDIR`]: super::built_in_attrs::DEFAULT_ICONSDIR
2507    pub(crate) fn apply_iconsdir_default(&mut self, iconsdir_set_in_header: bool) {
2508        if iconsdir_set_in_header {
2509            return;
2510        }
2511
2512        // Preserve any override whose value differs from the built-in default
2513        // (e.g. one applied via the API); only the built-in default itself is
2514        // eligible for `imagesdir`-relative derivation. See the doc comment for
2515        // the one indistinguishable corner case.
2516        if self.attribute_value("iconsdir").as_maybe_str()
2517            != Some(super::built_in_attrs::DEFAULT_ICONSDIR)
2518        {
2519            return;
2520        }
2521
2522        let imagesdir = self.attribute_value("imagesdir");
2523        let derived = match imagesdir.as_maybe_str().filter(|d| !d.is_empty()) {
2524            Some(dir) => format!("{}/icons", dir.trim_end_matches('/')),
2525            None => return,
2526        };
2527
2528        self.set_attribute_by_value_from_header("iconsdir", derived);
2529    }
2530
2531    /// Called while parsing a block (see [`Block::parse_with_outcome()`]) to
2532    /// accept or reject an attribute value from a document (body) attribute.
2533    ///
2534    /// [`Block::parse_with_outcome()`]: crate::blocks::Block::parse_with_outcome
2535    pub(crate) fn set_attribute_from_body<'src>(
2536        &mut self,
2537        attr: &Attribute<'src>,
2538        warnings: &mut Vec<Warning<'src>>,
2539    ) {
2540        let attr_name = remap_attr_name(attr.name().data());
2541
2542        // The derived backend-family namespace is a read-only synthesized
2543        // intrinsic; a document must not write any of it (see
2544        // [`is_reserved_derived_attr`]).
2545        if is_reserved_derived_attr(&attr_name) {
2546            return;
2547        }
2548
2549        // An attribute inherited from the parent document of an AsciiDoc table
2550        // cell is locked for the duration of that cell: a body assignment to it
2551        // is silently ignored (no warning), matching Asciidoctor.
2552        if self.locked_attribute_names.contains(attr_name.as_str()) {
2553            return;
2554        }
2555
2556        // Verify that we have permission to overwrite any existing attribute
2557        // value, considering both a per-parser entry and the shared built-in
2558        // default it would shadow.
2559        if let Some(existing_attr) = self.effective_attribute(&attr_name)
2560            && (existing_attr.modification_context != ModificationContext::Anywhere
2561                && existing_attr.modification_context != ModificationContext::ApiOrDocumentBody)
2562        {
2563            // A silently-locked intrinsic rejects the write without recording a
2564            // warning (see `AttributeValue::silent_when_locked`).
2565            if !existing_attr.silent_when_locked {
2566                warnings.push(Warning {
2567                    source: attr.span(),
2568                    warning: WarningType::AttributeValueIsLocked(attr_name),
2569                    origin: None,
2570                });
2571            }
2572            return;
2573        }
2574
2575        let mut value = attr.value().clone();
2576
2577        // A relative `leveloffset` (`+N` / `-N`) accumulates on top of the
2578        // offset already in effect; resolve it to an absolute value so the
2579        // stored attribute is always a plain integer, and warn if the result is
2580        // so extreme that no heading could ever land in the valid level range.
2581        if attr_name == "leveloffset" {
2582            value = self.resolve_leveloffset_and_warn(value, attr.span(), warnings);
2583        }
2584
2585        // Cap the resolved value at `max-attribute-value-size` bytes (a no-op
2586        // unless that limit is in force – by default, only under Secure).
2587        value = self.limit_attribute_value_size(value);
2588
2589        // `notitle` and `showtitle` are inverse spellings of one title-
2590        // visibility toggle; keep the partner in sync (see
2591        // [`apply_title_visibility_linkage`](Self::apply_title_visibility_linkage)).
2592        self.apply_title_visibility_linkage(
2593            &attr_name,
2594            &value,
2595            ModificationContext::Anywhere,
2596            false,
2597        );
2598
2599        let attribute_value = AttributeValue {
2600            allowable_value: AllowableValue::Any,
2601            modification_context: ModificationContext::Anywhere,
2602            silent_when_locked: false,
2603            value,
2604        };
2605
2606        // An explicit assignment supersedes (and resets) any counter of the same
2607        // name. This is what lets `:!name:` reset a counter.
2608        self.counter_values.borrow_mut().remove(&attr_name);
2609
2610        // The derived `backend-html5-doctype-*` attribute tracks `doctype`
2611        // automatically (it is synthesized on lookup), so no refresh is needed.
2612        Arc::make_mut(&mut self.attribute_values).insert(attr_name, attribute_value);
2613    }
2614
2615    /// Unlocks each *flexible* document attribute ([`FLEXIBLE_ATTRIBUTES`],
2616    /// currently just `sectnums`) that was supplied *set* through the API, so a
2617    /// later document-body assignment may still toggle it.
2618    ///
2619    /// Mirrors the flexible-attribute unfreeze at the end of Asciidoctor's
2620    /// `save_attributes` (run by `finalize_header`, after the header is parsed
2621    /// and before the body): an API attribute override whose value is *truthy*
2622    /// is dropped from the locked overrides, while one whose value is an
2623    /// [unset] (from `numbered!` / `sectnums!`) is kept locked. That asymmetry
2624    /// is exactly what lets an API-*enabled* `numbered` still be toggled off by
2625    /// a body `:numbered!:`, while an API-*disabled* `numbered!` stays
2626    /// permanently unnumbered even across a later `:numbered:`.
2627    ///
2628    /// Called once, for the top-level document only – Asciidoctor guards the
2629    /// unfreeze with `unless @parent_document`, and an AsciiDoc table cell
2630    /// never reaches this path. This must *not* recapture the attribute
2631    /// baseline: the unlock is a per-parse effect, so a `Parser` reused across
2632    /// documents re-derives it from the still-locked API override each time.
2633    ///
2634    /// [unset]: https://docs.asciidoctor.org/asciidoc/latest/attributes/unset-attributes/
2635    pub(crate) fn unlock_flexible_attributes(&mut self) {
2636        for name in FLEXIBLE_ATTRIBUTES {
2637            // Only an API-set (`ApiOnly`, i.e. locked) override with a value
2638            // that is not an explicit unset is unfrozen; everything else is
2639            // left exactly as it stands.
2640            if let Some(existing) = self.attribute_values.get(name)
2641                && existing.modification_context == ModificationContext::ApiOnly
2642                && existing.value != InterpretedValue::Unset
2643            {
2644                let unlocked = AttributeValue {
2645                    modification_context: ModificationContext::Anywhere,
2646                    silent_when_locked: false,
2647                    ..existing.clone()
2648                };
2649
2650                Arc::make_mut(&mut self.attribute_values).insert(name.to_string(), unlocked);
2651            }
2652        }
2653    }
2654
2655    /// Assign the next section number for a given level.
2656    pub(crate) fn assign_section_number(&mut self, level: usize) -> SectionNumber {
2657        match self.topmost_section_type {
2658            SectionType::Appendix => {
2659                self.last_appendix_section_number.assign_next_number(level);
2660                self.last_appendix_section_number.clone()
2661            }
2662
2663            // `topmost_section_type` is only ever `Normal` or `Appendix`: a
2664            // discrete heading never becomes the topmost section type (see
2665            // `SectionBlock::parse`). `Discrete` therefore cannot reach this
2666            // point, so it is folded in with `Normal` rather than carried as a
2667            // separate, untestable arm.
2668            SectionType::Normal | SectionType::Discrete => {
2669                self.last_section_number.assign_next_number(level);
2670                self.last_section_number.clone()
2671            }
2672        }
2673    }
2674
2675    /// Resolves a [counter] of the given `name`, advancing it to the next value
2676    /// in its sequence and returning that value.
2677    ///
2678    /// A counter is a specialized document attribute: its value is stored as
2679    /// (and read back from) the attribute of the same name, so a later
2680    /// `{name}` reference shows the current value and an attribute assignment
2681    /// such as `:!name:` resets it. Each resolution advances the counter:
2682    ///
2683    /// * an integer value is incremented (`1` -> `2`);
2684    /// * any other value is advanced like Ruby's `String#succ` (`a` -> `b`, `z`
2685    ///   -> `aa`, `Az` -> `Ba`), matching Asciidoctor.
2686    ///
2687    /// `seed` (from the `{counter:name:seed}` form) supplies the first value,
2688    /// but only when the counter is currently unset; otherwise it is ignored.
2689    /// With no seed the sequence starts at `1`.
2690    ///
2691    /// This mirrors Asciidoctor's `Document#counter`.
2692    ///
2693    /// [counter]: https://docs.asciidoctor.org/asciidoc/latest/attributes/counters/
2694    pub(crate) fn counter(&self, name: &str, seed: Option<&str>) -> String {
2695        self.counter_impl(name, seed, false)
2696    }
2697
2698    /// Like [`counter`](Self::counter), but the advanced value stays readable
2699    /// as the attribute of the same name even when that attribute is
2700    /// *locked* (API-set or a locked built-in). This is the captioning
2701    /// counter, used for the `<context>-number` of a numbered block.
2702    ///
2703    /// Mirrors Asciidoctor's `increment_and_store_counter`: it too advances a
2704    /// locked counter, and its block attribute entry is replayed onto the
2705    /// document attributes during conversion, so a locked `example-number`
2706    /// reads back as its latest counter value (unlike a plain inline
2707    /// `{counter:…}`, which leaves the locked value in place).
2708    pub(crate) fn counter_for_caption(&self, name: &str, seed: Option<&str>) -> String {
2709        self.counter_impl(name, seed, true)
2710    }
2711
2712    /// Advances the `name` counter and returns its new value. `seed` supplies
2713    /// the starting value when the counter has no current value to advance
2714    /// from.
2715    ///
2716    /// A counter reads the current value to produce (and display) the next one.
2717    /// For an unlocked attribute the advanced value is stored in the readable
2718    /// [`counter_values`](Self::counter_values) overlay, so a later reference
2719    /// reads it. For a *locked* attribute – one set via the API, or a locked
2720    /// built-in such as `max-include-depth` – the write path depends on the
2721    /// caller:
2722    ///
2723    /// * `commit_when_locked` (the captioning counter): the value is stored in
2724    ///   the readable overlay anyway, matching Asciidoctor's
2725    ///   `increment_and_store_counter`, whose block attribute entry is replayed
2726    ///   onto the document attributes during conversion.
2727    /// * otherwise (an inline `{counter:…}` / `{counter2:…}` directive): the
2728    ///   running value is kept in the private
2729    ///   [`locked_counter_values`](Self::locked_counter_values) map instead, so
2730    ///   the sequence still advances across repeated references while a plain
2731    ///   reference to the attribute continues to read the locked value. This
2732    ///   mirrors Asciidoctor's `Document#counter`, which advances `@counters`
2733    ///   but leaves `@attributes` untouched while the attribute is
2734    ///   `attribute_locked?`.
2735    fn counter_impl(&self, name: &str, seed: Option<&str>, commit_when_locked: bool) -> String {
2736        let use_private_state = !commit_when_locked && self.attribute_is_locked(name);
2737
2738        // The value to advance from: the private running state first (only
2739        // populated when it is in use), otherwise the current readable value of
2740        // the attribute (which, for an unlocked counter, already reflects the
2741        // overlay).
2742        let current = if use_private_state {
2743            self.locked_counter_values.borrow().get(name).cloned()
2744        } else {
2745            None
2746        }
2747        .or_else(|| match self.attribute_value(name) {
2748            InterpretedValue::Value(current) if !current.is_empty() => Some(current),
2749            _ => None,
2750        });
2751
2752        let next = match current {
2753            Some(current) => next_counter_value(&current),
2754            None => match seed {
2755                Some(seed) if !seed.is_empty() => seed.to_string(),
2756                _ => "1".to_string(),
2757            },
2758        };
2759
2760        if use_private_state {
2761            self.locked_counter_values
2762                .borrow_mut()
2763                .insert(name.to_string(), next.clone());
2764        } else {
2765            self.counter_values
2766                .borrow_mut()
2767                .insert(name.to_string(), next.clone());
2768        }
2769
2770        next
2771    }
2772
2773    /// Reports whether `name` currently resolves to an attribute that is
2774    /// *locked* against modification by a counter: it has an effective value
2775    /// whose [`ModificationContext`] is
2776    /// [`ApiOnly`](ModificationContext::ApiOnly) – an API-set override or a
2777    /// locked built-in such as `max-include-depth`.
2778    ///
2779    /// This mirrors Asciidoctor's `Document#attribute_locked?`, which is `true`
2780    /// exactly for an attribute supplied through the API (its
2781    /// `@attribute_overrides`). It is deliberately *narrower* than the
2782    /// write-permission check in
2783    /// [`set_attribute_from_body`](Self::set_attribute_from_body): a
2784    /// header-only attribute such as an unset `outfilesuffix`
2785    /// ([`ApiOrHeader`](ModificationContext::ApiOrHeader)) cannot be assigned
2786    /// from the body, yet a counter *may* advance it (matching Asciidoctor,
2787    /// where `{counter:outfilesuffix}` moves it while it is not API-locked).
2788    fn attribute_is_locked(&self, name: &str) -> bool {
2789        self.effective_attribute(name)
2790            .is_some_and(|a| a.modification_context == ModificationContext::ApiOnly)
2791    }
2792}
2793
2794/// Whether a `leveloffset` of `offset` leaves at least one syntactic heading
2795/// level able to land inside the supported section-level range.
2796///
2797/// Syntactic heading levels run 0 (`=`) through 5 (`======`) and valid section
2798/// levels run 1 through 5, so an offset keeps some heading in range only while
2799/// it stays within `1 - 5 ..= 5 - 0`, i.e. `-4..=5`. Outside that window every
2800/// heading is clamped, so the offset can never place a heading at its intended
2801/// level.
2802fn leveloffset_admits_any_heading(offset: i32) -> bool {
2803    (-4..=5).contains(&offset)
2804}
2805
2806/// Advances a counter value to the next value in its sequence, mirroring
2807/// Asciidoctor's `Helpers.nextval`.
2808///
2809/// A canonical integer string (one that round-trips through integer parsing,
2810/// e.g. `7` but not `07` or `+7`) is incremented numerically. Anything else is
2811/// advanced with [`string_succ`].
2812fn next_counter_value(current: &str) -> String {
2813    if let Ok(n) = current.parse::<i64>()
2814        && n.to_string() == current
2815    {
2816        // `saturating_add` keeps a counter that has somehow reached `i64::MAX`
2817        // pinned there rather than panicking (debug) or wrapping (release).
2818        return n.saturating_add(1).to_string();
2819    }
2820
2821    string_succ(current)
2822}
2823
2824/// Returns the successor of a string, mirroring Ruby's `String#succ` for the
2825/// ASCII cases that AsciiDoc counters can produce.
2826///
2827/// The right-most alphanumeric character is incremented within its own class
2828/// (digits, lowercase letters, uppercase letters), carrying leftward on
2829/// wrap-around (`9` -> `0`, `z` -> `a`, `Z` -> `A`) and prepending a fresh
2830/// leading character (`1`, `a`, or `A`) when the carry runs off the front
2831/// (`z` -> `aa`, `Zz` -> `AAa`). A string with no alphanumeric characters has
2832/// the code point of its last character incremented.
2833fn string_succ(current: &str) -> String {
2834    let chars: Vec<char> = current.chars().collect();
2835
2836    // Without an alphanumeric to carry through, Ruby increments the code point
2837    // of the final character.
2838    if !chars.iter().any(char::is_ascii_alphanumeric) {
2839        let mut chars = chars;
2840        if let Some(last) = chars.last_mut() {
2841            *last = char::from_u32(*last as u32 + 1).unwrap_or(*last);
2842        }
2843        return chars.into_iter().collect();
2844    }
2845
2846    // Walk right to left. `carrying` stays true while we are still looking for
2847    // (or carrying through) the alphanumeric run: trailing non-alphanumeric
2848    // characters are passed over unchanged, then the right-most alphanumeric is
2849    // incremented within its class and any wrap-around carries leftward to the
2850    // next alphanumeric. When the carry runs off the front, a fresh leading
2851    // character of the same class is prepended (`z` -> `aa`, `9` -> `10`).
2852    let mut out_rev: Vec<char> = Vec::with_capacity(chars.len() + 1);
2853    let mut carrying = true;
2854    let mut lead = '1';
2855
2856    for &c in chars.iter().rev() {
2857        if carrying && c.is_ascii_alphanumeric() {
2858            // Increment within the character's class, carrying on wrap-around.
2859            // The arms are exhaustive over ASCII alphanumerics, so the catch-all
2860            // can only be `Z` (the one value not matched above).
2861            let (next, carry) = match c {
2862                '0'..='8' | 'a'..='y' | 'A'..='Y' => ((c as u8 + 1) as char, false),
2863                '9' => ('0', true),
2864                'z' => ('a', true),
2865                _ => ('A', true),
2866            };
2867            out_rev.push(next);
2868            carrying = carry;
2869
2870            // On a carry, remember the class of leading character to prepend if
2871            // the carry runs off the front; `next` is `0`, `a`, or `A` here.
2872            lead = match next {
2873                '0' => '1',
2874                'a' => 'a',
2875                _ => 'A',
2876            };
2877        } else {
2878            // Either the carry is spent, or this is a trailing non-alphanumeric
2879            // we pass over while still searching for the run to increment.
2880            out_rev.push(c);
2881        }
2882    }
2883
2884    if carrying {
2885        out_rev.push(lead);
2886    }
2887
2888    out_rev.into_iter().rev().collect()
2889}
2890
2891/// Matches every character that Asciidoctor's `sanitize_attribute_name` strips
2892/// from an attribute name: anything that is not a [word character] (`\w`, i.e.
2893/// `\p{Word}`) or a hyphen. Mirrors Asciidoctor's `InvalidAttributeNameCharsRx`
2894/// (`/[^#{CC_WORD}-]/`).
2895///
2896/// [word character]: crate::internal::is_word_char
2897static INVALID_ATTR_NAME_CHARS: LazyLock<Regex> = LazyLock::new(|| {
2898    #[allow(clippy::unwrap_used)]
2899    Regex::new(r"[^\w-]").unwrap()
2900});
2901
2902fn remap_attr_name<N: AsRef<str>>(raw_attr_name: N) -> String {
2903    // Sanitize the name the way Asciidoctor's `sanitize_attribute_name` does:
2904    // drop every character that is not a word character or a hyphen, then
2905    // lower-case the result. This is what lets an attribute entry written as
2906    // `:Author Initials:` set the `authorinitials` attribute, `:Foo 3^ # -
2907    // Bar[:` set `foo3-bar`, and `:My frog:` set `myfrog`. Unicode word
2908    // characters are preserved, so `:café:` sets `café` and `:سمن:` sets `سمن`.
2909    //
2910    // The full Unicode case fold (Asciidoctor's `downcase`, not merely ASCII)
2911    // is what makes an attribute reference case-insensitive: an entry written
2912    // `:He-Man:` is reachable as `{he-man}` or `{HE-MAN}`. A reference is folded
2913    // through this same `to_lowercase()` before lookup (see `AttributeReplacer`
2914    // in `content::substitution_step`), so definition and reference stay
2915    // symmetric even when a fold expands a character (e.g. `İ` -> `i` + combining
2916    // dot): both sides land on the identical key.
2917    let attr_name: String = INVALID_ATTR_NAME_CHARS
2918        .replace_all(raw_attr_name.as_ref(), "")
2919        .to_lowercase();
2920
2921    // Some attribute names have aliases. Remap to the primary name.
2922    alias_attr_name(attr_name)
2923}
2924
2925/// Document attributes that are *flexible*: an API-supplied *set* value is
2926/// unlocked once the header is parsed so the document body may still toggle it,
2927/// while an API-supplied [unset] stays locked (see
2928/// [`unlock_flexible_attributes`](Parser::unlock_flexible_attributes)). Mirrors
2929/// Asciidoctor's `FLEXIBLE_ATTRIBUTES` constant, currently just `sectnums` (the
2930/// primary name of the `numbered` alias).
2931///
2932/// [unset]: https://docs.asciidoctor.org/asciidoc/latest/attributes/unset-attributes/
2933const FLEXIBLE_ATTRIBUTES: [&str; 1] = ["sectnums"];
2934
2935/// Remaps an attribute name that is a legacy alias to its primary name,
2936/// returning any other name unchanged.
2937///
2938/// `numbered` is a legacy alias for `sectnums`, and `hardbreaks` for
2939/// `hardbreaks-option`, so setting `numbered` sets `sectnums` (and `numbered!`
2940/// unsets it), and setting `hardbreaks` sets `hardbreaks-option`. Mirrors both
2941/// Asciidoctor's `Parser.store_attribute` (which renames a header/body
2942/// attribute entry before storing it) and its `Document#initialize` (which
2943/// renames the same two API-supplied attribute overrides: `attr_overrides`
2944/// `sectnums`/`hardbreaks-option` reassignment). Applying it on both paths is
2945/// what lets `-a hardbreaks` supplied through the API enable hard line breaks,
2946/// exactly as `:hardbreaks:` in the header does.
2947fn alias_attr_name(attr_name: String) -> String {
2948    match attr_name.as_str() {
2949        "hardbreaks" => "hardbreaks-option".to_string(),
2950        "numbered" => "sectnums".to_string(),
2951        _ => attr_name,
2952    }
2953}
2954
2955/// Returns `true` if `name` is a derived backend-family attribute whose
2956/// assignment must be rejected *even while it is inactive*, because the flag it
2957/// would name can become active later in the same parse and the stored override
2958/// would then shadow the read-only intrinsic:
2959///
2960/// * The bare derived values `basebackend` / `filetype` – always resolved on
2961///   the fly from `backend` (see [`derived_backend_value`]), never stored.
2962/// * The doctype-keyed flags `backend-<b>-doctype-<d>` /
2963///   `basebackend-<bb>-doctype-<d>` – the `doctype` component shifts mid-parse
2964///   (e.g. an AsciiDoc table cell that resets, then changes, its doctype), so
2965///   an assignment to an inactive one (`backend-html5-doctype-article` while
2966///   the doctype is `book`) must not be stored where it could shadow the
2967///   intrinsic once the doctype switches.
2968///
2969/// The remaining flag names (`backend-<b>`, `basebackend-<bb>`, `filetype-<f>`,
2970/// and bare `doctype-<d>`) are deliberately **not** reserved: rejecting them
2971/// would swallow author-defined attributes such as `:backend-custom:` or
2972/// `:doctype-draft:` (used as `ifdef` flags), which Asciidoctor keeps. The
2973/// *active* one of these is still write-protected by the normal permission
2974/// check, since [`synthesized_attr`] resolves it to a locked intrinsic.
2975fn is_reserved_derived_attr(name: &str) -> bool {
2976    is_derived_backend_value(name)
2977        || ((name.starts_with("backend-") || name.starts_with("basebackend-"))
2978            && name.contains("-doctype-"))
2979}
2980
2981#[cfg(test)]
2982mod tests {
2983    #![allow(clippy::panic)]
2984    #![allow(clippy::unwrap_used)]
2985
2986    use crate::{
2987        attributes::Attrlist,
2988        blocks::Block,
2989        parser::{
2990            CharacterReplacementType, IconRenderParams, ImageRenderParams,
2991            InlineSubstitutionRenderer, LinkRenderParams, QuoteScope, QuoteType, SpecialCharacter,
2992        },
2993        tests::prelude::*,
2994    };
2995
2996    #[test]
2997    fn default_is_unset() {
2998        let p = Parser::default();
2999        assert_eq!(p.attribute_value("foo"), InterpretedValue::Unset);
3000    }
3001
3002    #[test]
3003    fn new_matches_default() {
3004        // `Parser::new()` is a discoverability alias for `Parser::default()`.
3005        let p = Parser::new();
3006        assert_eq!(p.attribute_value("foo"), InterpretedValue::Unset);
3007        assert_eq!(p.safe_mode(), Parser::default().safe_mode());
3008    }
3009
3010    mod attribute_state_between_parses {
3011        use crate::tests::prelude::*;
3012
3013        #[test]
3014        fn discovered_header_attribute_does_not_leak() {
3015            let mut parser = Parser::default();
3016
3017            // The first document defines `foo`; it is inspectable on the parser
3018            // once that parse returns.
3019            let _ = parser.parse(":foo: bar\n\nText.\n");
3020            assert_eq!(
3021                parser.attribute_value("foo"),
3022                InterpretedValue::Value("bar")
3023            );
3024
3025            // A second document that never defines `foo` must not observe the
3026            // first document's assignment.
3027            let _ = parser.parse("Text.\n");
3028            assert_eq!(parser.attribute_value("foo"), InterpretedValue::Unset);
3029        }
3030
3031        #[test]
3032        fn discovered_body_attribute_does_not_leak() {
3033            let mut parser = Parser::default();
3034
3035            // A body (not header) assignment leaks the same way a header one
3036            // would if the baseline were not restored.
3037            let _ = parser.parse("First.\n\n:mode: fast\n\nSecond.\n");
3038            assert_eq!(
3039                parser.attribute_value("mode"),
3040                InterpretedValue::Value("fast")
3041            );
3042
3043            let _ = parser.parse("Text.\n");
3044            assert_eq!(parser.attribute_value("mode"), InterpretedValue::Unset);
3045        }
3046
3047        #[test]
3048        fn configured_baseline_is_restored_each_parse() {
3049            let mut parser = Parser::default().with_intrinsic_attribute(
3050                "site",
3051                "prod",
3052                ModificationContext::Anywhere,
3053            );
3054
3055            // The first document overrides the API-configured value in its body.
3056            let _ = parser.parse(":site: dev\n\nText.\n");
3057            assert_eq!(
3058                parser.attribute_value("site"),
3059                InterpretedValue::Value("dev")
3060            );
3061
3062            // The next parse begins from the configured baseline, not the
3063            // previous document's override.
3064            let _ = parser.parse("Text.\n");
3065            assert_eq!(
3066                parser.attribute_value("site"),
3067                InterpretedValue::Value("prod")
3068            );
3069        }
3070
3071        #[test]
3072        fn reconfiguring_between_parses_updates_baseline() {
3073            let mut parser = Parser::default();
3074
3075            let _ = parser.parse("Text.\n");
3076            assert_eq!(parser.attribute_value("env"), InterpretedValue::Unset);
3077
3078            // A builder call between parses re-establishes the baseline for every
3079            // subsequent parse.
3080            parser = parser.with_intrinsic_attribute("env", "ci", ModificationContext::Anywhere);
3081
3082            let _ = parser.parse("Text.\n");
3083            assert_eq!(parser.attribute_value("env"), InterpretedValue::Value("ci"));
3084        }
3085
3086        #[test]
3087        fn leaked_attribute_does_not_affect_rendered_output() {
3088            let mut parser = Parser::default();
3089
3090            // The first document defines `who`, so `{who}` resolves for it.
3091            let doc1 = parser.parse(":who: world\n\nHello {who}.\n");
3092            assert_eq!(rendered_paragraphs(&doc1), vec!["Hello world."]);
3093
3094            // The second document does not define `who`; without the baseline
3095            // restore, `{who}` would still resolve to "world". Instead it stays
3096            // an unresolved literal reference.
3097            let doc2 = parser.parse("Hello {who}.\n");
3098            assert_eq!(rendered_paragraphs(&doc2), vec!["Hello {who}."]);
3099        }
3100    }
3101
3102    mod leading_byte_order_mark {
3103        use crate::tests::prelude::*;
3104
3105        #[test]
3106        fn bom_before_header_yields_title() {
3107            // A UTF-8 BOM precedes the document header. It must be stripped so
3108            // the `= ` title line is recognized rather than misparsed as a
3109            // paragraph.
3110            let doc = Parser::default().parse("\u{feff}= My Title\n\nbody");
3111
3112            assert_eq!(doc.header().title(), Some("My Title"));
3113            assert_eq!(rendered_paragraphs(&doc), vec!["body"]);
3114        }
3115
3116        #[test]
3117        fn bom_before_paragraph_is_stripped() {
3118            // With no header, the BOM must still be removed so it does not
3119            // become the first character of the paragraph's content.
3120            let doc = Parser::default().parse("\u{feff}Hello.\n");
3121
3122            assert_eq!(rendered_paragraphs(&doc), vec!["Hello."]);
3123        }
3124
3125        #[test]
3126        fn only_a_single_leading_bom_is_stripped() {
3127            // Only one leading BOM is stripped; a second U+FEFF is ordinary
3128            // content and survives into the paragraph text (matching
3129            // Asciidoctor).
3130            let doc = Parser::default().parse("\u{feff}\u{feff}Hello.\n");
3131
3132            assert_eq!(rendered_paragraphs(&doc), vec!["\u{feff}Hello."]);
3133        }
3134
3135        #[test]
3136        fn bom_precedes_front_matter_handling() {
3137            // The BOM is stripped before front-matter detection, so a `---`
3138            // fence that immediately follows the mark still opens front matter
3139            // when `skip-front-matter` is set.
3140            let doc = Parser::default()
3141                .with_intrinsic_attribute_bool(
3142                    "skip-front-matter",
3143                    true,
3144                    ModificationContext::ApiOnly,
3145                )
3146                .parse("\u{feff}---\ntitle: Doc\n---\n\n= My Title\n\nbody");
3147
3148            assert_eq!(
3149                doc.attribute_value("front-matter"),
3150                InterpretedValue::Value("title: Doc")
3151            );
3152            assert_eq!(doc.header().title(), Some("My Title"));
3153        }
3154    }
3155
3156    mod remap_attr_name {
3157        use super::super::remap_attr_name;
3158
3159        #[test]
3160        fn strips_non_word_and_lower_cases_ascii() {
3161            assert_eq!(remap_attr_name("Foo Bar"), "foobar");
3162            assert_eq!(remap_attr_name("Foo 3^ # - Bar["), "foo3-bar");
3163            assert_eq!(remap_attr_name("My frog"), "myfrog");
3164        }
3165
3166        #[test]
3167        fn remaps_legacy_aliases() {
3168            // `hardbreaks` and `numbered` are legacy aliases remapped to their
3169            // primary names, matching Asciidoctor's `Parser.store_attribute`.
3170            assert_eq!(remap_attr_name("hardbreaks"), "hardbreaks-option");
3171            assert_eq!(remap_attr_name("Hardbreaks"), "hardbreaks-option");
3172            assert_eq!(remap_attr_name("numbered"), "sectnums");
3173        }
3174
3175        #[test]
3176        fn preserves_unicode_word_characters() {
3177            // Unicode letters and digits are word characters, so they survive
3178            // sanitization; the `{café}` / `{سمن}` references then resolve.
3179            assert_eq!(remap_attr_name("café"), "café");
3180            assert_eq!(remap_attr_name("سمن"), "سمن");
3181        }
3182
3183        #[test]
3184        fn preserves_marks_and_join_controls() {
3185            // `\p{Word}` includes combining marks and join controls, so a
3186            // decomposed name and a name embedding a ZWNJ are not mangled.
3187            let decomposed = "cafe\u{301}";
3188            assert_eq!(remap_attr_name(decomposed), decomposed);
3189
3190            let with_zwnj = "\u{645}\u{200c}\u{646}";
3191            assert_eq!(remap_attr_name(with_zwnj), with_zwnj);
3192        }
3193
3194        #[test]
3195        fn folds_case_with_full_unicode() {
3196            // The name is folded with the full Unicode `to_lowercase()`, so a
3197            // reference lookup is case-insensitive. A fold that expands a
3198            // character (`İ` -> `i` + U+0307 combining dot above) is harmless:
3199            // an attribute reference is folded through the same function, so
3200            // definition and reference still land on the identical key.
3201            assert_eq!(remap_attr_name("He-Man"), "he-man");
3202            assert_eq!(remap_attr_name("İstanbul"), "i\u{307}stanbul");
3203            assert_eq!(remap_attr_name("İstanbul"), "İstanbul".to_lowercase());
3204        }
3205    }
3206
3207    #[test]
3208    fn attribute_reference_resolves_case_insensitively() {
3209        // A reference is folded with the same Unicode `to_lowercase()` used to
3210        // store the name, so any casing of the reference resolves the entry.
3211        let doc = Parser::default().parse(":He-Man: the foe\n\n{he-man} / {HE-MAN} / {He-Man}");
3212        assert_eq!(
3213            rendered_paragraphs(&doc),
3214            vec!["the foe / the foe / the foe"]
3215        );
3216    }
3217
3218    #[test]
3219    fn attribute_reference_case_fold_round_trips_when_it_expands() {
3220        // `İ` folds to `i` + U+0307 under `to_lowercase()`. Because both the
3221        // definition and the reference fold through that same function, the
3222        // entry stays reachable by its own spelling despite the expansion.
3223        let doc = Parser::default().parse(":İ: dotted\n\n{İ}");
3224        assert_eq!(rendered_paragraphs(&doc), vec!["dotted"]);
3225    }
3226
3227    #[test]
3228    fn unicode_attribute_reference_resolves_in_preprocessor() {
3229        // The preprocessor (conditional directives, include targets) resolves
3230        // `{name}` references with the same Unicode word-character class as the
3231        // main substitution pass, so a Unicode-named attribute drives an
3232        // `ifeval` condition. See #726.
3233        let doc = Parser::default()
3234            .parse(":café: yes\n\nifeval::[\"{café}\" == \"yes\"]\nShown.\nendif::[]");
3235        assert_eq!(rendered_paragraphs(&doc), vec!["Shown."]);
3236    }
3237
3238    #[test]
3239    fn case_insensitive_attribute_reference_resolves_in_preprocessor() {
3240        // The preprocessor folds a `{name}` reference the same way the main
3241        // substitution pass does, so a mismatched-case reference still drives an
3242        // `ifeval` condition.
3243        let doc = Parser::default()
3244            .parse(":Answer: yes\n\nifeval::[\"{answer}\" == \"yes\"]\nShown.\nendif::[]");
3245        assert_eq!(rendered_paragraphs(&doc), vec!["Shown."]);
3246    }
3247
3248    #[test]
3249    fn owned_cell_warning_is_recorded_only_inside_an_owned_cell_source() {
3250        use std::rc::Rc;
3251
3252        use crate::{
3253            parser::{SourceLine, SourceMap},
3254            warnings::WarningType,
3255        };
3256
3257        let mut p = Parser::default();
3258
3259        // Outside an owned cell source there is no map to resolve against, so a
3260        // recorded warning has no origin and is dropped rather than queued.
3261        assert!(!p.is_in_owned_cell_source());
3262        p.record_owned_cell_warning(
3263            1,
3264            WarningType::IncludeFileNotFound("x.adoc".to_owned()),
3265            None,
3266        );
3267        assert!(p.take_owned_cell_warnings().is_empty());
3268
3269        // An explicit origin override is queued even without a cell source map.
3270        p.record_owned_cell_warning(
3271            1,
3272            WarningType::UnterminatedConditionalDirective("ifdef::foo[]".to_owned()),
3273            Some(SourceLine(Some("inc.adoc".to_owned()), 3)),
3274        );
3275        let overridden = p.take_owned_cell_warnings();
3276        let [overridden] = overridden.as_slice() else {
3277            panic!("expected exactly one recorded warning, got {overridden:?}");
3278        };
3279        assert_eq!(
3280            overridden.origin,
3281            SourceLine(Some("inc.adoc".to_owned()), 3)
3282        );
3283
3284        // Publish a cell source map (output line 1 came from `cell.adoc` line 2,
3285        // the way the preprocessor would record an include-expanded cell).
3286        let mut sm = SourceMap::default();
3287        sm.append(1, Some("cell.adoc"), 2, crate::parser::Fidelity::Verbatim);
3288        p.push_owned_cell_source_map(Rc::new(sm));
3289        assert!(p.is_in_owned_cell_source());
3290
3291        // Now the same call resolves the line to its origin and queues the
3292        // warning with that pre-resolved (file, line).
3293        p.record_owned_cell_warning(
3294            1,
3295            WarningType::IncludeFileNotFound("y.adoc".to_owned()),
3296            None,
3297        );
3298        let recorded = p.take_owned_cell_warnings();
3299        let [recorded] = recorded.as_slice() else {
3300            panic!("expected exactly one recorded warning, got {recorded:?}");
3301        };
3302        assert_eq!(recorded.origin, SourceLine(Some("cell.adoc".to_owned()), 2));
3303        assert_eq!(
3304            recorded.warning,
3305            WarningType::IncludeFileNotFound("y.adoc".to_owned())
3306        );
3307
3308        // Taking drains the buffer, and popping restores the not-in-owned-cell
3309        // state.
3310        assert!(p.take_owned_cell_warnings().is_empty());
3311        p.pop_owned_cell_source_map();
3312        assert!(!p.is_in_owned_cell_source());
3313    }
3314
3315    #[test]
3316    fn creates_catalog_if_needed() {
3317        let mut p = Parser::default();
3318        let doc = p.parse("= Hello, World!\n\n== First Section Title");
3319        let cat = doc.catalog();
3320        assert!(cat.refs.contains_key("_first_section_title"));
3321
3322        let doc = p.parse("= Hello, World!\n\n== Second Section Title");
3323        let cat = doc.catalog();
3324        assert!(!cat.refs.contains_key("_first_section_title"));
3325        assert!(cat.refs.contains_key("_second_section_title"));
3326    }
3327
3328    #[test]
3329    fn with_intrinsic_attribute() {
3330        let p =
3331            Parser::default().with_intrinsic_attribute("foo", "bar", ModificationContext::Anywhere);
3332
3333        assert_eq!(p.attribute_value("foo"), InterpretedValue::Value("bar"));
3334        assert_eq!(p.attribute_value("foo2"), InterpretedValue::Unset);
3335
3336        assert!(p.is_attribute_set("foo"));
3337        assert!(!p.is_attribute_set("foo2"));
3338        assert!(!p.is_attribute_set("xyz"));
3339    }
3340
3341    #[test]
3342    fn with_intrinsic_attribute_remaps_legacy_aliases() {
3343        // An API-supplied `hardbreaks` (Asciidoctor's `-a hardbreaks`) is a
3344        // legacy alias remapped to `hardbreaks-option`, exactly as the same
3345        // attribute written as a header entry (`:hardbreaks:`) is. Without the
3346        // remap the API form is stored verbatim as `hardbreaks` and the
3347        // paragraph's post-replacement check (which consults
3348        // `hardbreaks-option`) never sees it.
3349        let mut p = Parser::default().with_intrinsic_attribute(
3350            "hardbreaks",
3351            "",
3352            ModificationContext::Anywhere,
3353        );
3354
3355        assert!(p.is_attribute_set("hardbreaks-option"));
3356
3357        // The end-to-end effect: each unwrapped line gains a hard line break.
3358        let doc = p.parse("First line\nSecond line");
3359        assert_eq!(
3360            rendered_paragraphs(&doc),
3361            vec!["First line<br>\nSecond line"]
3362        );
3363    }
3364
3365    #[test]
3366    fn api_set_flexible_attribute_is_unlocked_after_the_header() {
3367        // An API-*set* `sectnums` (here via the `numbered` alias) is a flexible
3368        // attribute: it seeds numbering on, but is unlocked once the header is
3369        // parsed so a body `:sectnums!:` still takes effect. Modeled as the
3370        // html5 converter applies it: an `ApiOnly` override on `numbered`.
3371        let mut p = Parser::default().with_intrinsic_attribute(
3372            "numbered",
3373            "",
3374            ModificationContext::ApiOnly,
3375        );
3376
3377        // Before any parse the alias is stored, locked, under `sectnums`.
3378        assert!(p.is_attribute_set("sectnums"));
3379
3380        // A body `:sectnums!:` turns numbering back off for the sections that
3381        // follow it: the unlock let the assignment through.
3382        let doc = p.parse("= Title\n\n== On\n\n:sectnums!:\n\n== Off");
3383        let nums: Vec<Option<String>> = crate::tests::prelude::all_sections(&doc)
3384            .iter()
3385            .map(|s| s.section_number().map(|n| n.to_string()))
3386            .collect();
3387
3388        assert_eq!(nums, vec![Some("1".to_string()), None]);
3389    }
3390
3391    #[test]
3392    fn api_unset_flexible_attribute_stays_locked() {
3393        // An API-*unset* `sectnums` (here via `numbered!`, i.e. the alias set to
3394        // `false`) stays locked: a body `:sectnums:` cannot re-enable numbering.
3395        let mut p = Parser::default().with_intrinsic_attribute_bool(
3396            "numbered",
3397            false,
3398            ModificationContext::ApiOnly,
3399        );
3400
3401        assert!(!p.is_attribute_set("sectnums"));
3402
3403        let doc = p.parse("= Title\n\n:sectnums:\n\n== Still Off");
3404        let nums: Vec<Option<String>> = crate::tests::prelude::all_sections(&doc)
3405            .iter()
3406            .map(|s| s.section_number().map(|n| n.to_string()))
3407            .collect();
3408
3409        assert_eq!(nums, vec![None]);
3410    }
3411
3412    // Under `SafeMode::Server` or greater, `docdir` reads as empty and
3413    // `docfile` is relativized against `docdir`; see #735 and the ported
3414    // upstream tests in `tests/asciidoctor_rb/attributes_test.rs`. These cover
3415    // crate-specific edge cases not exercised by the single upstream test.
3416    #[test]
3417    fn masks_docdir_and_docfile_under_secure_mode() {
3418        // Secure (the default) is stricter than Server, so masking also applies.
3419        let p = Parser::default()
3420            .with_intrinsic_attribute("docdir", "/some/dir", ModificationContext::ApiOnly)
3421            .with_intrinsic_attribute(
3422                "docfile",
3423                "/some/dir/sample.adoc",
3424                ModificationContext::ApiOnly,
3425            );
3426        assert_eq!(p.safe_mode(), SafeMode::Secure);
3427        assert_eq!(p.attribute_value("docdir"), InterpretedValue::Value(""));
3428        assert_eq!(
3429            p.attribute_value("docfile"),
3430            InterpretedValue::Value("sample.adoc")
3431        );
3432
3433        // The masked `docdir` is still a *set* (present) attribute.
3434        assert!(p.is_attribute_set("docdir"));
3435        assert!(p.has_attribute("docfile"));
3436    }
3437
3438    #[test]
3439    fn relativizes_docfile_in_a_subdirectory_of_docdir() {
3440        // A `docfile` nested below `docdir` keeps its sub-path relative to
3441        // `docdir` (not merely its base name), matching Asciidoctor's
3442        // `docfile[(docdir.length + 1)..-1]` slice.
3443        let p = Parser::default()
3444            .with_safe_mode(SafeMode::Server)
3445            .with_intrinsic_attribute("docdir", "/some/dir", ModificationContext::ApiOnly)
3446            .with_intrinsic_attribute(
3447                "docfile",
3448                "/some/dir/sub/sample.adoc",
3449                ModificationContext::ApiOnly,
3450            );
3451        assert_eq!(
3452            p.attribute_value("docfile"),
3453            InterpretedValue::Value("sub/sample.adoc")
3454        );
3455    }
3456
3457    #[test]
3458    fn relativizes_docfile_not_under_docdir_to_its_basename() {
3459        // An inconsistent `docdir` / `docfile` pairing (docfile not under
3460        // docdir) must not be truncated at an unrelated byte offset; it
3461        // relativizes to the base name instead (see #735 review feedback).
3462        let p = Parser::default()
3463            .with_safe_mode(SafeMode::Server)
3464            .with_intrinsic_attribute("docdir", "/some/dir", ModificationContext::ApiOnly)
3465            .with_intrinsic_attribute(
3466                "docfile",
3467                "/some/different/file.adoc",
3468                ModificationContext::ApiOnly,
3469            );
3470        assert_eq!(
3471            p.attribute_value("docfile"),
3472            InterpretedValue::Value("file.adoc")
3473        );
3474    }
3475
3476    #[test]
3477    fn docfile_without_docdir_falls_back_to_basename_under_server_mode() {
3478        let p = Parser::default()
3479            .with_safe_mode(SafeMode::Server)
3480            .with_intrinsic_attribute(
3481                "docfile",
3482                "/some/dir/sample.adoc",
3483                ModificationContext::ApiOnly,
3484            );
3485        assert_eq!(
3486            p.attribute_value("docfile"),
3487            InterpretedValue::Value("sample.adoc")
3488        );
3489    }
3490
3491    #[test]
3492    fn does_not_mask_docdir_and_docfile_below_server_mode() {
3493        // Below Server, the API-provided values pass through verbatim.
3494        let p = Parser::default()
3495            .with_safe_mode(SafeMode::Safe)
3496            .with_intrinsic_attribute("docdir", "/some/dir", ModificationContext::ApiOnly)
3497            .with_intrinsic_attribute(
3498                "docfile",
3499                "/some/dir/sample.adoc",
3500                ModificationContext::ApiOnly,
3501            );
3502        assert_eq!(
3503            p.attribute_value("docdir"),
3504            InterpretedValue::Value("/some/dir")
3505        );
3506        assert_eq!(
3507            p.attribute_value("docfile"),
3508            InterpretedValue::Value("/some/dir/sample.adoc")
3509        );
3510    }
3511
3512    #[test]
3513    fn unset_docdir_and_docfile_stay_missing_under_server_mode() {
3514        // Masking never conjures a value for an attribute that was never set, so
3515        // a reference to an unset `docdir` / `docfile` still resolves as missing.
3516        let p = Parser::default().with_safe_mode(SafeMode::Server);
3517        assert_eq!(p.attribute_value("docdir"), InterpretedValue::Unset);
3518        assert_eq!(p.attribute_value("docfile"), InterpretedValue::Unset);
3519        assert!(!p.has_attribute("docdir"));
3520        assert!(!p.has_attribute("docfile"));
3521    }
3522
3523    #[test]
3524    fn leaves_non_string_docdir_and_docfile_untouched_under_server_mode() {
3525        // A `docdir` / `docfile` present as a boolean flag (not a path string)
3526        // carries no host path to leak, so the masking has nothing to blank or
3527        // relativize and leaves the (empty) `Set` value as-is.
3528        let p = Parser::default()
3529            .with_safe_mode(SafeMode::Server)
3530            .with_intrinsic_attribute_bool("docdir", true, ModificationContext::ApiOnly)
3531            .with_intrinsic_attribute_bool("docfile", true, ModificationContext::ApiOnly);
3532        assert_eq!(p.attribute_value("docdir"), InterpretedValue::Set);
3533        assert_eq!(p.attribute_value("docfile"), InterpretedValue::Set);
3534    }
3535
3536    #[test]
3537    fn with_intrinsic_attribute_set() {
3538        let p = Parser::default().with_intrinsic_attribute_bool(
3539            "foo",
3540            true,
3541            ModificationContext::Anywhere,
3542        );
3543
3544        assert_eq!(p.attribute_value("foo"), InterpretedValue::Set);
3545        assert_eq!(p.attribute_value("foo2"), InterpretedValue::Unset);
3546
3547        assert!(p.is_attribute_set("foo"));
3548        assert!(!p.is_attribute_set("foo2"));
3549        assert!(!p.is_attribute_set("xyz"));
3550    }
3551
3552    #[test]
3553    fn with_intrinsic_attribute_unset() {
3554        let p = Parser::default().with_intrinsic_attribute_bool(
3555            "foo",
3556            false,
3557            ModificationContext::Anywhere,
3558        );
3559
3560        assert_eq!(p.attribute_value("foo"), InterpretedValue::Unset);
3561        assert_eq!(p.attribute_value("foo2"), InterpretedValue::Unset);
3562
3563        assert!(!p.is_attribute_set("foo"));
3564        assert!(!p.is_attribute_set("foo2"));
3565        assert!(!p.is_attribute_set("xyz"));
3566    }
3567
3568    #[test]
3569    fn can_not_override_locked_default_value() {
3570        let mut parser = Parser::default();
3571
3572        let doc = parser.parse(":sp: not a space!");
3573
3574        assert_eq!(
3575            doc.warnings().next().unwrap().warning,
3576            WarningType::AttributeValueIsLocked("sp".to_owned())
3577        );
3578
3579        assert_eq!(parser.attribute_value("sp"), InterpretedValue::Value(" "));
3580    }
3581
3582    #[test]
3583    fn asciidoc_parser_version_is_predefined() {
3584        // The crate predefines `asciidoc-parser-version` with its own version
3585        // (the parser-specific counterpart of Ruby Asciidoctor's
3586        // `asciidoctor-version` intrinsic).
3587        let mut parser = Parser::default();
3588
3589        assert_eq!(
3590            parser.attribute_value("asciidoc-parser-version"),
3591            InterpretedValue::Value(env!("CARGO_PKG_VERSION"))
3592        );
3593
3594        // The value is available to attribute references and `ifeval`
3595        // expressions in document content.
3596        let doc = parser.parse(concat!(
3597            "= Title\n",
3598            "\n",
3599            "ifeval::['{asciidoc-parser-version}' >= '0.1.0']\n",
3600            "v{asciidoc-parser-version}\n",
3601            "endif::[]\n",
3602        ));
3603
3604        assert_eq!(
3605            rendered_paragraphs(&doc),
3606            vec![format!("v{}", env!("CARGO_PKG_VERSION"))]
3607        );
3608    }
3609
3610    #[test]
3611    fn asciidoc_parser_version_is_locked() {
3612        // The parser version describes the processor itself, so a document
3613        // assignment is rejected with a warning and the built-in value stays
3614        // in place.
3615        let mut parser = Parser::default();
3616
3617        let doc = parser.parse(":asciidoc-parser-version: 99.99.99");
3618
3619        assert_eq!(
3620            doc.warnings().next().unwrap().warning,
3621            WarningType::AttributeValueIsLocked("asciidoc-parser-version".to_owned())
3622        );
3623
3624        assert_eq!(
3625            parser.attribute_value("asciidoc-parser-version"),
3626            InterpretedValue::Value(env!("CARGO_PKG_VERSION"))
3627        );
3628    }
3629
3630    #[test]
3631    fn asciidoctor_version_is_predefined() {
3632        // The crate predefines `asciidoctor-version` with the Asciidoctor
3633        // release whose behavior it implements, so documents written against
3634        // Asciidoctor's own intrinsic behave the same here.
3635        let mut parser = Parser::default();
3636
3637        assert_eq!(
3638            parser.attribute_value("asciidoctor-version"),
3639            InterpretedValue::Value(crate::ASCIIDOCTOR_VERSION)
3640        );
3641
3642        // The value is available to `ifdef` gating and to attribute references
3643        // and `ifeval` expressions in document content.
3644        let doc = parser.parse(concat!(
3645            "= Title\n",
3646            "\n",
3647            "ifdef::asciidoctor-version[]\n",
3648            "ifeval::['{asciidoctor-version}' >= '0.1.0']\n",
3649            "v{asciidoctor-version}\n",
3650            "endif::[]\n",
3651            "endif::[]\n",
3652        ));
3653
3654        assert_eq!(
3655            rendered_paragraphs(&doc),
3656            vec![format!("v{}", crate::ASCIIDOCTOR_VERSION)]
3657        );
3658    }
3659
3660    #[test]
3661    fn asciidoctor_version_is_locked() {
3662        // Like its `asciidoc-parser-version` companion, this describes the
3663        // processor itself, so a document assignment is rejected with a warning
3664        // and the built-in value stays in place.
3665        let mut parser = Parser::default();
3666
3667        let doc = parser.parse(":asciidoctor-version: 99.99.99");
3668
3669        assert_eq!(
3670            doc.warnings().next().unwrap().warning,
3671            WarningType::AttributeValueIsLocked("asciidoctor-version".to_owned())
3672        );
3673
3674        assert_eq!(
3675            parser.attribute_value("asciidoctor-version"),
3676            InterpretedValue::Value(crate::ASCIIDOCTOR_VERSION)
3677        );
3678    }
3679
3680    #[test]
3681    fn asciidoctor_flag_is_predefined() {
3682        // The crate predefines the always-set `asciidoctor` boolean flag, so a
3683        // document guarding Asciidoctor-only content with `ifdef::asciidoctor[]`
3684        // behaves the same here. A `////` comment block containing a directive
3685        // that would corrupt it once the flag is defined must stay untouched
3686        // (see issue #810).
3687        let mut parser = Parser::default();
3688
3689        assert_eq!(parser.attribute_value("asciidoctor"), InterpretedValue::Set);
3690
3691        let doc = parser.parse(concat!(
3692            "= Title\n",
3693            "\n",
3694            "ifdef::asciidoctor[]\n",
3695            "shown when asciidoctor is set\n",
3696            "endif::[]\n",
3697            "\n",
3698            "////\n",
3699            "ifdef::asciidoctor[////]\n",
3700            "////\n",
3701            "\n",
3702            "line after comment block\n",
3703        ));
3704
3705        assert_eq!(
3706            rendered_paragraphs(&doc),
3707            vec![
3708                "shown when asciidoctor is set".to_owned(),
3709                "line after comment block".to_owned(),
3710            ]
3711        );
3712    }
3713
3714    #[test]
3715    fn asciidoctor_flag_is_locked() {
3716        // Like the version intrinsics, the flag describes the processor itself,
3717        // so a document assignment is rejected with a warning and the built-in
3718        // value stays in place.
3719        let mut parser = Parser::default();
3720
3721        let doc = parser.parse(":asciidoctor: 99.99.99");
3722
3723        assert_eq!(
3724            doc.warnings().next().unwrap().warning,
3725            WarningType::AttributeValueIsLocked("asciidoctor".to_owned())
3726        );
3727
3728        assert_eq!(parser.attribute_value("asciidoctor"), InterpretedValue::Set);
3729    }
3730
3731    #[test]
3732    fn asciidoc_parser_version_distinguishes_the_two_processors() {
3733        // Both version intrinsics are defined, so a document tells the
3734        // processors apart via `asciidoc-parser-version`, which Ruby
3735        // Asciidoctor does not define.
3736        let mut parser = Parser::default();
3737
3738        let doc = parser.parse(concat!(
3739            "= Title\n",
3740            "\n",
3741            "ifdef::asciidoc-parser-version[]\n",
3742            "This is asciidoc-parser.\n",
3743            "endif::[]\n",
3744        ));
3745
3746        assert_eq!(rendered_paragraphs(&doc), vec!["This is asciidoc-parser."]);
3747    }
3748
3749    #[test]
3750    fn silently_locked_intrinsic_rejects_header_and_body_without_warning() {
3751        // A silently-locked `ApiOnly` intrinsic (as a converter would seed a
3752        // safe-mode-restricted attribute) rejects both a header assignment and a
3753        // body assignment of the same name, leaving the value unchanged and
3754        // recording no warning.
3755        let mut parser = Parser::default().with_intrinsic_attribute_silent(
3756            "backend",
3757            "html5",
3758            ModificationContext::ApiOnly,
3759        );
3760
3761        let doc = parser.parse(concat!(
3762            "= Title\n",
3763            ":backend: docbook5\n",
3764            "\n",
3765            "Body paragraph.\n",
3766            "\n",
3767            ":backend: manpage\n",
3768        ));
3769
3770        assert_eq!(doc.warnings().count(), 0);
3771        assert_eq!(
3772            parser.attribute_value("backend"),
3773            InterpretedValue::Value("html5")
3774        );
3775    }
3776
3777    #[test]
3778    fn silently_locked_bool_intrinsic_rejects_without_warning() {
3779        let mut parser = Parser::default().with_intrinsic_attribute_bool_silent(
3780            "sectids",
3781            true,
3782            ModificationContext::ApiOnly,
3783        );
3784
3785        let doc = parser.parse(concat!("= Title\n", ":!sectids:\n"));
3786
3787        assert_eq!(doc.warnings().count(), 0);
3788        assert_eq!(parser.attribute_value("sectids"), InterpretedValue::Set);
3789    }
3790
3791    #[test]
3792    fn silently_locked_bool_intrinsic_false_is_unset() {
3793        // A `false` flag records an `Unset` tombstone, and a locked (`ApiOnly`)
3794        // attribute rejects a document body reassignment without warning.
3795        let mut parser = Parser::default().with_intrinsic_attribute_bool_silent(
3796            "sectids",
3797            false,
3798            ModificationContext::ApiOnly,
3799        );
3800
3801        let doc = parser.parse(concat!("= Title\n", ":sectids:\n"));
3802
3803        assert_eq!(doc.warnings().count(), 0);
3804        assert_eq!(parser.attribute_value("sectids"), InterpretedValue::Unset);
3805    }
3806
3807    #[test]
3808    fn normally_locked_intrinsic_still_warns() {
3809        // Regression: a non-silent `ApiOnly` intrinsic still records
3810        // `AttributeValueIsLocked` when the document tries to reassign it.
3811        let mut parser = Parser::default().with_intrinsic_attribute(
3812            "backend",
3813            "html5",
3814            ModificationContext::ApiOnly,
3815        );
3816
3817        let doc = parser.parse(concat!("= Title\n", ":backend: docbook5\n"));
3818
3819        assert_eq!(
3820            doc.warnings().next().unwrap().warning,
3821            WarningType::AttributeValueIsLocked("backend".to_owned())
3822        );
3823        assert_eq!(
3824            parser.attribute_value("backend"),
3825            InterpretedValue::Value("html5")
3826        );
3827    }
3828
3829    #[test]
3830    fn catalog_transferred_to_document() {
3831        let mut parser = Parser::default();
3832        let doc = parser.parse("= Test Document\n\nSome content");
3833
3834        let catalog = doc.catalog();
3835        assert!(catalog.is_empty());
3836
3837        // The catalog was transferred to the document, leaving the parser with
3838        // an empty catalog.
3839        assert!(parser.catalog.borrow().is_empty());
3840    }
3841
3842    #[test]
3843    fn block_ids_registered_in_catalog() {
3844        let mut parser = Parser::default();
3845        let doc = parser.parse("= Test Document\n\n[#my-block]\nSome content with an ID");
3846
3847        let catalog = doc.catalog();
3848        assert!(!catalog.is_empty());
3849        assert!(catalog.contains_id("my-block"));
3850
3851        let entry = catalog.get_ref("my-block").unwrap();
3852        assert_eq!(entry.id, "my-block");
3853        assert_eq!(entry.ref_type, crate::document::RefType::Anchor);
3854    }
3855
3856    /// A simple test renderer that modifies special characters differently
3857    /// from the default HTML renderer.
3858    #[derive(Debug)]
3859    struct TestRenderer;
3860
3861    impl InlineSubstitutionRenderer for TestRenderer {
3862        fn render_special_character(&self, type_: SpecialCharacter, dest: &mut String) {
3863            // Custom rendering: wrap special characters in brackets.
3864            match type_ {
3865                SpecialCharacter::Lt => dest.push_str("[LT]"),
3866                SpecialCharacter::Gt => dest.push_str("[GT]"),
3867                SpecialCharacter::Ampersand => dest.push_str("[AMP]"),
3868            }
3869        }
3870
3871        fn render_quoted_substitution(
3872            &self,
3873            _type_: QuoteType,
3874            _scope: QuoteScope,
3875            _attrlist: Option<Attrlist<'_>>,
3876            _id: Option<String>,
3877            body: &str,
3878            dest: &mut String,
3879        ) {
3880            dest.push_str(body);
3881        }
3882
3883        fn render_character_replacement(
3884            &self,
3885            _type_: CharacterReplacementType,
3886            dest: &mut String,
3887        ) {
3888            dest.push_str("[CHAR]");
3889        }
3890
3891        fn render_line_break(&self, dest: &mut String) {
3892            dest.push_str("[BR]");
3893        }
3894
3895        fn render_image(&self, _params: &ImageRenderParams, dest: &mut String) {
3896            dest.push_str("[IMAGE]");
3897        }
3898
3899        fn image_uri(
3900            &self,
3901            target_image_path: &str,
3902            _parser: &Parser,
3903            _asset_dir_key: Option<&str>,
3904        ) -> String {
3905            target_image_path.to_string()
3906        }
3907
3908        fn render_icon(&self, _params: &IconRenderParams, dest: &mut String) {
3909            dest.push_str("[ICON]");
3910        }
3911
3912        fn render_link(&self, _params: &LinkRenderParams, dest: &mut String) {
3913            dest.push_str("[LINK]");
3914        }
3915
3916        fn render_anchor(&self, id: &str, _reftext: Option<String>, dest: &mut String) {
3917            dest.push_str(&format!("[ANCHOR:{}]", id));
3918        }
3919
3920        fn render_xref(&self, params: &crate::parser::XrefRenderParams, dest: &mut String) {
3921            dest.push_str(&format!("[XREF:{}]", params.target));
3922        }
3923
3924        fn render_callout(&self, params: &crate::parser::CalloutRenderParams, dest: &mut String) {
3925            dest.push_str(&format!("[CALLOUT:{}]", params.number));
3926        }
3927
3928        fn render_index_term(
3929            &self,
3930            params: &crate::parser::IndexTermRenderParams,
3931            dest: &mut String,
3932        ) {
3933            match params.visible_term {
3934                Some(term) => dest.push_str(&format!("[INDEXTERM:{term}]")),
3935                None => dest.push_str("[INDEXTERM]"),
3936            }
3937        }
3938
3939        fn render_button(&self, text: &str, dest: &mut String) {
3940            dest.push_str(&format!("[BUTTON:{text}]"));
3941        }
3942
3943        fn render_keyboard(&self, keys: &[String], dest: &mut String) {
3944            dest.push_str(&format!("[KBD:{}]", keys.join("+")));
3945        }
3946
3947        fn render_menu(&self, params: &crate::parser::MenuRenderParams, dest: &mut String) {
3948            dest.push_str(&format!("[MENU:{}]", params.menu));
3949        }
3950
3951        fn render_footnote(&self, params: &crate::parser::FootnoteRenderParams, dest: &mut String) {
3952            match params.index {
3953                Some(index) => dest.push_str(&format!("[FOOTNOTE:{index}]")),
3954                None => dest.push_str(&format!("[FOOTNOTE:{}]", params.text)),
3955            }
3956        }
3957    }
3958
3959    #[test]
3960    fn with_inline_substitution_renderer() {
3961        let mut parser = Parser::default().with_inline_substitution_renderer(TestRenderer);
3962
3963        // Parse a simple document with special characters and a footnote.
3964        let doc = parser.parse("Hello & goodbye < world > test footnote:[a note]");
3965
3966        // The document should parse successfully.
3967        assert_eq!(doc.warnings().count(), 0);
3968
3969        // Get the first block from the document.
3970        let block = doc.child_blocks().next().unwrap();
3971
3972        let Block::Simple(simple_block) = block else {
3973            panic!("Expected simple block, got: {block:?}");
3974        };
3975
3976        // Our custom renderer should show [AMP], [LT], and [GT] instead of HTML
3977        // entities, and a resolved footnote as [FOOTNOTE:<index>].
3978        assert_eq!(
3979            simple_block.content().rendered(),
3980            "Hello [AMP] goodbye [LT] world [GT] test [FOOTNOTE:1]"
3981        );
3982    }
3983
3984    #[test]
3985    fn custom_renderer_renders_unresolved_footnote() {
3986        let mut parser = Parser::default().with_inline_substitution_renderer(TestRenderer);
3987
3988        // An unresolved footnote reference exercises the renderer's `None`
3989        // (no index) branch, which our custom renderer shows as
3990        // [FOOTNOTE:<text>].
3991        let doc = parser.parse("test.footnote:missing[]");
3992
3993        let block = doc.child_blocks().next().unwrap();
3994        let Block::Simple(simple_block) = block else {
3995            panic!("Expected simple block, got: {block:?}");
3996        };
3997
3998        assert_eq!(simple_block.content().rendered(), "test.[FOOTNOTE:missing]");
3999    }
4000
4001    /// A custom [`PathResolver`](crate::parser::PathResolver) that rewrites
4002    /// every asset target under a fixed content root, ignoring the start path.
4003    /// Stands in for a host (Antora/Zola-style) that maps targets through a
4004    /// virtual filesystem or URL scheme.
4005    #[derive(Debug)]
4006    struct CdnPathResolver;
4007
4008    impl crate::parser::PathResolver for CdnPathResolver {
4009        fn web_path(&self, target: &str, _start: Option<&str>) -> String {
4010            format!("https://cdn.example.com/{target}")
4011        }
4012    }
4013
4014    #[test]
4015    fn with_path_resolver() {
4016        let mut parser = Parser::default().with_path_resolver(CdnPathResolver);
4017
4018        // An inline image's `src` is resolved through the path resolver, so the
4019        // custom resolver should rewrite it under the content root.
4020        let doc = parser.parse("image:tiger.png[tiger]");
4021
4022        let block = doc.child_blocks().next().unwrap();
4023        let Block::Simple(simple_block) = block else {
4024            panic!("Expected simple block, got: {block:?}");
4025        };
4026
4027        assert_eq!(
4028            simple_block.content().rendered(),
4029            r#"<span class="image"><img src="https://cdn.example.com/tiger.png" alt="tiger"></span>"#
4030        );
4031    }
4032
4033    mod resolve_show_title {
4034        use crate::parser::{ModificationContext, Parser};
4035
4036        fn with(name: &str, set: bool) -> Parser {
4037            Parser::default().with_intrinsic_attribute_bool(
4038                name,
4039                set,
4040                ModificationContext::Anywhere,
4041            )
4042        }
4043
4044        #[test]
4045        fn neither_present_uses_default() {
4046            assert!(Parser::default().resolve_show_title(true));
4047            assert!(!Parser::default().resolve_show_title(false));
4048        }
4049
4050        #[test]
4051        fn showtitle_takes_precedence_and_decides() {
4052            // Present and set -> shown; present and unset -> hidden, regardless
4053            // of the default.
4054            assert!(with("showtitle", true).resolve_show_title(false));
4055            assert!(!with("showtitle", false).resolve_show_title(true));
4056        }
4057
4058        #[test]
4059        fn notitle_is_the_complement_when_showtitle_absent() {
4060            // notitle set -> hidden; notitle unset -> shown.
4061            assert!(!with("notitle", true).resolve_show_title(true));
4062            assert!(with("notitle", false).resolve_show_title(false));
4063        }
4064    }
4065
4066    mod notitle_showtitle_linkage {
4067        use crate::{
4068            blocks::{Block, FindBlocks},
4069            document::InterpretedValue,
4070            parser::{ModificationContext, Parser},
4071        };
4072
4073        // Asciidoctor asciidoctor/asciidoctor#3804: `notitle` and `showtitle`
4074        // are two spellings of one title-visibility toggle, wired as inverses.
4075        // Assigning either updates the partner so the resolved document carries
4076        // one consistent signal – following Asciidoctor's hash semantics, where
4077        // turning the toggle *on* sets one spelling and *removes* the other.
4078
4079        fn parse_header(entries: &str) -> Parser {
4080            let mut parser = Parser::default();
4081            let _ = parser.parse(&format!("= Title\n{entries}\n\nbody"));
4082            parser
4083        }
4084
4085        #[test]
4086        fn header_showtitle_set_unsets_notitle() {
4087            // `:showtitle:` => notitle removed (absent).
4088            let parser = parse_header(":showtitle:");
4089            assert_eq!(parser.attribute_value("showtitle"), InterpretedValue::Set);
4090            assert!(!parser.has_attribute("notitle"));
4091        }
4092
4093        #[test]
4094        fn header_showtitle_unset_sets_notitle() {
4095            // `:!showtitle:` => notitle set.
4096            let parser = parse_header(":!showtitle:");
4097            assert!(!parser.is_attribute_set("showtitle"));
4098            assert_eq!(parser.attribute_value("notitle"), InterpretedValue::Set);
4099            assert!(parser.is_attribute_set("notitle"));
4100        }
4101
4102        #[test]
4103        fn header_notitle_set_unsets_showtitle() {
4104            // `:notitle:` => showtitle removed (absent).
4105            let parser = parse_header(":notitle:");
4106            assert_eq!(parser.attribute_value("notitle"), InterpretedValue::Set);
4107            assert!(!parser.has_attribute("showtitle"));
4108        }
4109
4110        #[test]
4111        fn header_notitle_unset_sets_showtitle() {
4112            // `:!notitle:` => showtitle set. This is the case called out in the
4113            // issue: a consumer keying off `showtitle` now sees a signal.
4114            let parser = parse_header(":!notitle:");
4115            assert!(!parser.is_attribute_set("notitle"));
4116            assert_eq!(parser.attribute_value("showtitle"), InterpretedValue::Set);
4117            assert!(parser.is_attribute_set("showtitle"));
4118        }
4119
4120        #[test]
4121        fn last_assignment_wins() {
4122            // Each assignment rewrites the partner, so whichever is assigned
4123            // last decides the resolved toggle.
4124            let parser = parse_header(":notitle:\n:showtitle:");
4125            assert_eq!(parser.attribute_value("showtitle"), InterpretedValue::Set);
4126            assert!(!parser.has_attribute("notitle"));
4127
4128            let parser = parse_header(":showtitle:\n:notitle:");
4129            assert_eq!(parser.attribute_value("notitle"), InterpretedValue::Set);
4130            assert!(!parser.has_attribute("showtitle"));
4131        }
4132
4133        #[test]
4134        fn body_assignment_is_linked() {
4135            // A body attribute entry links the partner just as a header entry
4136            // does.
4137            let mut parser = Parser::default();
4138            let _ = parser.parse("= Title\n\nintro\n\n:notitle:\n\nmore");
4139            assert_eq!(parser.attribute_value("notitle"), InterpretedValue::Set);
4140            assert!(!parser.has_attribute("showtitle"));
4141        }
4142
4143        #[test]
4144        fn api_assignment_is_linked() {
4145            // Setting either attribute via the API links the partner, matching
4146            // Asciidoctor's `attributes: { 'notitle!' => '' }` etc.
4147            let parser = Parser::default().with_intrinsic_attribute_bool(
4148                "notitle",
4149                true,
4150                ModificationContext::Anywhere,
4151            );
4152            assert_eq!(parser.attribute_value("notitle"), InterpretedValue::Set);
4153            assert!(!parser.has_attribute("showtitle"));
4154
4155            let parser = Parser::default().with_intrinsic_attribute_bool(
4156                "notitle",
4157                false,
4158                ModificationContext::Anywhere,
4159            );
4160            assert!(!parser.is_attribute_set("notitle"));
4161            assert_eq!(parser.attribute_value("showtitle"), InterpretedValue::Set);
4162        }
4163
4164        #[test]
4165        fn turning_the_toggle_on_leaves_no_partner_tombstone() {
4166            // `:notitle:` removes `showtitle` outright rather than leaving an
4167            // unset tombstone, so a `{showtitle}` reference stays literal (as it
4168            // would with the attribute absent) instead of resolving to an empty
4169            // string. This guards the interaction flagged in review.
4170            let parser = parse_header(":notitle:");
4171            assert!(!parser.has_attribute("showtitle"));
4172
4173            let mut parser = Parser::default();
4174            let doc = parser.parse("= Title\n:notitle:\n\n{showtitle}");
4175            let block = doc.child_blocks().next().unwrap();
4176            let Block::Simple(simple_block) = block else {
4177                panic!("expected a simple block");
4178            };
4179            assert_eq!(simple_block.content().rendered(), "{showtitle}");
4180        }
4181
4182        #[test]
4183        fn unrelated_attributes_are_untouched() {
4184            // A document that never assigns either spelling leaves both absent –
4185            // the linkage is a no-op for every other attribute.
4186            let parser = parse_header(":sectnums:");
4187            assert!(!parser.has_attribute("notitle"));
4188            assert!(!parser.has_attribute("showtitle"));
4189        }
4190    }
4191
4192    mod derived_backend_family_attrs {
4193        use crate::{
4194            document::InterpretedValue,
4195            parser::{AllowableValue, AttributeValue, ModificationContext, Parser},
4196        };
4197
4198        #[test]
4199        fn tracks_the_active_doctype() {
4200            let mut parser = Parser::default();
4201
4202            // The default doctype is `article`, so only its derived attribute is
4203            // defined (to an empty value).
4204            assert_eq!(
4205                parser.attribute_value("backend-html5-doctype-article"),
4206                InterpretedValue::Value(String::new())
4207            );
4208            assert_eq!(
4209                parser.attribute_value("backend-html5-doctype-book"),
4210                InterpretedValue::Unset
4211            );
4212
4213            // Forcing a new doctype moves the derived attribute with it.
4214            parser.force_doctype("book");
4215            assert_eq!(
4216                parser.attribute_value("backend-html5-doctype-book"),
4217                InterpretedValue::Value(String::new())
4218            );
4219            assert_eq!(
4220                parser.attribute_value("backend-html5-doctype-article"),
4221                InterpretedValue::Unset
4222            );
4223        }
4224
4225        #[test]
4226        fn defines_no_derived_attr_when_doctype_is_not_a_value() {
4227            let mut parser = Parser::default();
4228
4229            // The default article derived attribute starts out defined.
4230            assert_eq!(
4231                parser.attribute_value("backend-html5-doctype-article"),
4232                InterpretedValue::Value(String::new())
4233            );
4234
4235            // Shadow the built-in `doctype` default with an explicit unset
4236            // tombstone. With `doctype` no longer resolving to a `Value`, no
4237            // derived attribute is synthesized for any doctype.
4238            std::sync::Arc::make_mut(&mut parser.attribute_values).insert(
4239                "doctype".to_string(),
4240                AttributeValue {
4241                    allowable_value: AllowableValue::Any,
4242                    modification_context: ModificationContext::Anywhere,
4243                    silent_when_locked: false,
4244                    value: InterpretedValue::Unset,
4245                },
4246            );
4247
4248            assert_eq!(parser.attribute_value("doctype"), InterpretedValue::Unset);
4249            assert_eq!(
4250                parser.attribute_value("backend-html5-doctype-article"),
4251                InterpretedValue::Unset
4252            );
4253        }
4254
4255        #[test]
4256        fn document_header_cannot_assign_a_derived_doctype_flag() {
4257            // The `backend-html5-doctype-*` namespace is a read-only intrinsic,
4258            // so a document header assignment to it is ignored: the flag for the
4259            // (inactive) `book` doctype stays undefined rather than taking the
4260            // assigned value, so it cannot later shadow the intrinsic.
4261            let mut parser = Parser::default();
4262            let _doc = parser.parse("= Title\n:backend-html5-doctype-book: custom\n\nbody");
4263
4264            assert_eq!(
4265                parser.attribute_value("backend-html5-doctype-book"),
4266                InterpretedValue::Unset
4267            );
4268        }
4269
4270        #[test]
4271        fn default_backend_family_is_materialized() {
4272            let parser = Parser::default();
4273
4274            // The default backend is `html5`; its whole derived family resolves
4275            // to queryable document attributes (empty-valued flags plus the
4276            // `backend` / `basebackend` / `filetype` values).
4277            for (name, value) in [
4278                ("backend", "html5"),
4279                ("backend-html5", ""),
4280                ("basebackend", "html"),
4281                ("basebackend-html", ""),
4282                ("filetype", "html"),
4283                ("filetype-html", ""),
4284                ("doctype-article", ""),
4285                ("backend-html5-doctype-article", ""),
4286                ("basebackend-html-doctype-article", ""),
4287            ] {
4288                assert!(parser.has_attribute(name), "missing {name:?}");
4289                assert!(parser.is_attribute_set(name), "not set: {name:?}");
4290                assert_eq!(
4291                    parser.attribute_value(name),
4292                    InterpretedValue::Value(value.to_string()),
4293                    "unexpected value for {name:?}"
4294                );
4295            }
4296        }
4297
4298        #[test]
4299        fn family_tracks_a_non_html_backend() {
4300            // Setting a different backend re-derives the whole family from it
4301            // (basebackend strips the trailing digits, filetype maps through the
4302            // Asciidoctor extension table), and the inactive `html5` flags fall
4303            // away.
4304            let doc = Parser::default().parse(":backend: docbook5\n\nbody");
4305
4306            assert_eq!(
4307                doc.attribute_value("backend"),
4308                InterpretedValue::Value("docbook5".to_string())
4309            );
4310            assert_eq!(
4311                doc.attribute_value("basebackend"),
4312                InterpretedValue::Value("docbook".to_string())
4313            );
4314            assert_eq!(
4315                doc.attribute_value("filetype"),
4316                InterpretedValue::Value("xml".to_string())
4317            );
4318            assert!(doc.has_attribute("backend-docbook5"));
4319            assert!(doc.has_attribute("basebackend-docbook"));
4320            assert!(doc.has_attribute("backend-docbook5-doctype-article"));
4321
4322            // The derived values report as set through the post-parse
4323            // `Document` (snapshot) reader, not just the live parser.
4324            assert!(doc.is_attribute_set("basebackend"));
4325            assert!(doc.is_attribute_set("filetype"));
4326
4327            // The html5 flags are no longer active.
4328            assert!(!doc.has_attribute("backend-html5"));
4329            assert!(!doc.has_attribute("basebackend-html"));
4330            assert!(!doc.has_attribute("backend-html5-doctype-article"));
4331        }
4332
4333        #[test]
4334        fn derived_value_and_flag_attributes_are_read_only() {
4335            // `basebackend` / `filetype` and the derived flag namespace are
4336            // read-only intrinsics; a document assignment is silently ignored and
4337            // the synthesized value stands.
4338            let doc = Parser::default().parse(
4339                ":basebackend: custom\n:filetype: custom\n:backend-html5: custom\n:doctype-article: custom\n\nbody",
4340            );
4341
4342            assert_eq!(
4343                doc.attribute_value("basebackend"),
4344                InterpretedValue::Value("html".to_string())
4345            );
4346            assert_eq!(
4347                doc.attribute_value("filetype"),
4348                InterpretedValue::Value("html".to_string())
4349            );
4350            assert_eq!(
4351                doc.attribute_value("backend-html5"),
4352                InterpretedValue::Value(String::new())
4353            );
4354            assert_eq!(
4355                doc.attribute_value("doctype-article"),
4356                InterpretedValue::Value(String::new())
4357            );
4358        }
4359
4360        #[test]
4361        fn custom_prefixed_flags_stay_assignable() {
4362            // Author-defined attributes that share a derived-family prefix but
4363            // name no active flag (and are not the doctype-keyed namespace) are
4364            // kept, not swallowed by the read-only reservation, so they stay
4365            // visible to `ifdef` / attribute references – matching Asciidoctor.
4366            let doc = Parser::default().parse(
4367                ":backend-custom: enabled\n:basebackend-custom: on\n:filetype-custom: yes\n:doctype-draft: 1\n\nbody",
4368            );
4369
4370            for (name, value) in [
4371                ("backend-custom", "enabled"),
4372                ("basebackend-custom", "on"),
4373                ("filetype-custom", "yes"),
4374                ("doctype-draft", "1"),
4375            ] {
4376                assert!(doc.has_attribute(name), "missing {name:?}");
4377                assert_eq!(
4378                    doc.attribute_value(name),
4379                    InterpretedValue::Value(value.to_string()),
4380                    "unexpected value for {name:?}"
4381                );
4382            }
4383        }
4384
4385        #[test]
4386        fn unset_backend_makes_the_family_absent() {
4387            // Explicitly unsetting `backend` leaves nothing to derive from, so
4388            // `basebackend` / `filetype` and the backend-keyed flags are absent
4389            // rather than resolving to empty traits or degenerate `backend-` /
4390            // `filetype-` names.
4391            let doc = Parser::default().parse(":backend!:\n\nbody");
4392
4393            assert_eq!(doc.attribute_value("backend"), InterpretedValue::Unset);
4394            for name in ["basebackend", "filetype"] {
4395                assert!(!doc.has_attribute(name), "unexpectedly present: {name:?}");
4396                assert!(!doc.is_attribute_set(name), "unexpectedly set: {name:?}");
4397                assert_eq!(doc.attribute_value(name), InterpretedValue::Unset);
4398            }
4399
4400            // No degenerate empty-suffix flags, and the html5 flags are gone.
4401            for name in [
4402                "backend-",
4403                "basebackend-",
4404                "filetype-",
4405                "backend-html5",
4406                "basebackend-html",
4407            ] {
4408                assert!(!doc.has_attribute(name), "unexpectedly present: {name:?}");
4409            }
4410
4411            // The doctype-only flag does not depend on `backend`, so it remains.
4412            assert!(doc.has_attribute("doctype-article"));
4413        }
4414    }
4415
4416    mod docname {
4417        use crate::Parser;
4418
4419        #[test]
4420        fn none_without_primary_file_name() {
4421            assert_eq!(Parser::default().docname(), None);
4422        }
4423
4424        #[test]
4425        fn strips_directory_and_extension() {
4426            assert_eq!(
4427                Parser::default()
4428                    .with_primary_file_name("mydoc.adoc")
4429                    .docname()
4430                    .as_deref(),
4431                Some("mydoc")
4432            );
4433            assert_eq!(
4434                Parser::default()
4435                    .with_primary_file_name("docs/guide/mydoc.adoc")
4436                    .docname()
4437                    .as_deref(),
4438                Some("mydoc")
4439            );
4440
4441            // A Windows-style separator is handled too, since the primary file
4442            // name may be supplied on either platform.
4443            assert_eq!(
4444                Parser::default()
4445                    .with_primary_file_name(r"docs\guide\mydoc.adoc")
4446                    .docname()
4447                    .as_deref(),
4448                Some("mydoc")
4449            );
4450        }
4451
4452        #[test]
4453        fn keeps_name_with_no_extension() {
4454            assert_eq!(
4455                Parser::default()
4456                    .with_primary_file_name("README")
4457                    .docname()
4458                    .as_deref(),
4459                Some("README")
4460            );
4461        }
4462
4463        #[test]
4464        fn none_when_path_has_no_file_component() {
4465            // A primary file name that ends in a separator has an empty base
4466            // name, which yields no document name.
4467            assert_eq!(
4468                Parser::default()
4469                    .with_primary_file_name("docs/guide/")
4470                    .docname(),
4471                None
4472            );
4473        }
4474
4475        #[test]
4476        fn leading_dot_name_is_kept_whole() {
4477            // A leading-dot name (e.g. `.adoc`) is treated as a dotfile with no
4478            // extension and kept whole, matching Ruby's
4479            // `File.basename(".adoc", ".*")`.
4480            assert_eq!(
4481                Parser::default()
4482                    .with_primary_file_name(".adoc")
4483                    .docname()
4484                    .as_deref(),
4485                Some(".adoc")
4486            );
4487        }
4488    }
4489
4490    mod counter {
4491        use super::super::next_counter_value;
4492        use crate::{document::InterpretedValue, tests::prelude::*};
4493
4494        #[test]
4495        fn next_counter_value_integer() {
4496            assert_eq!(next_counter_value("1"), "2");
4497            assert_eq!(next_counter_value("9"), "10");
4498            assert_eq!(next_counter_value("0"), "1");
4499            assert_eq!(next_counter_value("-1"), "0");
4500        }
4501
4502        #[test]
4503        fn next_counter_value_non_canonical_integer_is_advanced_as_a_string() {
4504            // A leading zero (or sign) does not round-trip through integer
4505            // parsing, so it is advanced like a string instead.
4506            assert_eq!(next_counter_value("07"), "08");
4507            assert_eq!(next_counter_value("+5"), "+6");
4508
4509            // A leading-zero value still carries digit-to-digit like a string.
4510            assert_eq!(next_counter_value("09"), "10");
4511            assert_eq!(next_counter_value("099"), "100");
4512        }
4513
4514        #[test]
4515        fn next_counter_value_saturates_at_i64_max() {
4516            // A counter pinned at `i64::MAX` stays there rather than panicking
4517            // (debug) or wrapping (release).
4518            let max = i64::MAX.to_string();
4519            assert_eq!(next_counter_value(&max), max);
4520        }
4521
4522        #[test]
4523        fn next_counter_value_characters() {
4524            assert_eq!(next_counter_value("a"), "b");
4525            assert_eq!(next_counter_value("A"), "B");
4526            assert_eq!(next_counter_value("z"), "aa");
4527            assert_eq!(next_counter_value("Z"), "AA");
4528            assert_eq!(next_counter_value("az"), "ba");
4529            assert_eq!(next_counter_value("zz"), "aaa");
4530            assert_eq!(next_counter_value("Zz"), "AAa");
4531        }
4532
4533        #[test]
4534        fn next_counter_value_trailing_non_alphanumeric() {
4535            // The right-most alphanumeric is incremented; trailing punctuation is
4536            // left in place.
4537            assert_eq!(next_counter_value("a)"), "b)");
4538        }
4539
4540        #[test]
4541        fn next_counter_value_no_alphanumeric() {
4542            // With nothing alphanumeric to carry, the final code point advances.
4543            assert_eq!(next_counter_value("{"), "|");
4544        }
4545
4546        #[test]
4547        fn counter_defaults_to_one() {
4548            let p = Parser::default();
4549            assert_eq!(p.counter("x", None), "1");
4550            assert_eq!(p.counter("x", None), "2");
4551            assert_eq!(
4552                p.attribute_value("x"),
4553                InterpretedValue::Value("2".to_string())
4554            );
4555            assert!(p.has_attribute("x"));
4556            assert!(p.is_attribute_set("x"));
4557        }
4558
4559        #[test]
4560        fn counter_seed_used_only_while_unset() {
4561            let p = Parser::default();
4562            assert_eq!(p.counter("c", Some("A")), "A");
4563
4564            // Once set, a later seed is ignored.
4565            assert_eq!(p.counter("c", Some("Q")), "B");
4566        }
4567
4568        #[test]
4569        fn counter_empty_seed_falls_back_to_one() {
4570            let p = Parser::default();
4571            assert_eq!(p.counter("c", Some("")), "1");
4572        }
4573    }
4574
4575    /// Coverage for the time-dependent document attributes (`docdate`,
4576    /// `doctime`, `docdatetime`, `docyear`, and their `local*` siblings) that
4577    /// is *not* a direct port of Asciidoctor's Ruby tests: the injectable
4578    /// clock ([`Parser::with_reference_time`] /
4579    /// [`Parser::with_input_mtime`]), and resolution *during* a parse (a
4580    /// `{docdate}` reference or an `ifdef::docdate[]` directive) rather
4581    /// than off the finished document.
4582    ///
4583    /// The direct Ruby ports live alongside the vendored suite in
4584    /// `tests/asciidoctor_rb/document_test.rs`.
4585    mod datetime_attributes {
4586        use crate::{parser::ReferenceTime, tests::prelude::*};
4587
4588        #[test]
4589        fn pins_local_attributes_with_reference_time() {
4590            // The injectable clock (this crate's stable-output mechanism) pins
4591            // the `local*` attributes, which Asciidoctor derives from
4592            // `::Time.now`.
4593            let doc = Parser::default()
4594                .with_reference_time(ReferenceTime::from_local(2019, 1, 2, 3, 4, 5, 6 * 3600))
4595                .parse("");
4596
4597            assert_eq!(
4598                doc.attribute_value("localdate"),
4599                InterpretedValue::Value("2019-01-02")
4600            );
4601            assert_eq!(
4602                doc.attribute_value("localyear"),
4603                InterpretedValue::Value("2019")
4604            );
4605            assert_eq!(
4606                doc.attribute_value("localtime"),
4607                InterpretedValue::Value("03:04:05 +0600")
4608            );
4609            assert_eq!(
4610                doc.attribute_value("localdatetime"),
4611                InterpretedValue::Value("2019-01-02 03:04:05 +0600")
4612            );
4613        }
4614
4615        #[test]
4616        fn resolves_date_attributes_referenced_in_the_document_body() {
4617            // A `{docdate}` reference resolves the attribute on demand through
4618            // the parser (during substitution), not off the finished document
4619            // snapshot.
4620            let doc = Parser::default()
4621                .with_reference_time(ReferenceTime::from_unix_timestamp(1_420_106_400))
4622                .parse("docdate={docdate} docyear={docyear} docdatetime={docdatetime}");
4623
4624            assert_eq!(
4625                rendered_paragraphs(&doc),
4626                vec![
4627                    "docdate=2015-01-01 docyear=2015 docdatetime=2015-01-01 10:00:00 UTC"
4628                        .to_string()
4629                ]
4630            );
4631        }
4632
4633        #[test]
4634        fn conditional_directive_sees_a_computed_date_attribute() {
4635            // `ifdef` queries `is_attribute_set`, which must report the computed
4636            // `docdate` as set.
4637            let doc = Parser::default()
4638                .with_reference_time(ReferenceTime::from_unix_timestamp(1_420_106_400))
4639                .parse("ifdef::docdate[present]");
4640
4641            assert_eq!(rendered_paragraphs(&doc), vec!["present".to_string()]);
4642        }
4643
4644        #[test]
4645        fn an_explicit_doctime_feeds_the_computed_docdatetime() {
4646            // An explicit `doctime` (a stored value) supplies the time portion
4647            // of the computed `docdatetime`, both when referenced in the body
4648            // and when read off the document.
4649            let mut parser = Parser::default()
4650                .with_reference_time(ReferenceTime::from_unix_timestamp(1_420_106_400))
4651                .with_intrinsic_attribute(
4652                    "doctime",
4653                    "09:09:09-0500",
4654                    ModificationContext::ApiOrHeader,
4655                );
4656            let doc = parser.parse("at {docdatetime}");
4657
4658            assert_eq!(
4659                rendered_paragraphs(&doc),
4660                vec!["at 2015-01-01 09:09:09-0500".to_string()]
4661            );
4662            assert_eq!(
4663                doc.attribute_value("docdatetime"),
4664                InterpretedValue::Value("2015-01-01 09:09:09-0500")
4665            );
4666        }
4667
4668        #[test]
4669        fn an_unset_doctime_falls_back_to_the_reference_time() {
4670            // An explicitly unset `doctime` is treated as absent, so
4671            // `docdatetime` falls back to the reference instant's time.
4672            let mut parser = Parser::default()
4673                .with_reference_time(ReferenceTime::from_unix_timestamp(1_420_106_400))
4674                .with_intrinsic_attribute_bool("doctime", false, ModificationContext::ApiOrHeader);
4675            let doc = parser.parse("at {docdatetime}");
4676
4677            assert_eq!(
4678                rendered_paragraphs(&doc),
4679                vec!["at 2015-01-01 10:00:00 UTC".to_string()]
4680            );
4681            assert_eq!(
4682                doc.attribute_value("docdatetime"),
4683                InterpretedValue::Value("2015-01-01 10:00:00 UTC")
4684            );
4685        }
4686
4687        #[test]
4688        fn a_value_less_doctime_reads_as_an_empty_time() {
4689            // A value-less `doctime` (set, but with no value) contributes an
4690            // empty time, leaving a trailing space in the computed
4691            // `docdatetime`.
4692            let mut parser = Parser::default()
4693                .with_reference_time(ReferenceTime::from_unix_timestamp(1_420_106_400))
4694                .with_intrinsic_attribute_bool("doctime", true, ModificationContext::ApiOrHeader);
4695            let doc = parser.parse("x{docdatetime}x");
4696
4697            assert_eq!(rendered_paragraphs(&doc), vec!["x2015-01-01 x".to_string()]);
4698            assert_eq!(
4699                doc.attribute_value("docdatetime"),
4700                InterpretedValue::Value("2015-01-01 ")
4701            );
4702        }
4703    }
4704
4705    // Crate-native `skip-front-matter` cases (no Asciidoctor analog) covering
4706    // edge conditions beyond the reader-suite ports in
4707    // `tests::asciidoctor_rb::reader_test`. See [`Parser::skip_front_matter`].
4708    mod skip_front_matter {
4709        use crate::tests::prelude::*;
4710
4711        #[test]
4712        fn crlf_line_endings() {
4713            // The front-matter delimiters are matched after a CRLF line ending
4714            // is stripped, and the captured `front-matter` value is likewise
4715            // chomped, so a document with `\r\n` line endings is handled the
4716            // same as one with bare `\n`.
4717            let doc = Parser::default()
4718                .with_intrinsic_attribute_bool(
4719                    "skip-front-matter",
4720                    true,
4721                    ModificationContext::ApiOnly,
4722                )
4723                .parse("---\r\nlayout: post\r\ntitle: Document Title\r\n---\r\n= Document Title\r\nAuthor Name\r\n\r\npreamble\r\n");
4724
4725            assert_eq!(
4726                doc.attribute_value("front-matter"),
4727                InterpretedValue::Value("layout: post\ntitle: Document Title")
4728            );
4729            assert_eq!(doc.header().title(), Some("Document Title"));
4730            assert_eq!(doc.header().title_source().unwrap().line(), 5);
4731        }
4732
4733        #[test]
4734        fn first_line_is_not_a_delimiter() {
4735            // With `skip-front-matter` set but no opening `---` on the first
4736            // line, there is nothing to skip: the document parses normally and
4737            // no `front-matter` attribute is recorded.
4738            let doc = Parser::default()
4739                .with_intrinsic_attribute_bool(
4740                    "skip-front-matter",
4741                    true,
4742                    ModificationContext::ApiOnly,
4743                )
4744                .parse("= Document Title\nAuthor Name\n\npreamble\n");
4745
4746            assert_eq!(doc.attribute_value("front-matter"), InterpretedValue::Unset);
4747            assert_eq!(doc.header().title(), Some("Document Title"));
4748            assert_eq!(doc.header().title_source().unwrap().line(), 1);
4749        }
4750    }
4751}