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::new(
1155            source,
1156            WarningType::MaxBlockNestingExceeded(self.block_nesting_limit),
1157        ));
1158    }
1159
1160    /// Returns the effective `max-attribute-value-size`: the byte limit applied
1161    /// to a resolved attribute-entry value, or `None` when no limit is in
1162    /// force.
1163    ///
1164    /// The value is coerced as Ruby's `String#to_i` would (matching
1165    /// Asciidoctor); a non-positive result – including an explicit unset or `0`
1166    /// – disables the limit. The `4096` default only exists under
1167    /// `SafeMode::Secure` (see
1168    /// [`apply_safe_mode_attributes`](Self::apply_safe_mode_attributes)), so in
1169    /// a relaxed safe mode this resolves to `None` unless the caller sets an
1170    /// explicit positive value.
1171    fn max_attribute_value_size(&self) -> Option<usize> {
1172        match self.attribute_value("max-attribute-value-size") {
1173            InterpretedValue::Value(value) => {
1174                let size = super::preprocessor::ruby_to_i(&value);
1175                (size > 0).then(|| usize::try_from(size).unwrap_or(usize::MAX))
1176            }
1177            _ => None,
1178        }
1179    }
1180
1181    /// Applies the [`max-attribute-value-size`](Self::max_attribute_value_size)
1182    /// limit to a freshly resolved attribute-entry `value`, truncating it (on a
1183    /// character boundary, so a multibyte character is never split) when it
1184    /// exceeds the limit. Values that already fit, and non-`Value` variants,
1185    /// are returned unchanged.
1186    fn limit_attribute_value_size(&self, value: InterpretedValue) -> InterpretedValue {
1187        let Some(max) = self.max_attribute_value_size() else {
1188            return value;
1189        };
1190
1191        let InterpretedValue::Value(text) = value else {
1192            return value;
1193        };
1194
1195        if text.len() <= max {
1196            return InterpretedValue::Value(text);
1197        }
1198
1199        // Back up to the nearest character boundary at or below `max` so a
1200        // multibyte character straddling the limit is dropped whole rather than
1201        // split (which would otherwise yield invalid UTF-8).
1202        let mut end = max;
1203        while end > 0 && !text.is_char_boundary(end) {
1204            end -= 1;
1205        }
1206
1207        let mut text = text;
1208        text.truncate(end);
1209        InterpretedValue::Value(text)
1210    }
1211
1212    /// Resolves a `leveloffset` assignment value, converting a relative form
1213    /// (`+N` / `-N`) into the absolute value it produces given the
1214    /// `leveloffset` currently in effect. Absolute values, and values that
1215    /// aren't a signed integer, are returned unchanged.
1216    ///
1217    /// This mirrors Asciidoctor, where a relative `leveloffset` accumulates on
1218    /// top of the offset already in effect. That accumulation is what lets the
1219    /// offsets of nested includes compose: each `include::[leveloffset=+1]`
1220    /// (and its `:leveloffset: +1` wrapper) shifts headings one level further
1221    /// down relative to wherever the surrounding content already sits.
1222    fn resolve_leveloffset_assignment(&self, value: InterpretedValue) -> InterpretedValue {
1223        let InterpretedValue::Value(ref v) = value else {
1224            return value;
1225        };
1226
1227        // Only a leading `+`/`-` marks a relative assignment; anything else
1228        // (an absolute value, or a non-numeric value) is stored unchanged.
1229        let trimmed = v.trim();
1230        if !trimmed.starts_with(['+', '-']) {
1231            return value;
1232        }
1233
1234        // Parse the whole signed value as `i64` so the extreme relative delta
1235        // `-2147483648` (whose magnitude exceeds `i32::MAX`) is still read as
1236        // itself rather than failing and being stored as an absolute value.
1237        match trimmed.parse::<i64>() {
1238            // The running offset is a valid `i32`, so widening it to `i64`
1239            // makes the accumulation itself infallible; `saturating_add` then
1240            // guards the (already absurd) case of a delta near `i64::MIN/MAX`,
1241            // and the result is clamped back into the `i32` the attribute
1242            // stores. This keeps a pathological offset from overflowing –
1243            // which would panic in debug builds and wrap in release builds –
1244            // rather than imposing a real bound the syntax does not otherwise
1245            // impose.
1246            Ok(delta) => InterpretedValue::Value(
1247                (self.level_offset() as i64)
1248                    .saturating_add(delta)
1249                    .clamp(i32::MIN as i64, i32::MAX as i64)
1250                    .to_string(),
1251            ),
1252            Err(_) => value,
1253        }
1254    }
1255
1256    /// Resolves a `leveloffset` assignment (see
1257    /// [`resolve_leveloffset_assignment`](Self::resolve_leveloffset_assignment))
1258    /// and, if the resulting absolute offset is so large or small that *every*
1259    /// heading would be shifted outside the supported 1..=5 section-level
1260    /// range, records a [`LeveloffsetExcludesAllHeadingLevels`] warning
1261    /// against `span`.
1262    ///
1263    /// [`LeveloffsetExcludesAllHeadingLevels`]:
1264    /// crate::warnings::WarningType::LeveloffsetExcludesAllHeadingLevels
1265    fn resolve_leveloffset_and_warn<'src>(
1266        &self,
1267        value: InterpretedValue,
1268        span: crate::Span<'src>,
1269        warnings: &mut Vec<Warning<'src>>,
1270    ) -> InterpretedValue {
1271        let value = self.resolve_leveloffset_assignment(value);
1272
1273        if let InterpretedValue::Value(ref v) = value
1274            && let Ok(offset) = v.trim().parse::<i32>()
1275            && !leveloffset_admits_any_heading(offset)
1276        {
1277            warnings.push(Warning::new(
1278                span,
1279                WarningType::LeveloffsetExcludesAllHeadingLevels(offset),
1280            ));
1281        }
1282
1283        value
1284    }
1285
1286    /// Captures the parser's fully-resolved document-attribute state so it can
1287    /// outlive the parser – for example, retained on a [`Document`] to answer
1288    /// [`attribute_value`]/[`has_attribute`]/[`is_attribute_set`] without a
1289    /// parser in hand (the embed path a renderer uses for `convert_document`).
1290    ///
1291    /// This shares the parser's attribute tables by [`Arc`] rather than copying
1292    /// them, so it is cheap to take on every parse (the large built-in table is
1293    /// never deep-cloned). The time-dependent attributes are not materialized;
1294    /// the snapshot carries the reference-time configuration so it can resolve
1295    /// them on demand exactly as the parser does. See [`ResolvedAttributes`].
1296    ///
1297    /// [`Document`]: crate::Document
1298    /// [`attribute_value`]: Self::attribute_value
1299    /// [`has_attribute`]: Self::has_attribute
1300    /// [`is_attribute_set`]: Self::is_attribute_set
1301    pub(crate) fn snapshot_attributes(&self) -> ResolvedAttributes {
1302        ResolvedAttributes::new(
1303            Arc::clone(&self.attribute_values),
1304            Arc::clone(&self.default_attribute_values),
1305            self.counter_values.borrow().clone(),
1306            self.safe,
1307            self.reference_time.clone(),
1308            self.input_mtime.clone(),
1309        )
1310    }
1311
1312    /// Resolves whether a document title should be displayed, from the
1313    /// `showtitle`/`notitle` attribute pair (which are complements).
1314    ///
1315    /// `showtitle` takes precedence: if present, the title shows precisely when
1316    /// it is set. Otherwise `notitle`, if present, hides the title when set.
1317    /// When neither attribute is present, `default_shown` decides – a
1318    /// standalone document (such as a nested AsciiDoc table cell) shows its
1319    /// title, while an embedded document does not.
1320    pub(crate) fn resolve_show_title(&self, default_shown: bool) -> bool {
1321        if self.has_attribute("showtitle") {
1322            self.is_attribute_set("showtitle")
1323        } else if self.has_attribute("notitle") {
1324            !self.is_attribute_set("notitle")
1325        } else {
1326            default_shown
1327        }
1328    }
1329
1330    /// Applies the `notitle` ⇔ `showtitle` inverse-toggle linkage
1331    /// (Asciidoctor asciidoctor/asciidoctor#3804).
1332    ///
1333    /// `notitle` and `showtitle` are two spellings of a single "show the
1334    /// document title" switch, wired as opposites: assigning either attribute
1335    /// updates the other so the resolved document reflects one consistent
1336    /// toggle. This yields last-assignment-wins semantics for free, since each
1337    /// assignment rewrites the partner left by the previous one.
1338    ///
1339    /// `attr_name` is the attribute just assigned and `value` its stored value;
1340    /// the call is a no-op for any other name. Turning the toggle *off* (an
1341    /// explicit [unset], e.g. `:!notitle:`) turns the partner *on* – it is
1342    /// stored [set] with the same `modification_context` and
1343    /// `silent_when_locked` flag as the triggering assignment. Turning the
1344    /// toggle *on* (an empty `Set` or an explicit value, e.g. `:notitle:`)
1345    /// *removes* the partner entirely.
1346    ///
1347    /// The partner is removed – rather than left as an explicit unset
1348    /// tombstone – to mirror Asciidoctor's attribute-hash semantics, where an
1349    /// "off" attribute is simply absent. That keeps every observer consistent:
1350    /// `has_attribute`, `ifdef`/`ifndef`, and `{partner}` reference
1351    /// substitution all see the same absence Asciidoctor does (so, e.g., a
1352    /// `{showtitle}` reference stays literal after `:notitle:` rather than
1353    /// silently resolving to an empty string).
1354    ///
1355    /// [set]: https://docs.asciidoctor.org/asciidoc/latest/attributes/set-attributes/
1356    /// [unset]: https://docs.asciidoctor.org/asciidoc/latest/attributes/unset-attributes/
1357    fn apply_title_visibility_linkage(
1358        &mut self,
1359        attr_name: &str,
1360        value: &InterpretedValue,
1361        modification_context: ModificationContext,
1362        silent_when_locked: bool,
1363    ) {
1364        let partner = match attr_name {
1365            "notitle" => "showtitle",
1366            "showtitle" => "notitle",
1367            _ => return,
1368        };
1369
1370        // Either way the partner supersedes (and resets) any counter of the
1371        // same name, mirroring a direct assignment.
1372        self.counter_values.borrow_mut().remove(partner);
1373
1374        if let InterpretedValue::Unset = value {
1375            // The toggle is off, so the partner turns on.
1376            Arc::make_mut(&mut self.attribute_values).insert(
1377                partner.to_string(),
1378                AttributeValue {
1379                    allowable_value: AllowableValue::Any,
1380                    modification_context,
1381                    silent_when_locked,
1382                    value: InterpretedValue::Set,
1383                },
1384            );
1385        } else if self.attribute_values.contains_key(partner) {
1386            // The toggle is on, so the partner turns off – and, matching
1387            // Asciidoctor, "off" means absent. (Guarded so the common case of
1388            // no prior partner entry does not clone the shared map.)
1389            Arc::make_mut(&mut self.attribute_values).remove(partner);
1390        }
1391    }
1392
1393    /// Forces the `doctype` attribute to `value`.
1394    ///
1395    /// Used when a nested AsciiDoc table cell resets its doctype to the default
1396    /// (a cell does not inherit the parent's doctype). The value stays
1397    /// modifiable from the document body so the cell may still set its own
1398    /// doctype.
1399    ///
1400    /// The derived `backend-html5-doctype-{doctype}` attribute needs no
1401    /// explicit refresh: it is synthesized on the fly for whatever
1402    /// `doctype` currently resolves to (see
1403    /// [`attribute_value`](Self::attribute_value)).
1404    pub(crate) fn force_doctype(&mut self, value: &str) {
1405        Arc::make_mut(&mut self.attribute_values).insert(
1406            "doctype".to_string(),
1407            AttributeValue {
1408                allowable_value: AllowableValue::Any,
1409                modification_context: ModificationContext::ApiOrDocumentBody,
1410                silent_when_locked: false,
1411                value: InterpretedValue::Value(value.to_string()),
1412            },
1413        );
1414    }
1415
1416    /// Records the current [`attribute_values`](Self::attribute_values) as the
1417    /// configured baseline restored at the start of each parse.
1418    ///
1419    /// Called at the end of every attribute-configuring builder method, once
1420    /// all of that call's effects (including any
1421    /// [title-visibility](Self::apply_title_visibility_linkage) partner or
1422    /// safe-mode attributes) have been applied. The snapshot is an [`Arc`]
1423    /// clone, so it captures exactly the post-call state and stays cheap; see
1424    /// [`baseline_attribute_values`](Self::baseline_attribute_values).
1425    fn capture_attribute_baseline(&mut self) {
1426        self.baseline_attribute_values = Arc::clone(&self.attribute_values);
1427    }
1428
1429    /// Sets the value of an [intrinsic attribute].
1430    ///
1431    /// Intrinsic attributes are set automatically by the processor. These
1432    /// attributes provide information about the document being processed (e.g.,
1433    /// `docfile`), the security mode under which the processor is running
1434    /// (e.g., `safe-mode-name`), and information about the user’s environment
1435    /// (e.g., `user-home`).
1436    ///
1437    /// The [`modification_context`](ModificationContext) establishes whether
1438    /// the value can be subsequently modified by the document header and/or in
1439    /// the document body.
1440    ///
1441    /// A single trailing `@` on `value` is AsciiDoc's *soft-set* modifier: it
1442    /// is stripped from the stored value and marks the attribute as
1443    /// overridable by a document `:name:` entry (i.e. the effective
1444    /// [`modification_context`](ModificationContext) becomes
1445    /// [`Anywhere`](ModificationContext::Anywhere), regardless of the value
1446    /// passed). To store a value that genuinely ends in `@`, set it from the
1447    /// document body instead, where the trailing `@` is literal.
1448    ///
1449    /// Subsequent calls to this function or [`with_intrinsic_attribute_bool()`]
1450    /// are always permitted. The last such call for any given attribute name
1451    /// takes precendence.
1452    ///
1453    /// [intrinsic attribute]: https://docs.asciidoctor.org/asciidoc/latest/attributes/document-attributes-ref/#intrinsic-attributes
1454    ///
1455    /// [`with_intrinsic_attribute_bool()`]: Self::with_intrinsic_attribute_bool
1456    #[must_use]
1457    pub fn with_intrinsic_attribute<N: AsRef<str>, V: AsRef<str>>(
1458        mut self,
1459        name: N,
1460        value: V,
1461        modification_context: ModificationContext,
1462    ) -> Self {
1463        let name = alias_attr_name(name.as_ref().to_lowercase());
1464
1465        let (value, modification_context) =
1466            apply_soft_set_modifier(value.as_ref(), modification_context);
1467
1468        let value = InterpretedValue::Value(value);
1469        let attribute_value = AttributeValue {
1470            allowable_value: AllowableValue::Any,
1471            modification_context,
1472            silent_when_locked: false,
1473            value: value.clone(),
1474        };
1475
1476        Arc::make_mut(&mut self.attribute_values).insert(name.clone(), attribute_value);
1477
1478        self.apply_title_visibility_linkage(&name, &value, modification_context, false);
1479
1480        self.capture_attribute_baseline();
1481
1482        self
1483    }
1484
1485    /// Sets the value of an [intrinsic attribute], rejecting any disallowed
1486    /// subsequent write *silently*.
1487    ///
1488    /// This behaves exactly like [`with_intrinsic_attribute()`] except that a
1489    /// document header or body assignment that the
1490    /// [`modification_context`](ModificationContext) does not permit is dropped
1491    /// with **no** `AttributeValueIsLocked` warning, instead of recording one.
1492    /// The rejected write is otherwise handled identically (the value is left
1493    /// unchanged).
1494    ///
1495    /// This reproduces Asciidoctor's *silent* safe-mode attribute restrictions:
1496    /// under `SERVER`/`SECURE`, a document assignment of a restricted
1497    /// conversion attribute (`backend`, `doctype`, `docinfo`,
1498    /// `source-highlighter`) is simply dropped, with no diagnostic. Seed
1499    /// such an attribute as an [`ApiOnly`](ModificationContext::ApiOnly)
1500    /// silent intrinsic to lock it against document assignment without
1501    /// warning.
1502    ///
1503    /// Subsequent calls to this function or the other
1504    /// `with_intrinsic_attribute` variants are always permitted. The last
1505    /// such call for any given attribute name takes precedence.
1506    ///
1507    /// [intrinsic attribute]: https://docs.asciidoctor.org/asciidoc/latest/attributes/document-attributes-ref/#intrinsic-attributes
1508    ///
1509    /// [`with_intrinsic_attribute()`]: Self::with_intrinsic_attribute
1510    #[must_use]
1511    pub fn with_intrinsic_attribute_silent<N: AsRef<str>, V: AsRef<str>>(
1512        mut self,
1513        name: N,
1514        value: V,
1515        modification_context: ModificationContext,
1516    ) -> Self {
1517        let name = alias_attr_name(name.as_ref().to_lowercase());
1518
1519        let (value, modification_context) =
1520            apply_soft_set_modifier(value.as_ref(), modification_context);
1521
1522        let value = InterpretedValue::Value(value);
1523        let attribute_value = AttributeValue {
1524            allowable_value: AllowableValue::Any,
1525            modification_context,
1526            silent_when_locked: true,
1527            value: value.clone(),
1528        };
1529
1530        Arc::make_mut(&mut self.attribute_values).insert(name.clone(), attribute_value);
1531
1532        self.apply_title_visibility_linkage(&name, &value, modification_context, true);
1533
1534        self.capture_attribute_baseline();
1535
1536        self
1537    }
1538
1539    /// Register a referenceable element (anchor, section, bibliography entry)
1540    /// in the document catalog.
1541    ///
1542    /// This takes `&self` (rather than `&mut self`) so that it can be called
1543    /// from inline-substitution code paths that only hold a shared reference to
1544    /// the parser, such as a regex [`Replacer`](regex::Replacer).
1545    pub(crate) fn register_ref(
1546        &self,
1547        id: &str,
1548        reftext: Option<&str>,
1549        ref_type: RefType,
1550    ) -> Result<(), crate::document::DuplicateIdError> {
1551        self.catalog
1552            .borrow_mut()
1553            .register_ref(id, reftext, ref_type)
1554    }
1555
1556    /// Attaches an [`XrefSignifier`](crate::parser::XrefSignifier) to an
1557    /// already-registered catalog element, so a cross-reference to it can build
1558    /// `full`/`short` [`xrefstyle`](crate::parser::XrefStyle) text.
1559    ///
1560    /// Takes `&self` for the same reason as
1561    /// [`register_ref`](Self::register_ref).
1562    pub(crate) fn set_ref_signifier(&self, id: &str, signifier: crate::parser::XrefSignifier) {
1563        self.catalog.borrow_mut().set_signifier(id, signifier);
1564    }
1565
1566    /// Records a referenced image in the document catalog when
1567    /// [`catalog_assets`](Self::with_catalog_assets) is enabled. A no-op
1568    /// otherwise.
1569    ///
1570    /// `target` is the (already attribute-substituted) image target as written
1571    /// in the macro; `imagesdir` is the value of the document `imagesdir`
1572    /// attribute at the point of reference, or `None` when it is unset.
1573    ///
1574    /// Takes `&self` so it can be called from the macros substitution step,
1575    /// which only holds a shared reference to the parser.
1576    pub(crate) fn register_image(&self, target: String, imagesdir: Option<String>) {
1577        if self.catalog_assets {
1578            self.catalog.borrow_mut().register_image(target, imagesdir);
1579        }
1580    }
1581
1582    /// Records a referenced link target in the document catalog when
1583    /// [`catalog_assets`](Self::with_catalog_assets) is enabled. A no-op
1584    /// otherwise.
1585    ///
1586    /// `target` is the final link target as it appears in the rendered `href`
1587    /// (e.g. `https://example.org`, `mailto:fred@example.com`).
1588    ///
1589    /// Takes `&self` so it can be called from the macros substitution step,
1590    /// which only holds a shared reference to the parser.
1591    pub(crate) fn register_link(&self, target: String) {
1592        if self.catalog_assets {
1593            self.catalog.borrow_mut().register_link(target);
1594        }
1595    }
1596
1597    /// Registers a callout number defined by a verbatim block.
1598    ///
1599    /// Takes `&self` so it can be called from the callouts substitution step,
1600    /// which only holds a shared reference to the parser.
1601    pub(crate) fn register_callout(&self, number: u32) {
1602        self.callouts.borrow_mut().current.push(number);
1603    }
1604
1605    /// Returns `true` if a callout numbered `number` was registered for the
1606    /// current (not-yet-closed) callout list.
1607    pub(crate) fn callout_defined(&self, number: u32) -> bool {
1608        self.callouts.borrow().current.contains(&number)
1609    }
1610
1611    /// Closes the current callout list, so callouts registered afterward belong
1612    /// to the next list.
1613    pub(crate) fn close_callout_list(&self) {
1614        self.callouts.borrow_mut().current.clear();
1615    }
1616
1617    /// Returns the number of an already-defined footnote with the given ID, if
1618    /// one exists in the current document's footnote registry.
1619    ///
1620    /// Takes `&self` so it can be called from the macros substitution step,
1621    /// which only holds a shared reference to the parser.
1622    pub(crate) fn footnote_index_for_id(&self, id: &str) -> Option<String> {
1623        self.catalog
1624            .borrow()
1625            .footnote_with_id(id)
1626            .map(|f| f.index.clone())
1627    }
1628
1629    /// Defines a new footnote, advancing the `footnote-number` counter and
1630    /// registering the footnote in the current document's registry. Returns the
1631    /// number assigned to the footnote.
1632    ///
1633    /// `source` is the span of the content the defining `footnote:[…]` macro
1634    /// was written in; its offset into the document source is recorded so a
1635    /// cross-reference warning can be anchored at the footnote rather than at
1636    /// the whole document. When the footnote is defined while substituting a
1637    /// privately-owned sub-source (a Markdown-style blockquote or an AsciiDoc
1638    /// table cell – see
1639    /// [`owned_subsource_depth`](Self::owned_subsource_depth)), that offset
1640    /// does not map to the document, so no location is recorded and
1641    /// resolution falls back to the whole-document span.
1642    ///
1643    /// Takes `&self` so it can be called from the macros substitution step.
1644    pub(crate) fn define_footnote(
1645        &self,
1646        id: Option<&str>,
1647        text: String,
1648        xrefs: Vec<crate::content::XrefSegment>,
1649        source: crate::Span<'_>,
1650    ) -> String {
1651        // A footnote's text is extracted out of the block during macro
1652        // substitution, so any cross-reference inside it never reaches the
1653        // document-level resolution pass over block content. Those
1654        // cross-references are captured (as placeholders in `text` plus the
1655        // `xrefs` segments) so they can be resolved alongside the block
1656        // references. The stored `text` is the unresolved fallback rendering
1657        // until then, so it is always clean.
1658        let (text, deferred) = if xrefs.is_empty() {
1659            (text, None)
1660        } else {
1661            let deferred = crate::content::FootnoteDeferred::new(text, xrefs);
1662            let rendered = deferred.render(&*self.renderer);
1663            (rendered, Some(Box::new(deferred)))
1664        };
1665
1666        // Footnotes are numbered consecutively throughout the document via the
1667        // `footnote-number` counter, which is seeded to `0` so the first
1668        // footnote is numbered `1`. The counter is a document-wide attribute, so
1669        // numbering continues across nested documents (AsciiDoc table cells)
1670        // even though the footnote *list* does not. The counter honors any seed
1671        // the document sets, so a non-integer seed yields a non-integer number
1672        // (matching Asciidoctor); the value is therefore kept as a string.
1673        let index = self.counter("footnote-number", None);
1674
1675        // Record the defining occurrence's location only when it is locatable in
1676        // the document source. A footnote defined inside an owned sub-source
1677        // indexes that private source, whose offset would misplace the warning,
1678        // so it is left unrecorded (resolution then falls back to the
1679        // whole-document span).
1680        let location = if self.owned_subsource_depth == 0 {
1681            Some((source.byte_offset(), source.data().len()))
1682        } else {
1683            None
1684        };
1685
1686        self.catalog
1687            .borrow_mut()
1688            .register_footnote(crate::document::Footnote {
1689                index: index.clone(),
1690                id: id.map(|s| s.to_owned()),
1691                text,
1692                deferred,
1693                location,
1694            });
1695
1696        index
1697    }
1698
1699    /// Removes and returns the current document's footnote list, leaving an
1700    /// empty list behind. Used to give a nested document (an AsciiDoc table
1701    /// cell) its own footnote registry; see [`restore_footnotes`].
1702    ///
1703    /// [`restore_footnotes`]: Self::restore_footnotes
1704    pub(crate) fn take_footnotes(&self) -> Vec<crate::document::Footnote> {
1705        self.catalog.borrow_mut().take_footnotes()
1706    }
1707
1708    /// Restores a previously-[taken](Self::take_footnotes) footnote list,
1709    /// discarding any footnotes registered in the meantime (i.e. those defined
1710    /// inside the nested document).
1711    pub(crate) fn restore_footnotes(&self, footnotes: Vec<crate::document::Footnote>) {
1712        self.catalog.borrow_mut().restore_footnotes(footnotes);
1713    }
1714
1715    /// Records a warning produced while replacing attribute references.
1716    ///
1717    /// Takes `&self` so it can be called from the attributes substitution step,
1718    /// which only holds a shared reference to the parser. `source` locates the
1719    /// text the warning refers to; its byte offset and length are stored so a
1720    /// spanned [`Warning`] can be reconstructed later (see
1721    /// [`take_substitution_warnings`](Self::take_substitution_warnings)).
1722    pub(crate) fn record_substitution_warning(
1723        &self,
1724        source: crate::Span<'_>,
1725        warning: WarningType,
1726    ) {
1727        self.substitution_warnings
1728            .borrow_mut()
1729            .push(DeferredWarning {
1730                offset: source.byte_offset(),
1731                len: source.len(),
1732                warning,
1733                origin: None,
1734            });
1735    }
1736
1737    /// Returns the number of substitution warnings recorded so far.
1738    ///
1739    /// Used together with [`truncate_substitution_warnings`] to discard
1740    /// warnings recorded while parsing an owned (e.g. include-expanded) source,
1741    /// whose offsets do not refer to the primary document source.
1742    ///
1743    /// [`truncate_substitution_warnings`]: Self::truncate_substitution_warnings
1744    pub(crate) fn substitution_warnings_len(&self) -> usize {
1745        self.substitution_warnings.borrow().len()
1746    }
1747
1748    /// Discards any substitution warnings recorded since the buffer held `len`
1749    /// entries.
1750    pub(crate) fn truncate_substitution_warnings(&self, len: usize) {
1751        self.substitution_warnings.borrow_mut().truncate(len);
1752    }
1753
1754    /// Removes and returns any substitution warnings recorded since the buffer
1755    /// held `len` entries.
1756    pub(crate) fn drain_substitution_warnings_since(&self, len: usize) -> Vec<DeferredWarning> {
1757        self.substitution_warnings.borrow_mut().split_off(len)
1758    }
1759
1760    /// Takes the substitution warnings recorded during parsing, leaving the
1761    /// buffer empty.
1762    pub(crate) fn take_substitution_warnings(&self) -> Vec<DeferredWarning> {
1763        std::mem::take(&mut *self.substitution_warnings.borrow_mut())
1764    }
1765
1766    /// Returns `true` while the parser is parsing the content of an owned
1767    /// (include-expanded) AsciiDoc table cell, i.e. when a span's line indexes
1768    /// an owned copy rather than the document source.
1769    pub(crate) fn is_in_owned_cell_source(&self) -> bool {
1770        !self.owned_cell_source_maps.is_empty()
1771    }
1772
1773    /// Pushes an owned cell's source map for the duration of its parse. Paired
1774    /// with [`pop_owned_cell_source_map`](Self::pop_owned_cell_source_map).
1775    pub(crate) fn push_owned_cell_source_map(&mut self, source_map: Rc<SourceMap>) {
1776        self.owned_cell_source_maps.push(source_map);
1777    }
1778
1779    /// Pops the source map pushed by the matching
1780    /// [`push_owned_cell_source_map`](Self::push_owned_cell_source_map).
1781    pub(crate) fn pop_owned_cell_source_map(&mut self) {
1782        self.owned_cell_source_maps.pop();
1783    }
1784
1785    /// Resolves a line number in the innermost owned cell's source back to the
1786    /// file and line it originally came from, using that cell's source map.
1787    ///
1788    /// Returns `None` when not inside an owned cell source.
1789    pub(crate) fn owned_cell_original_file_and_line(&self, line: usize) -> Option<SourceLine> {
1790        self.owned_cell_source_maps
1791            .last()
1792            .and_then(|sm| sm.original_file_and_line(line))
1793    }
1794
1795    /// Records a warning raised by a directive at `line` in the innermost owned
1796    /// cell's source, resolving `line` to the file and line it originally came
1797    /// from so the warning can be surfaced later with a real cursor (see
1798    /// [`take_owned_cell_warnings`]).
1799    ///
1800    /// A no-op when not inside an owned cell source (the line does not resolve
1801    /// to an owned origin) – the caller only reaches this from an owned-cell
1802    /// parse, but the guard keeps a stray call from recording an unanchorable
1803    /// warning.
1804    ///
1805    /// Takes `&self`: an owned-cell parse holds the parser mutably behind a
1806    /// `self_cell` construction closure, so recording goes through interior
1807    /// mutability.
1808    ///
1809    /// [`take_owned_cell_warnings`]: Self::take_owned_cell_warnings
1810    pub(crate) fn record_owned_cell_warning(
1811        &self,
1812        line: usize,
1813        warning: WarningType,
1814        origin_override: Option<SourceLine>,
1815    ) {
1816        // A no-output directive that originated in a file the cell *included*
1817        // carries a true `(file, line)` origin already; prefer it. Otherwise
1818        // resolve the cell's own directive line through the enclosing owned
1819        // cell's source map.
1820        let origin = origin_override.or_else(|| self.owned_cell_original_file_and_line(line));
1821        if let Some(origin) = origin {
1822            self.owned_cell_warnings
1823                .borrow_mut()
1824                .push(ResolvedWarning { origin, warning });
1825        }
1826    }
1827
1828    /// Takes the owned-cell warnings recorded during parsing, leaving the
1829    /// buffer empty.
1830    pub(crate) fn take_owned_cell_warnings(&self) -> Vec<ResolvedWarning> {
1831        std::mem::take(&mut *self.owned_cell_warnings.borrow_mut())
1832    }
1833
1834    /// Generate a unique ID derived from `base_id` and register it in the
1835    /// document catalog, returning the ID that was assigned.
1836    pub(crate) fn generate_and_register_unique_id(
1837        &self,
1838        base_id: &str,
1839        reftext: Option<&str>,
1840        ref_type: RefType,
1841    ) -> String {
1842        // A synthetic ID that collides with an existing one is enumerated using
1843        // the `idseparator` (e.g. `_section_one`, `_section_one_2`), matching
1844        // Ruby Asciidoctor – not a hardcoded hyphen. Mirrors the separator
1845        // resolution in `generate_section_id`.
1846        let separator = self
1847            .attribute_value("idseparator")
1848            .as_maybe_str()
1849            .unwrap_or_default()
1850            .chars()
1851            .next()
1852            .map(|c| c.to_string())
1853            .unwrap_or_default();
1854
1855        self.catalog
1856            .borrow_mut()
1857            .generate_and_register_unique_id(base_id, reftext, ref_type, &separator)
1858    }
1859
1860    /// Takes the catalog from the parser, transferring ownership and leaving an
1861    /// empty catalog in its place.
1862    ///
1863    /// This is used by `Document::parse` to transfer the catalog from the
1864    /// parser to the document at the end of parsing.
1865    pub(crate) fn take_catalog(&mut self) -> Catalog {
1866        std::mem::take(&mut *self.catalog.borrow_mut())
1867    }
1868
1869    /* Comment out until we're prepared to use and test this.
1870        /// Sets the default value for an [intrinsic attribute].
1871        ///
1872        /// Default values for attributes are provided automatically by the
1873        /// processor. These values provide a falllback textual value for an
1874        /// attribute when it is merely "set" by the document via API, header, or
1875        /// document body.
1876        ///
1877        /// Calling this does not imply that the value is set automatically by
1878        /// default, nor does it establish any policy for where the value may be
1879        /// modified. For that, please use [`with_intrinsic_attribute`].
1880        ///
1881        /// [intrinsic attribute]: https://docs.asciidoctor.org/asciidoc/latest/attributes/document-attributes-ref/#intrinsic-attributes
1882        /// [`with_intrinsic_attribute`]: Self::with_intrinsic_attribute
1883        pub fn with_default_attribute_value<N: AsRef<str>, V: AsRef<str>>(
1884            mut self,
1885            name: N,
1886            value: V,
1887        ) -> Self {
1888            self.default_attribute_values
1889                .insert(name.as_ref().to_string(), value.as_ref().to_string());
1890
1891            self
1892        }
1893    */
1894
1895    /// Sets the value of an [intrinsic attribute] from a boolean flag.
1896    ///
1897    /// A boolean `true` is interpreted as "set." A boolean `false` is
1898    /// interpreted as "unset."
1899    ///
1900    /// Intrinsic attributes are set automatically by the processor. These
1901    /// attributes provide information about the document being processed (e.g.,
1902    /// `docfile`), the security mode under which the processor is running
1903    /// (e.g., `safe-mode-name`), and information about the user’s environment
1904    /// (e.g., `user-home`).
1905    ///
1906    /// The [`modification_context`](ModificationContext) establishes whether
1907    /// the value can be subsequently modified by the document header and/or in
1908    /// the document body.
1909    ///
1910    /// Subsequent calls to this function or [`with_intrinsic_attribute()`] are
1911    /// always permitted. The last such call for any given attribute name takes
1912    /// precendence.
1913    ///
1914    /// [intrinsic attribute]: https://docs.asciidoctor.org/asciidoc/latest/attributes/document-attributes-ref/#intrinsic-attributes
1915    ///
1916    /// [`with_intrinsic_attribute()`]: Self::with_intrinsic_attribute
1917    #[must_use]
1918    pub fn with_intrinsic_attribute_bool<N: AsRef<str>>(
1919        mut self,
1920        name: N,
1921        value: bool,
1922        modification_context: ModificationContext,
1923    ) -> Self {
1924        let name = alias_attr_name(name.as_ref().to_lowercase());
1925        let value = if value {
1926            InterpretedValue::Set
1927        } else {
1928            InterpretedValue::Unset
1929        };
1930        let attribute_value = AttributeValue {
1931            allowable_value: AllowableValue::Any,
1932            modification_context,
1933            silent_when_locked: false,
1934            value: value.clone(),
1935        };
1936
1937        Arc::make_mut(&mut self.attribute_values).insert(name.clone(), attribute_value);
1938
1939        self.apply_title_visibility_linkage(&name, &value, modification_context, false);
1940
1941        self.capture_attribute_baseline();
1942
1943        self
1944    }
1945
1946    /// Sets the value of an [intrinsic attribute] from a boolean flag,
1947    /// rejecting any disallowed subsequent write *silently*.
1948    ///
1949    /// This behaves exactly like [`with_intrinsic_attribute_bool()`] except
1950    /// that a document header or body assignment that the
1951    /// [`modification_context`](ModificationContext) does not permit is dropped
1952    /// with **no** `AttributeValueIsLocked` warning, instead of recording one.
1953    /// See [`with_intrinsic_attribute_silent()`] for the motivating use case
1954    /// (Asciidoctor's silent safe-mode attribute restrictions).
1955    ///
1956    /// A boolean `true` is interpreted as "set." A boolean `false` is
1957    /// interpreted as "unset."
1958    ///
1959    /// Subsequent calls to this function or the other
1960    /// `with_intrinsic_attribute` variants are always permitted. The last
1961    /// such call for any given attribute name takes precedence.
1962    ///
1963    /// [intrinsic attribute]: https://docs.asciidoctor.org/asciidoc/latest/attributes/document-attributes-ref/#intrinsic-attributes
1964    ///
1965    /// [`with_intrinsic_attribute_bool()`]: Self::with_intrinsic_attribute_bool
1966    /// [`with_intrinsic_attribute_silent()`]: Self::with_intrinsic_attribute_silent
1967    #[must_use]
1968    pub fn with_intrinsic_attribute_bool_silent<N: AsRef<str>>(
1969        mut self,
1970        name: N,
1971        value: bool,
1972        modification_context: ModificationContext,
1973    ) -> Self {
1974        let name = alias_attr_name(name.as_ref().to_lowercase());
1975        let value = if value {
1976            InterpretedValue::Set
1977        } else {
1978            InterpretedValue::Unset
1979        };
1980        let attribute_value = AttributeValue {
1981            allowable_value: AllowableValue::Any,
1982            modification_context,
1983            silent_when_locked: true,
1984            value: value.clone(),
1985        };
1986
1987        Arc::make_mut(&mut self.attribute_values).insert(name.clone(), attribute_value);
1988
1989        self.apply_title_visibility_linkage(&name, &value, modification_context, true);
1990
1991        self.capture_attribute_baseline();
1992
1993        self
1994    }
1995
1996    /// Pins the reference time (the value of "now") used to compute the
1997    /// time-dependent document attributes, for reproducible output.
1998    ///
1999    /// AsciiDoc derives `localdate`, `localtime`, `localdatetime`, and
2000    /// `localyear` from the current wall-clock time, and `docdate`, `doctime`,
2001    /// `docdatetime`, and `docyear` from the source file's modification time
2002    /// (falling back to "now" when no modification time is known). Because
2003    /// those values change from run to run, any output that embeds them is
2004    /// not reproducible. Supplying a [`ReferenceTime`] pins "now" to a
2005    /// fixed instant so the computed attributes are stable.
2006    ///
2007    /// This is the API counterpart of the `SOURCE_DATE_EPOCH` environment
2008    /// variable; a value set here takes precedence over that variable. To pin
2009    /// only the source-modification time that drives the `doc*` attributes
2010    /// (leaving `local*` on the real clock), use [`with_input_mtime`] instead;
2011    /// an [`with_input_mtime`] value takes precedence over this one for the
2012    /// `doc*` attributes.
2013    ///
2014    /// A value set via the document header or body (e.g. an explicit
2015    /// `:docdate:`) still wins over the computed default.
2016    ///
2017    /// [`with_input_mtime`]: Self::with_input_mtime
2018    #[must_use]
2019    pub fn with_reference_time(mut self, reference_time: ReferenceTime) -> Self {
2020        self.reference_time = Some(reference_time);
2021        self
2022    }
2023
2024    /// Pins the modification time of the source document, which drives the
2025    /// `docdate`, `doctime`, `docdatetime`, and `docyear` attributes.
2026    ///
2027    /// This mirrors Asciidoctor's `input_mtime` option: the `local*` attributes
2028    /// continue to reflect "now" (the real clock, a [`with_reference_time`]
2029    /// value, or `SOURCE_DATE_EPOCH`), while the `doc*` attributes reflect the
2030    /// supplied source modification time. A value set here takes precedence
2031    /// over a [`with_reference_time`] value for the `doc*` attributes.
2032    ///
2033    /// A value set via the document header or body (e.g. an explicit
2034    /// `:docdate:`) still wins over the computed default.
2035    ///
2036    /// [`with_reference_time`]: Self::with_reference_time
2037    #[must_use]
2038    pub fn with_input_mtime(mut self, input_mtime: ReferenceTime) -> Self {
2039        self.input_mtime = Some(input_mtime);
2040        self
2041    }
2042
2043    /// Resolves a time-dependent document attribute (`docdate`, `doctime`,
2044    /// `docdatetime`, `docyear`, or a `local*` sibling) on demand, returning
2045    /// `None` for any other name (or when the attribute resolves to no value,
2046    /// as `docyear` / `localyear` do for an explicit date without a `YYYY-`
2047    /// prefix).
2048    ///
2049    /// The reference instant is captured lazily on the first such read of a
2050    /// parse and cached (see [`datetime_context`](Self::datetime_context)), so
2051    /// a parse that never references a time-dependent attribute does no
2052    /// clock, environment, or allocation work, and repeated reads observe
2053    /// one consistent instant. An explicit value assigned via the API,
2054    /// header, or body always wins; the derived `*year` / `*datetime` are
2055    /// computed from whichever value each sibling resolves to. See
2056    /// [`DatetimeContext`].
2057    ///
2058    /// Takes `&self` so it can be called from the shared-reference attribute
2059    /// readers (which the substitution code paths reach with only a `&Parser`);
2060    /// the lazy capture goes through the [`RefCell`].
2061    fn resolve_datetime_attribute(&self, name: &str) -> Option<InterpretedValue> {
2062        if !is_datetime_attribute(name) {
2063            return None;
2064        }
2065
2066        let context = {
2067            let mut slot = self.datetime_context.borrow_mut();
2068            slot.get_or_insert_with(|| {
2069                DatetimeContext::capture(self.reference_time.as_ref(), self.input_mtime.as_ref())
2070            })
2071            .clone()
2072        };
2073
2074        context
2075            .resolve(name, |sibling| self.stored_datetime_override(sibling))
2076            .map(InterpretedValue::Value)
2077    }
2078
2079    /// Returns the *explicitly-set* value of `name` from the per-parser
2080    /// attribute map, as an owned string (a value-less "set" reads as an empty
2081    /// string), or `None` when it has no such entry.
2082    ///
2083    /// This reads only the stored overrides – never the on-the-fly datetime
2084    /// resolution – so it can supply the explicit sibling values
2085    /// [`resolve_datetime_attribute`](Self::resolve_datetime_attribute) needs
2086    /// without recursing. It mirrors the Ruby truthiness the datetime
2087    /// computation relies on (`attrs['docdate']`), where any present value –
2088    /// including an empty string – counts as explicitly supplied.
2089    fn stored_datetime_override(&self, name: &str) -> Option<String> {
2090        self.attribute_values
2091            .get(name)
2092            .and_then(|av| match &av.value {
2093                InterpretedValue::Value(value) => Some(value.clone()),
2094                InterpretedValue::Set => Some(String::new()),
2095                InterpretedValue::Unset => None,
2096            })
2097    }
2098
2099    /// Replace the default [`InlineSubstitutionRenderer`] for this parser.
2100    ///
2101    /// The default implementation of [`InlineSubstitutionRenderer`] that is
2102    /// provided is suitable for HTML5 rendering. If you are targeting a
2103    /// different back-end rendering, you will need to provide your own
2104    /// implementation and set it using this call before parsing.
2105    #[must_use]
2106    pub fn with_inline_substitution_renderer<ISR: InlineSubstitutionRenderer + 'static>(
2107        mut self,
2108        renderer: ISR,
2109    ) -> Self {
2110        self.renderer = Rc::new(renderer);
2111        self
2112    }
2113
2114    /// Sets the name of the primary file to be parsed when [`parse()`] is
2115    /// called.
2116    ///
2117    /// This name will be used for any error messages detected in this file and
2118    /// also will be passed to [`IncludeFileHandler::resolve_target()`] as the
2119    /// `source` argument for any `include::` file resolution requests from this
2120    /// file.
2121    ///
2122    /// [`parse()`]: Self::parse
2123    /// [`IncludeFileHandler::resolve_target()`]: crate::parser::IncludeFileHandler::resolve_target
2124    #[must_use]
2125    pub fn with_primary_file_name<S: AsRef<str>>(mut self, name: S) -> Self {
2126        self.primary_file_name = Some(name.as_ref().to_owned());
2127        self
2128    }
2129
2130    /// Sets the [`IncludeFileHandler`] for this parser.
2131    ///
2132    /// The include file handler is responsible for resolving `include::`
2133    /// directives encountered during preprocessing. If no handler is provided,
2134    /// include directives will be ignored.
2135    ///
2136    /// [`IncludeFileHandler`]: crate::parser::IncludeFileHandler
2137    #[must_use]
2138    pub fn with_include_file_handler<IFH: IncludeFileHandler + 'static>(
2139        mut self,
2140        handler: IFH,
2141    ) -> Self {
2142        self.include_file_handler = Some(Rc::new(handler));
2143        self
2144    }
2145
2146    /// Sets the [`DocinfoFileHandler`] for this parser.
2147    ///
2148    /// The docinfo file handler is responsible for providing the content of
2149    /// [docinfo files] requested while resolving a document's docinfo (see the
2150    /// `docinfo` attribute). If no handler is provided, no docinfo content is
2151    /// resolved and [`Document::docinfo`] returns an empty string for every
2152    /// location.
2153    ///
2154    /// [`DocinfoFileHandler`]: crate::parser::DocinfoFileHandler
2155    /// [docinfo files]: https://docs.asciidoctor.org/asciidoc/latest/docinfo/
2156    /// [`Document::docinfo`]: crate::Document::docinfo
2157    #[must_use]
2158    pub fn with_docinfo_file_handler<DFH: DocinfoFileHandler + 'static>(
2159        mut self,
2160        handler: DFH,
2161    ) -> Self {
2162        self.docinfo_file_handler = Some(Rc::new(handler));
2163        self
2164    }
2165
2166    /// Sets the [`SvgFileHandler`] for this parser.
2167    ///
2168    /// The SVG file handler is responsible for providing the raw contents of an
2169    /// SVG file requested by an inline image with the `inline` option (e.g.
2170    /// `image:diagram.svg[opts=inline]`). If no handler is provided, inline SVG
2171    /// images fall back to rendering their alt text.
2172    ///
2173    /// [`SvgFileHandler`]: crate::parser::SvgFileHandler
2174    #[must_use]
2175    pub fn with_svg_file_handler<SFH: SvgFileHandler + 'static>(mut self, handler: SFH) -> Self {
2176        self.svg_file_handler = Some(Rc::new(handler));
2177        self
2178    }
2179
2180    /// Sets the [`ImageFileHandler`] for this parser.
2181    ///
2182    /// The image file handler is responsible for providing the raw bytes of an
2183    /// image that must be embedded as a `data:` URI – i.e. when the `data-uri`
2184    /// document attribute is set and the safe mode is below
2185    /// [`SafeMode::Secure`]. If no handler is provided (or it cannot find the
2186    /// file), such images fall back to an ordinary web path, exactly as if
2187    /// `data-uri` were not set.
2188    ///
2189    /// [`ImageFileHandler`]: crate::parser::ImageFileHandler
2190    #[must_use]
2191    pub fn with_image_file_handler<IFH: ImageFileHandler + 'static>(
2192        mut self,
2193        handler: IFH,
2194    ) -> Self {
2195        self.image_file_handler = Some(Rc::new(handler));
2196        self
2197    }
2198
2199    /// Sets the [`PathResolver`] for this parser.
2200    ///
2201    /// The path resolver turns an asset target (an image `src`, a stylesheet
2202    /// href, and so on) into the clean, resolved path that appears in the
2203    /// rendered output. The default is [`DefaultPathResolver`], which mirrors
2204    /// Ruby Asciidoctor. A host that needs custom path or URL rewriting – a
2205    /// virtual filesystem, a content root, URL slugs – can supply its own
2206    /// implementation here.
2207    ///
2208    /// [`PathResolver`]: crate::parser::PathResolver
2209    /// [`DefaultPathResolver`]: crate::parser::DefaultPathResolver
2210    #[must_use]
2211    pub fn with_path_resolver<PR: PathResolver + 'static>(mut self, path_resolver: PR) -> Self {
2212        self.path_resolver = Rc::new(path_resolver);
2213        self
2214    }
2215
2216    /// Enables or disables cataloging of referenced image assets.
2217    ///
2218    /// When enabled (Asciidoctor's `catalog_assets` API option), each image
2219    /// referenced by an `image:`/`image::` macro is recorded in the document
2220    /// catalog and can be retrieved afterward via
2221    /// [`Catalog::images`](crate::document::Catalog::images). The default is
2222    /// disabled, in which case no image references are recorded.
2223    #[must_use]
2224    pub fn with_catalog_assets(mut self, catalog_assets: bool) -> Self {
2225        self.catalog_assets = catalog_assets;
2226        self
2227    }
2228
2229    /// Sets the [`SafeMode`] under which the document is parsed and rendered.
2230    ///
2231    /// The default is [`SafeMode::Secure`], the most conservative setting.
2232    /// Relaxing the safe mode enables security-sensitive rendering behavior,
2233    /// such as rendering an interactive SVG image as an `<object>` element.
2234    ///
2235    /// [`SafeMode`]: crate::SafeMode
2236    #[must_use]
2237    pub fn with_safe_mode(mut self, safe: SafeMode) -> Self {
2238        self.safe = safe;
2239        self.apply_safe_mode_attributes();
2240
2241        self.capture_attribute_baseline();
2242
2243        self
2244    }
2245
2246    /// Overrides the `safe-mode-*` family of [intrinsic attributes] from the
2247    /// current safe mode.
2248    ///
2249    /// These attributes let a document (or a downstream converter) inspect the
2250    /// security mode under which it is being processed:
2251    ///
2252    /// * `safe-mode-level` – the numeric level (`0`, `1`, `10`, or `20`).
2253    /// * `safe-mode-name` – the lowercase mode name (`unsafe`, `safe`,
2254    ///   `server`, or `secure`).
2255    /// * `safe-mode-<name>` – a single flag attribute (set to an empty value)
2256    ///   naming the active mode; the flags for the other modes are absent so
2257    ///   that a reference to them resolves literally.
2258    ///
2259    /// Only `safe-mode-level` and `safe-mode-name` are stored here (shadowing
2260    /// their built-in Secure-mode defaults). The active `safe-mode-<name>` flag
2261    /// is synthesized on the fly from `safe-mode-name` (see
2262    /// [`synthesized_attr`]), so exactly one flag is ever defined and the
2263    /// inactive flags stay absent without any per-mode bookkeeping here.
2264    ///
2265    /// All of these are read-only from the document's perspective (they can
2266    /// only be established via the API), matching Ruby Asciidoctor.
2267    ///
2268    /// [intrinsic attributes]: https://docs.asciidoctor.org/asciidoc/latest/attributes/document-attributes-ref/#intrinsic-attributes
2269    fn apply_safe_mode_attributes(&mut self) {
2270        let intrinsic = |value: InterpretedValue| AttributeValue {
2271            allowable_value: AllowableValue::Any,
2272            modification_context: ModificationContext::ApiOnly,
2273            silent_when_locked: false,
2274            value,
2275        };
2276
2277        let attrs = Arc::make_mut(&mut self.attribute_values);
2278        attrs.insert(
2279            "safe-mode-level".to_string(),
2280            intrinsic(InterpretedValue::Value(self.safe.level().to_string())),
2281        );
2282        attrs.insert(
2283            "safe-mode-name".to_string(),
2284            intrinsic(InterpretedValue::Value(self.safe.name().to_string())),
2285        );
2286
2287        // NOTE: `max-attribute-value-size` is deliberately *not* touched here.
2288        // Its Secure-only default is resolved as a mode-aware synthesized
2289        // attribute in [`effective_attribute`](Self::effective_attribute), so a
2290        // caller's explicit limit (which lives in `attribute_values`) is never
2291        // clobbered by a safe-mode change, whatever the builder-call order.
2292    }
2293
2294    /// Returns the [`SafeMode`] under which this parser operates.
2295    ///
2296    /// [`SafeMode`]: crate::SafeMode
2297    pub fn safe_mode(&self) -> SafeMode {
2298        self.safe
2299    }
2300
2301    /// Returns the [`ImageFileHandler`] registered on this parser, if any.
2302    ///
2303    /// A custom [`InlineSubstitutionRenderer`] that resolves image URIs itself
2304    /// (rather than inheriting [`image_uri`]'s default `data-uri` embedding)
2305    /// can use this to read an image's bytes through the same handler the
2306    /// built-in HTML renderer uses. Returns `None` when no handler was
2307    /// registered via [`with_image_file_handler`], in which case there is
2308    /// no way to embed images and a web path should be used instead.
2309    ///
2310    /// [`ImageFileHandler`]: crate::parser::ImageFileHandler
2311    /// [`InlineSubstitutionRenderer`]: crate::parser::InlineSubstitutionRenderer
2312    /// [`image_uri`]: crate::parser::InlineSubstitutionRenderer::image_uri
2313    /// [`with_image_file_handler`]: Self::with_image_file_handler
2314    pub fn image_file_handler(&self) -> Option<&dyn ImageFileHandler> {
2315        self.image_file_handler.as_deref()
2316    }
2317
2318    /// Returns the [`SvgFileHandler`] registered on this parser, if any.
2319    ///
2320    /// A custom [`InlineSubstitutionRenderer`] that renders inline SVG images
2321    /// itself (rather than inheriting [`render_image`]'s `opts=inline`
2322    /// handling) can use this to read an SVG's contents through the same
2323    /// handler the built-in HTML renderer uses. Returns `None` when no
2324    /// handler was registered via [`with_svg_file_handler`], in which case
2325    /// inline SVG contents are unavailable and the alt text should be used
2326    /// instead.
2327    ///
2328    /// [`SvgFileHandler`]: crate::parser::SvgFileHandler
2329    /// [`InlineSubstitutionRenderer`]: crate::parser::InlineSubstitutionRenderer
2330    /// [`render_image`]: crate::parser::InlineSubstitutionRenderer::render_image
2331    /// [`with_svg_file_handler`]: Self::with_svg_file_handler
2332    pub fn svg_file_handler(&self) -> Option<&dyn SvgFileHandler> {
2333        self.svg_file_handler.as_deref()
2334    }
2335
2336    /// Returns the document name (`docname`): the base name of the primary
2337    /// file, stripped of its directory and final extension.
2338    ///
2339    /// This is the `<docname>` used to build private docinfo file names (e.g.
2340    /// `mydoc-docinfo.html` for `mydoc.adoc`). Returns `None` when no primary
2341    /// file name has been set, in which case private docinfo files cannot be
2342    /// resolved.
2343    pub(crate) fn docname(&self) -> Option<String> {
2344        let primary = self.primary_file_name.as_deref()?;
2345
2346        // Strip the directory portion (handling both separators, since the
2347        // primary file name may have been supplied on either platform).
2348        let base = primary.rsplit(['/', '\\']).next().unwrap_or(primary);
2349
2350        // Strip a single trailing extension, if present. A leading-dot name
2351        // (e.g. `.adoc`) is treated as having no extension and is kept whole as
2352        // the stem, matching Ruby's `File.basename(".adoc", ".*")`.
2353        let stem = match base.rfind('.') {
2354            Some(0) | None => base,
2355            Some(idx) => &base[..idx],
2356        };
2357
2358        if stem.is_empty() {
2359            None
2360        } else {
2361            Some(stem.to_string())
2362        }
2363    }
2364
2365    /// Returns `true` if the AsciiDoc file named by `key` (an inter-document
2366    /// xref path – relative to this document, AsciiDoc extension removed) was
2367    /// included into this document *in full* by the preprocessor.
2368    ///
2369    /// A cross reference to such a file collapses to a same-document reference,
2370    /// since the file's anchors are now part of this document. Takes `&self` so
2371    /// it can be called from an inline-substitution
2372    /// [`Replacer`](regex::Replacer) that holds only a shared reference to
2373    /// the parser. See
2374    /// [`Catalog::include_is_full`](crate::document::Catalog::include_is_full).
2375    pub(crate) fn catalog_include_is_full(&self, key: &str) -> bool {
2376        self.catalog.borrow().include_is_full(key)
2377    }
2378
2379    /// Records an included AsciiDoc file in the document catalog's include
2380    /// registry, mid-parse.
2381    ///
2382    /// `Parser::parse_deferred` seeds the registry with the outermost
2383    /// document's own includes before parsing begins; this entry point is for
2384    /// an include performed while a nested scope with a shared catalog – an
2385    /// AsciiDoc table cell – is parsed. Takes `&self` for the same reason as
2386    /// [`catalog_include_is_full`](Self::catalog_include_is_full). See
2387    /// [`Catalog::register_include`](crate::document::Catalog::register_include).
2388    pub(crate) fn register_include(&self, key: &str, full: bool) {
2389        self.catalog.borrow_mut().register_include(key, full);
2390    }
2391
2392    /// Called from [`Header::parse()`] to accept or reject an attribute value.
2393    ///
2394    /// [`Header::parse()`]: crate::document::Header::parse
2395    pub(crate) fn set_attribute_from_header<'src>(
2396        &mut self,
2397        attr: &Attribute<'src>,
2398        warnings: &mut Vec<Warning<'src>>,
2399    ) {
2400        let attr_name = remap_attr_name(attr.name().data());
2401
2402        // The derived backend-family namespace is a read-only synthesized
2403        // intrinsic; a document must not write any of it (see
2404        // [`is_reserved_derived_attr`]).
2405        if is_reserved_derived_attr(&attr_name) {
2406            return;
2407        }
2408
2409        // Verify that we have permission to overwrite any existing attribute
2410        // value, considering both a per-parser entry and the shared built-in
2411        // default it would shadow (a built-in such as `sp` is `ApiOnly`).
2412        if let Some(existing_attr) = self.effective_attribute(&attr_name)
2413            && (existing_attr.modification_context == ModificationContext::ApiOnly
2414                || existing_attr.modification_context == ModificationContext::ApiOrDocumentBody)
2415        {
2416            // A silently-locked intrinsic rejects the write without recording a
2417            // warning (see `AttributeValue::silent_when_locked`).
2418            if !existing_attr.silent_when_locked {
2419                warnings.push(Warning::new(
2420                    attr.span(),
2421                    WarningType::AttributeValueIsLocked(attr_name),
2422                ));
2423            }
2424            return;
2425        }
2426
2427        let mut value = attr.value().clone();
2428
2429        if let InterpretedValue::Set = value
2430            && let Some(default_value) = self.default_attribute_values.get(&attr_name)
2431        {
2432            value = InterpretedValue::Value(default_value.clone());
2433        }
2434
2435        // A relative `leveloffset` (`+N` / `-N`) accumulates on top of the
2436        // offset already in effect; resolve it to an absolute value so the
2437        // stored attribute is always a plain integer, and warn if the result is
2438        // so extreme that no heading could ever land in the valid level range.
2439        if attr_name == "leveloffset" {
2440            value = self.resolve_leveloffset_and_warn(value, attr.span(), warnings);
2441        }
2442
2443        // Cap the resolved value at `max-attribute-value-size` bytes (a no-op
2444        // unless that limit is in force – by default, only under Secure).
2445        value = self.limit_attribute_value_size(value);
2446
2447        // `notitle` and `showtitle` are inverse spellings of one title-
2448        // visibility toggle; keep the partner in sync (see
2449        // [`apply_title_visibility_linkage`](Self::apply_title_visibility_linkage)).
2450        self.apply_title_visibility_linkage(
2451            &attr_name,
2452            &value,
2453            ModificationContext::Anywhere,
2454            false,
2455        );
2456
2457        let attribute_value = AttributeValue {
2458            allowable_value: AllowableValue::Any,
2459            modification_context: ModificationContext::Anywhere,
2460            silent_when_locked: false,
2461            value,
2462        };
2463
2464        // An explicit assignment supersedes (and resets) any counter of the same
2465        // name.
2466        self.counter_values.borrow_mut().remove(&attr_name);
2467
2468        // The derived `backend-html5-doctype-*` attribute tracks `doctype`
2469        // automatically (it is synthesized on lookup), so no refresh is needed.
2470        Arc::make_mut(&mut self.attribute_values).insert(attr_name, attribute_value);
2471    }
2472
2473    /// Called from [`Header::parse()`] for a value that is derived from parsing
2474    /// the header (except for attribute lines).
2475    ///
2476    /// [`Header::parse()`]: crate::document::Header::parse
2477    pub(crate) fn set_attribute_by_value_from_header<N: AsRef<str>, V: AsRef<str>>(
2478        &mut self,
2479        name: N,
2480        value: V,
2481    ) {
2482        let attr_name = remap_attr_name(name);
2483
2484        let attribute_value = AttributeValue {
2485            allowable_value: AllowableValue::Any,
2486            modification_context: ModificationContext::Anywhere,
2487            silent_when_locked: false,
2488            value: InterpretedValue::Value(value.as_ref().to_owned()),
2489        };
2490
2491        self.counter_values.borrow_mut().remove(&attr_name);
2492        Arc::make_mut(&mut self.attribute_values).insert(attr_name, attribute_value);
2493    }
2494
2495    /// Applies the `imagesdir`-relative default for the `iconsdir` attribute.
2496    ///
2497    /// The `iconsdir` attribute defaults to `{imagesdir}/icons`; when
2498    /// `imagesdir` is left empty this resolves to the built-in
2499    /// [`DEFAULT_ICONSDIR`] (`./images/icons`). When `imagesdir` is set to a
2500    /// non-empty value and `iconsdir` was left at its built-in default, the
2501    /// icons directory is derived as `{imagesdir}/icons`.
2502    ///
2503    /// The derivation is skipped – so an explicit `iconsdir` wins – when either
2504    /// the attribute was set in the header (`iconsdir_set_in_header`) or its
2505    /// resolved value differs from [`DEFAULT_ICONSDIR`] (which is how an
2506    /// override applied any other way, e.g. via the API, is detected). The one
2507    /// case this cannot detect is a non-header override whose value happens to
2508    /// equal the built-in default (e.g. an API caller setting `iconsdir` to
2509    /// exactly `./images/icons`): it is indistinguishable from the default and
2510    /// so is re-derived. That combination is contradictory in practice (it
2511    /// pins `iconsdir` to the value it would take were `imagesdir` unset) and
2512    /// is not worth a dedicated provenance flag.
2513    ///
2514    /// This is called once, after the document header is parsed, mirroring
2515    /// Asciidoctor's document-initialization timing (a later `imagesdir` change
2516    /// in the document body does not retroactively re-derive `iconsdir`). See
2517    /// icons-image.adoc.
2518    ///
2519    /// [`DEFAULT_ICONSDIR`]: super::built_in_attrs::DEFAULT_ICONSDIR
2520    pub(crate) fn apply_iconsdir_default(&mut self, iconsdir_set_in_header: bool) {
2521        if iconsdir_set_in_header {
2522            return;
2523        }
2524
2525        // Preserve any override whose value differs from the built-in default
2526        // (e.g. one applied via the API); only the built-in default itself is
2527        // eligible for `imagesdir`-relative derivation. See the doc comment for
2528        // the one indistinguishable corner case.
2529        if self.attribute_value("iconsdir").as_maybe_str()
2530            != Some(super::built_in_attrs::DEFAULT_ICONSDIR)
2531        {
2532            return;
2533        }
2534
2535        let imagesdir = self.attribute_value("imagesdir");
2536        let derived = match imagesdir.as_maybe_str().filter(|d| !d.is_empty()) {
2537            Some(dir) => format!("{}/icons", dir.trim_end_matches('/')),
2538            None => return,
2539        };
2540
2541        self.set_attribute_by_value_from_header("iconsdir", derived);
2542    }
2543
2544    /// Called while parsing a block (see [`Block::parse_with_outcome()`]) to
2545    /// accept or reject an attribute value from a document (body) attribute.
2546    ///
2547    /// [`Block::parse_with_outcome()`]: crate::blocks::Block::parse_with_outcome
2548    pub(crate) fn set_attribute_from_body<'src>(
2549        &mut self,
2550        attr: &Attribute<'src>,
2551        warnings: &mut Vec<Warning<'src>>,
2552    ) {
2553        let attr_name = remap_attr_name(attr.name().data());
2554
2555        // The derived backend-family namespace is a read-only synthesized
2556        // intrinsic; a document must not write any of it (see
2557        // [`is_reserved_derived_attr`]).
2558        if is_reserved_derived_attr(&attr_name) {
2559            return;
2560        }
2561
2562        // An attribute inherited from the parent document of an AsciiDoc table
2563        // cell is locked for the duration of that cell: a body assignment to it
2564        // is silently ignored (no warning), matching Asciidoctor.
2565        if self.locked_attribute_names.contains(attr_name.as_str()) {
2566            return;
2567        }
2568
2569        // Verify that we have permission to overwrite any existing attribute
2570        // value, considering both a per-parser entry and the shared built-in
2571        // default it would shadow.
2572        if let Some(existing_attr) = self.effective_attribute(&attr_name)
2573            && (existing_attr.modification_context != ModificationContext::Anywhere
2574                && existing_attr.modification_context != ModificationContext::ApiOrDocumentBody)
2575        {
2576            // A silently-locked intrinsic rejects the write without recording a
2577            // warning (see `AttributeValue::silent_when_locked`).
2578            if !existing_attr.silent_when_locked {
2579                warnings.push(Warning::new(
2580                    attr.span(),
2581                    WarningType::AttributeValueIsLocked(attr_name),
2582                ));
2583            }
2584            return;
2585        }
2586
2587        let mut value = attr.value().clone();
2588
2589        // A relative `leveloffset` (`+N` / `-N`) accumulates on top of the
2590        // offset already in effect; resolve it to an absolute value so the
2591        // stored attribute is always a plain integer, and warn if the result is
2592        // so extreme that no heading could ever land in the valid level range.
2593        if attr_name == "leveloffset" {
2594            value = self.resolve_leveloffset_and_warn(value, attr.span(), warnings);
2595        }
2596
2597        // Cap the resolved value at `max-attribute-value-size` bytes (a no-op
2598        // unless that limit is in force – by default, only under Secure).
2599        value = self.limit_attribute_value_size(value);
2600
2601        // `notitle` and `showtitle` are inverse spellings of one title-
2602        // visibility toggle; keep the partner in sync (see
2603        // [`apply_title_visibility_linkage`](Self::apply_title_visibility_linkage)).
2604        self.apply_title_visibility_linkage(
2605            &attr_name,
2606            &value,
2607            ModificationContext::Anywhere,
2608            false,
2609        );
2610
2611        let attribute_value = AttributeValue {
2612            allowable_value: AllowableValue::Any,
2613            modification_context: ModificationContext::Anywhere,
2614            silent_when_locked: false,
2615            value,
2616        };
2617
2618        // An explicit assignment supersedes (and resets) any counter of the same
2619        // name. This is what lets `:!name:` reset a counter.
2620        self.counter_values.borrow_mut().remove(&attr_name);
2621
2622        // The derived `backend-html5-doctype-*` attribute tracks `doctype`
2623        // automatically (it is synthesized on lookup), so no refresh is needed.
2624        Arc::make_mut(&mut self.attribute_values).insert(attr_name, attribute_value);
2625    }
2626
2627    /// Unlocks each *flexible* document attribute ([`FLEXIBLE_ATTRIBUTES`],
2628    /// currently just `sectnums`) that was supplied *set* through the API, so a
2629    /// later document-body assignment may still toggle it.
2630    ///
2631    /// Mirrors the flexible-attribute unfreeze at the end of Asciidoctor's
2632    /// `save_attributes` (run by `finalize_header`, after the header is parsed
2633    /// and before the body): an API attribute override whose value is *truthy*
2634    /// is dropped from the locked overrides, while one whose value is an
2635    /// [unset] (from `numbered!` / `sectnums!`) is kept locked. That asymmetry
2636    /// is exactly what lets an API-*enabled* `numbered` still be toggled off by
2637    /// a body `:numbered!:`, while an API-*disabled* `numbered!` stays
2638    /// permanently unnumbered even across a later `:numbered:`.
2639    ///
2640    /// Called once, for the top-level document only – Asciidoctor guards the
2641    /// unfreeze with `unless @parent_document`, and an AsciiDoc table cell
2642    /// never reaches this path. This must *not* recapture the attribute
2643    /// baseline: the unlock is a per-parse effect, so a `Parser` reused across
2644    /// documents re-derives it from the still-locked API override each time.
2645    ///
2646    /// [unset]: https://docs.asciidoctor.org/asciidoc/latest/attributes/unset-attributes/
2647    pub(crate) fn unlock_flexible_attributes(&mut self) {
2648        for name in FLEXIBLE_ATTRIBUTES {
2649            // Only an API-set (`ApiOnly`, i.e. locked) override with a value
2650            // that is not an explicit unset is unfrozen; everything else is
2651            // left exactly as it stands.
2652            if let Some(existing) = self.attribute_values.get(name)
2653                && existing.modification_context == ModificationContext::ApiOnly
2654                && existing.value != InterpretedValue::Unset
2655            {
2656                let unlocked = AttributeValue {
2657                    modification_context: ModificationContext::Anywhere,
2658                    silent_when_locked: false,
2659                    ..existing.clone()
2660                };
2661
2662                Arc::make_mut(&mut self.attribute_values).insert(name.to_string(), unlocked);
2663            }
2664        }
2665    }
2666
2667    /// Assign the next section number for a given level.
2668    pub(crate) fn assign_section_number(&mut self, level: usize) -> SectionNumber {
2669        match self.topmost_section_type {
2670            SectionType::Appendix => {
2671                self.last_appendix_section_number.assign_next_number(level);
2672                self.last_appendix_section_number.clone()
2673            }
2674
2675            // `topmost_section_type` is only ever `Normal` or `Appendix`: a
2676            // discrete heading never becomes the topmost section type (see
2677            // `SectionBlock::parse`). `Discrete` therefore cannot reach this
2678            // point, so it is folded in with `Normal` rather than carried as a
2679            // separate, untestable arm.
2680            SectionType::Normal | SectionType::Discrete => {
2681                self.last_section_number.assign_next_number(level);
2682                self.last_section_number.clone()
2683            }
2684        }
2685    }
2686
2687    /// Resolves a [counter] of the given `name`, advancing it to the next value
2688    /// in its sequence and returning that value.
2689    ///
2690    /// A counter is a specialized document attribute: its value is stored as
2691    /// (and read back from) the attribute of the same name, so a later
2692    /// `{name}` reference shows the current value and an attribute assignment
2693    /// such as `:!name:` resets it. Each resolution advances the counter:
2694    ///
2695    /// * an integer value is incremented (`1` -> `2`);
2696    /// * any other value is advanced like Ruby's `String#succ` (`a` -> `b`, `z`
2697    ///   -> `aa`, `Az` -> `Ba`), matching Asciidoctor.
2698    ///
2699    /// `seed` (from the `{counter:name:seed}` form) supplies the first value,
2700    /// but only when the counter is currently unset; otherwise it is ignored.
2701    /// With no seed the sequence starts at `1`.
2702    ///
2703    /// This mirrors Asciidoctor's `Document#counter`.
2704    ///
2705    /// [counter]: https://docs.asciidoctor.org/asciidoc/latest/attributes/counters/
2706    pub(crate) fn counter(&self, name: &str, seed: Option<&str>) -> String {
2707        self.counter_impl(name, seed, false)
2708    }
2709
2710    /// Like [`counter`](Self::counter), but the advanced value stays readable
2711    /// as the attribute of the same name even when that attribute is
2712    /// *locked* (API-set or a locked built-in). This is the captioning
2713    /// counter, used for the `<context>-number` of a numbered block.
2714    ///
2715    /// Mirrors Asciidoctor's `increment_and_store_counter`: it too advances a
2716    /// locked counter, and its block attribute entry is replayed onto the
2717    /// document attributes during conversion, so a locked `example-number`
2718    /// reads back as its latest counter value (unlike a plain inline
2719    /// `{counter:…}`, which leaves the locked value in place).
2720    pub(crate) fn counter_for_caption(&self, name: &str, seed: Option<&str>) -> String {
2721        self.counter_impl(name, seed, true)
2722    }
2723
2724    /// Advances the `name` counter and returns its new value. `seed` supplies
2725    /// the starting value when the counter has no current value to advance
2726    /// from.
2727    ///
2728    /// A counter reads the current value to produce (and display) the next one.
2729    /// For an unlocked attribute the advanced value is stored in the readable
2730    /// [`counter_values`](Self::counter_values) overlay, so a later reference
2731    /// reads it. For a *locked* attribute – one set via the API, or a locked
2732    /// built-in such as `max-include-depth` – the write path depends on the
2733    /// caller:
2734    ///
2735    /// * `commit_when_locked` (the captioning counter): the value is stored in
2736    ///   the readable overlay anyway, matching Asciidoctor's
2737    ///   `increment_and_store_counter`, whose block attribute entry is replayed
2738    ///   onto the document attributes during conversion.
2739    /// * otherwise (an inline `{counter:…}` / `{counter2:…}` directive): the
2740    ///   running value is kept in the private
2741    ///   [`locked_counter_values`](Self::locked_counter_values) map instead, so
2742    ///   the sequence still advances across repeated references while a plain
2743    ///   reference to the attribute continues to read the locked value. This
2744    ///   mirrors Asciidoctor's `Document#counter`, which advances `@counters`
2745    ///   but leaves `@attributes` untouched while the attribute is
2746    ///   `attribute_locked?`.
2747    fn counter_impl(&self, name: &str, seed: Option<&str>, commit_when_locked: bool) -> String {
2748        let use_private_state = !commit_when_locked && self.attribute_is_locked(name);
2749
2750        // The value to advance from: the private running state first (only
2751        // populated when it is in use), otherwise the current readable value of
2752        // the attribute (which, for an unlocked counter, already reflects the
2753        // overlay).
2754        let current = if use_private_state {
2755            self.locked_counter_values.borrow().get(name).cloned()
2756        } else {
2757            None
2758        }
2759        .or_else(|| match self.attribute_value(name) {
2760            InterpretedValue::Value(current) if !current.is_empty() => Some(current),
2761            _ => None,
2762        });
2763
2764        let next = match current {
2765            Some(current) => next_counter_value(&current),
2766            None => match seed {
2767                Some(seed) if !seed.is_empty() => seed.to_string(),
2768                _ => "1".to_string(),
2769            },
2770        };
2771
2772        if use_private_state {
2773            self.locked_counter_values
2774                .borrow_mut()
2775                .insert(name.to_string(), next.clone());
2776        } else {
2777            self.counter_values
2778                .borrow_mut()
2779                .insert(name.to_string(), next.clone());
2780        }
2781
2782        next
2783    }
2784
2785    /// Reports whether `name` currently resolves to an attribute that is
2786    /// *locked* against modification by a counter: it has an effective value
2787    /// whose [`ModificationContext`] is
2788    /// [`ApiOnly`](ModificationContext::ApiOnly) – an API-set override or a
2789    /// locked built-in such as `max-include-depth`.
2790    ///
2791    /// This mirrors Asciidoctor's `Document#attribute_locked?`, which is `true`
2792    /// exactly for an attribute supplied through the API (its
2793    /// `@attribute_overrides`). It is deliberately *narrower* than the
2794    /// write-permission check in
2795    /// [`set_attribute_from_body`](Self::set_attribute_from_body): a
2796    /// header-only attribute such as an unset `outfilesuffix`
2797    /// ([`ApiOrHeader`](ModificationContext::ApiOrHeader)) cannot be assigned
2798    /// from the body, yet a counter *may* advance it (matching Asciidoctor,
2799    /// where `{counter:outfilesuffix}` moves it while it is not API-locked).
2800    fn attribute_is_locked(&self, name: &str) -> bool {
2801        self.effective_attribute(name)
2802            .is_some_and(|a| a.modification_context == ModificationContext::ApiOnly)
2803    }
2804}
2805
2806/// Whether a `leveloffset` of `offset` leaves at least one syntactic heading
2807/// level able to land inside the supported section-level range.
2808///
2809/// Syntactic heading levels run 0 (`=`) through 5 (`======`) and valid section
2810/// levels run 1 through 5, so an offset keeps some heading in range only while
2811/// it stays within `1 - 5 ..= 5 - 0`, i.e. `-4..=5`. Outside that window every
2812/// heading is clamped, so the offset can never place a heading at its intended
2813/// level.
2814fn leveloffset_admits_any_heading(offset: i32) -> bool {
2815    (-4..=5).contains(&offset)
2816}
2817
2818/// Advances a counter value to the next value in its sequence, mirroring
2819/// Asciidoctor's `Helpers.nextval`.
2820///
2821/// A canonical integer string (one that round-trips through integer parsing,
2822/// e.g. `7` but not `07` or `+7`) is incremented numerically. Anything else is
2823/// advanced with [`string_succ`].
2824fn next_counter_value(current: &str) -> String {
2825    if let Ok(n) = current.parse::<i64>()
2826        && n.to_string() == current
2827    {
2828        // `saturating_add` keeps a counter that has somehow reached `i64::MAX`
2829        // pinned there rather than panicking (debug) or wrapping (release).
2830        return n.saturating_add(1).to_string();
2831    }
2832
2833    string_succ(current)
2834}
2835
2836/// Returns the successor of a string, mirroring Ruby's `String#succ` for the
2837/// ASCII cases that AsciiDoc counters can produce.
2838///
2839/// The right-most alphanumeric character is incremented within its own class
2840/// (digits, lowercase letters, uppercase letters), carrying leftward on
2841/// wrap-around (`9` -> `0`, `z` -> `a`, `Z` -> `A`) and prepending a fresh
2842/// leading character (`1`, `a`, or `A`) when the carry runs off the front
2843/// (`z` -> `aa`, `Zz` -> `AAa`). A string with no alphanumeric characters has
2844/// the code point of its last character incremented.
2845fn string_succ(current: &str) -> String {
2846    let chars: Vec<char> = current.chars().collect();
2847
2848    // Without an alphanumeric to carry through, Ruby increments the code point
2849    // of the final character.
2850    if !chars.iter().any(char::is_ascii_alphanumeric) {
2851        let mut chars = chars;
2852        if let Some(last) = chars.last_mut() {
2853            *last = char::from_u32(*last as u32 + 1).unwrap_or(*last);
2854        }
2855        return chars.into_iter().collect();
2856    }
2857
2858    // Walk right to left. `carrying` stays true while we are still looking for
2859    // (or carrying through) the alphanumeric run: trailing non-alphanumeric
2860    // characters are passed over unchanged, then the right-most alphanumeric is
2861    // incremented within its class and any wrap-around carries leftward to the
2862    // next alphanumeric. When the carry runs off the front, a fresh leading
2863    // character of the same class is prepended (`z` -> `aa`, `9` -> `10`).
2864    let mut out_rev: Vec<char> = Vec::with_capacity(chars.len() + 1);
2865    let mut carrying = true;
2866    let mut lead = '1';
2867
2868    for &c in chars.iter().rev() {
2869        if carrying && c.is_ascii_alphanumeric() {
2870            // Increment within the character's class, carrying on wrap-around.
2871            // The arms are exhaustive over ASCII alphanumerics, so the catch-all
2872            // can only be `Z` (the one value not matched above).
2873            let (next, carry) = match c {
2874                '0'..='8' | 'a'..='y' | 'A'..='Y' => ((c as u8 + 1) as char, false),
2875                '9' => ('0', true),
2876                'z' => ('a', true),
2877                _ => ('A', true),
2878            };
2879            out_rev.push(next);
2880            carrying = carry;
2881
2882            // On a carry, remember the class of leading character to prepend if
2883            // the carry runs off the front; `next` is `0`, `a`, or `A` here.
2884            lead = match next {
2885                '0' => '1',
2886                'a' => 'a',
2887                _ => 'A',
2888            };
2889        } else {
2890            // Either the carry is spent, or this is a trailing non-alphanumeric
2891            // we pass over while still searching for the run to increment.
2892            out_rev.push(c);
2893        }
2894    }
2895
2896    if carrying {
2897        out_rev.push(lead);
2898    }
2899
2900    out_rev.into_iter().rev().collect()
2901}
2902
2903/// Matches every character that Asciidoctor's `sanitize_attribute_name` strips
2904/// from an attribute name: anything that is not a [word character] (`\w`, i.e.
2905/// `\p{Word}`) or a hyphen. Mirrors Asciidoctor's `InvalidAttributeNameCharsRx`
2906/// (`/[^#{CC_WORD}-]/`).
2907///
2908/// [word character]: crate::internal::is_word_char
2909static INVALID_ATTR_NAME_CHARS: LazyLock<Regex> = LazyLock::new(|| {
2910    #[allow(clippy::unwrap_used)]
2911    Regex::new(r"[^\w-]").unwrap()
2912});
2913
2914fn remap_attr_name<N: AsRef<str>>(raw_attr_name: N) -> String {
2915    // Sanitize the name the way Asciidoctor's `sanitize_attribute_name` does:
2916    // drop every character that is not a word character or a hyphen, then
2917    // lower-case the result. This is what lets an attribute entry written as
2918    // `:Author Initials:` set the `authorinitials` attribute, `:Foo 3^ # -
2919    // Bar[:` set `foo3-bar`, and `:My frog:` set `myfrog`. Unicode word
2920    // characters are preserved, so `:café:` sets `café` and `:سمن:` sets `سمن`.
2921    //
2922    // The full Unicode case fold (Asciidoctor's `downcase`, not merely ASCII)
2923    // is what makes an attribute reference case-insensitive: an entry written
2924    // `:He-Man:` is reachable as `{he-man}` or `{HE-MAN}`. A reference is folded
2925    // through this same `to_lowercase()` before lookup (see `AttributeReplacer`
2926    // in `content::substitution_step`), so definition and reference stay
2927    // symmetric even when a fold expands a character (e.g. `İ` -> `i` + combining
2928    // dot): both sides land on the identical key.
2929    let attr_name: String = INVALID_ATTR_NAME_CHARS
2930        .replace_all(raw_attr_name.as_ref(), "")
2931        .to_lowercase();
2932
2933    // Some attribute names have aliases. Remap to the primary name.
2934    alias_attr_name(attr_name)
2935}
2936
2937/// Document attributes that are *flexible*: an API-supplied *set* value is
2938/// unlocked once the header is parsed so the document body may still toggle it,
2939/// while an API-supplied [unset] stays locked (see
2940/// [`unlock_flexible_attributes`](Parser::unlock_flexible_attributes)). Mirrors
2941/// Asciidoctor's `FLEXIBLE_ATTRIBUTES` constant, currently just `sectnums` (the
2942/// primary name of the `numbered` alias).
2943///
2944/// [unset]: https://docs.asciidoctor.org/asciidoc/latest/attributes/unset-attributes/
2945const FLEXIBLE_ATTRIBUTES: [&str; 1] = ["sectnums"];
2946
2947/// Remaps an attribute name that is a legacy alias to its primary name,
2948/// returning any other name unchanged.
2949///
2950/// `numbered` is a legacy alias for `sectnums`, and `hardbreaks` for
2951/// `hardbreaks-option`, so setting `numbered` sets `sectnums` (and `numbered!`
2952/// unsets it), and setting `hardbreaks` sets `hardbreaks-option`. Mirrors both
2953/// Asciidoctor's `Parser.store_attribute` (which renames a header/body
2954/// attribute entry before storing it) and its `Document#initialize` (which
2955/// renames the same two API-supplied attribute overrides: `attr_overrides`
2956/// `sectnums`/`hardbreaks-option` reassignment). Applying it on both paths is
2957/// what lets `-a hardbreaks` supplied through the API enable hard line breaks,
2958/// exactly as `:hardbreaks:` in the header does.
2959fn alias_attr_name(attr_name: String) -> String {
2960    match attr_name.as_str() {
2961        "hardbreaks" => "hardbreaks-option".to_string(),
2962        "numbered" => "sectnums".to_string(),
2963        _ => attr_name,
2964    }
2965}
2966
2967/// Applies AsciiDoc's *soft-set* modifier to an intrinsic (API/CLI) attribute
2968/// value.
2969///
2970/// A single trailing `@` on an attribute value supplied via the API (or the
2971/// Asciidoctor CLI) marks the attribute as *soft set*: the effective value is
2972/// the string with the `@` removed, and the attribute becomes overridable by a
2973/// document `:name:` entry. That maps onto [`ModificationContext::Anywhere`].
2974///
2975/// When no trailing `@` is present the value and `modification_context` are
2976/// returned unchanged. Only one `@` is stripped, mirroring Ruby's `String#chop`
2977/// (so `foo@@` yields `foo@`), and a `@` that is not the final character (e.g.
2978/// `foo@bar`) is not a modifier and is left in place.
2979fn apply_soft_set_modifier(
2980    value: &str,
2981    modification_context: ModificationContext,
2982) -> (String, ModificationContext) {
2983    match value.strip_suffix('@') {
2984        Some(stripped) => (stripped.to_string(), ModificationContext::Anywhere),
2985        None => (value.to_string(), modification_context),
2986    }
2987}
2988
2989/// Returns `true` if `name` is a derived backend-family attribute whose
2990/// assignment must be rejected *even while it is inactive*, because the flag it
2991/// would name can become active later in the same parse and the stored override
2992/// would then shadow the read-only intrinsic:
2993///
2994/// * The bare derived values `basebackend` / `filetype` – always resolved on
2995///   the fly from `backend` (see [`derived_backend_value`]), never stored.
2996/// * The doctype-keyed flags `backend-<b>-doctype-<d>` /
2997///   `basebackend-<bb>-doctype-<d>` – the `doctype` component shifts mid-parse
2998///   (e.g. an AsciiDoc table cell that resets, then changes, its doctype), so
2999///   an assignment to an inactive one (`backend-html5-doctype-article` while
3000///   the doctype is `book`) must not be stored where it could shadow the
3001///   intrinsic once the doctype switches.
3002///
3003/// The remaining flag names (`backend-<b>`, `basebackend-<bb>`, `filetype-<f>`,
3004/// and bare `doctype-<d>`) are deliberately **not** reserved: rejecting them
3005/// would swallow author-defined attributes such as `:backend-custom:` or
3006/// `:doctype-draft:` (used as `ifdef` flags), which Asciidoctor keeps. The
3007/// *active* one of these is still write-protected by the normal permission
3008/// check, since [`synthesized_attr`] resolves it to a locked intrinsic.
3009fn is_reserved_derived_attr(name: &str) -> bool {
3010    is_derived_backend_value(name)
3011        || ((name.starts_with("backend-") || name.starts_with("basebackend-"))
3012            && name.contains("-doctype-"))
3013}
3014
3015#[cfg(test)]
3016mod tests {
3017    #![allow(clippy::panic)]
3018    #![allow(clippy::unwrap_used)]
3019
3020    use crate::{
3021        attributes::Attrlist,
3022        blocks::Block,
3023        parser::{
3024            CharacterReplacementType, IconRenderParams, ImageRenderParams,
3025            InlineSubstitutionRenderer, LinkRenderParams, QuoteScope, QuoteType, SpecialCharacter,
3026        },
3027        tests::prelude::*,
3028    };
3029
3030    #[test]
3031    fn default_is_unset() {
3032        let p = Parser::default();
3033        assert_eq!(p.attribute_value("foo"), InterpretedValue::Unset);
3034    }
3035
3036    #[test]
3037    fn new_matches_default() {
3038        // `Parser::new()` is a discoverability alias for `Parser::default()`.
3039        let p = Parser::new();
3040        assert_eq!(p.attribute_value("foo"), InterpretedValue::Unset);
3041        assert_eq!(p.safe_mode(), Parser::default().safe_mode());
3042    }
3043
3044    mod attribute_state_between_parses {
3045        use crate::tests::prelude::*;
3046
3047        #[test]
3048        fn discovered_header_attribute_does_not_leak() {
3049            let mut parser = Parser::default();
3050
3051            // The first document defines `foo`; it is inspectable on the parser
3052            // once that parse returns.
3053            let _ = parser.parse(":foo: bar\n\nText.\n");
3054            assert_eq!(
3055                parser.attribute_value("foo"),
3056                InterpretedValue::Value("bar")
3057            );
3058
3059            // A second document that never defines `foo` must not observe the
3060            // first document's assignment.
3061            let _ = parser.parse("Text.\n");
3062            assert_eq!(parser.attribute_value("foo"), InterpretedValue::Unset);
3063        }
3064
3065        #[test]
3066        fn discovered_body_attribute_does_not_leak() {
3067            let mut parser = Parser::default();
3068
3069            // A body (not header) assignment leaks the same way a header one
3070            // would if the baseline were not restored.
3071            let _ = parser.parse("First.\n\n:mode: fast\n\nSecond.\n");
3072            assert_eq!(
3073                parser.attribute_value("mode"),
3074                InterpretedValue::Value("fast")
3075            );
3076
3077            let _ = parser.parse("Text.\n");
3078            assert_eq!(parser.attribute_value("mode"), InterpretedValue::Unset);
3079        }
3080
3081        #[test]
3082        fn configured_baseline_is_restored_each_parse() {
3083            let mut parser = Parser::default().with_intrinsic_attribute(
3084                "site",
3085                "prod",
3086                ModificationContext::Anywhere,
3087            );
3088
3089            // The first document overrides the API-configured value in its body.
3090            let _ = parser.parse(":site: dev\n\nText.\n");
3091            assert_eq!(
3092                parser.attribute_value("site"),
3093                InterpretedValue::Value("dev")
3094            );
3095
3096            // The next parse begins from the configured baseline, not the
3097            // previous document's override.
3098            let _ = parser.parse("Text.\n");
3099            assert_eq!(
3100                parser.attribute_value("site"),
3101                InterpretedValue::Value("prod")
3102            );
3103        }
3104
3105        #[test]
3106        fn reconfiguring_between_parses_updates_baseline() {
3107            let mut parser = Parser::default();
3108
3109            let _ = parser.parse("Text.\n");
3110            assert_eq!(parser.attribute_value("env"), InterpretedValue::Unset);
3111
3112            // A builder call between parses re-establishes the baseline for every
3113            // subsequent parse.
3114            parser = parser.with_intrinsic_attribute("env", "ci", ModificationContext::Anywhere);
3115
3116            let _ = parser.parse("Text.\n");
3117            assert_eq!(parser.attribute_value("env"), InterpretedValue::Value("ci"));
3118        }
3119
3120        #[test]
3121        fn leaked_attribute_does_not_affect_rendered_output() {
3122            let mut parser = Parser::default();
3123
3124            // The first document defines `who`, so `{who}` resolves for it.
3125            let doc1 = parser.parse(":who: world\n\nHello {who}.\n");
3126            assert_eq!(rendered_paragraphs(&doc1), vec!["Hello world."]);
3127
3128            // The second document does not define `who`; without the baseline
3129            // restore, `{who}` would still resolve to "world". Instead it stays
3130            // an unresolved literal reference.
3131            let doc2 = parser.parse("Hello {who}.\n");
3132            assert_eq!(rendered_paragraphs(&doc2), vec!["Hello {who}."]);
3133        }
3134    }
3135
3136    mod leading_byte_order_mark {
3137        use crate::tests::prelude::*;
3138
3139        #[test]
3140        fn bom_before_header_yields_title() {
3141            // A UTF-8 BOM precedes the document header. It must be stripped so
3142            // the `= ` title line is recognized rather than misparsed as a
3143            // paragraph.
3144            let doc = Parser::default().parse("\u{feff}= My Title\n\nbody");
3145
3146            assert_eq!(doc.header().title(), Some("My Title"));
3147            assert_eq!(rendered_paragraphs(&doc), vec!["body"]);
3148        }
3149
3150        #[test]
3151        fn bom_before_paragraph_is_stripped() {
3152            // With no header, the BOM must still be removed so it does not
3153            // become the first character of the paragraph's content.
3154            let doc = Parser::default().parse("\u{feff}Hello.\n");
3155
3156            assert_eq!(rendered_paragraphs(&doc), vec!["Hello."]);
3157        }
3158
3159        #[test]
3160        fn only_a_single_leading_bom_is_stripped() {
3161            // Only one leading BOM is stripped; a second U+FEFF is ordinary
3162            // content and survives into the paragraph text (matching
3163            // Asciidoctor).
3164            let doc = Parser::default().parse("\u{feff}\u{feff}Hello.\n");
3165
3166            assert_eq!(rendered_paragraphs(&doc), vec!["\u{feff}Hello."]);
3167        }
3168
3169        #[test]
3170        fn bom_precedes_front_matter_handling() {
3171            // The BOM is stripped before front-matter detection, so a `---`
3172            // fence that immediately follows the mark still opens front matter
3173            // when `skip-front-matter` is set.
3174            let doc = Parser::default()
3175                .with_intrinsic_attribute_bool(
3176                    "skip-front-matter",
3177                    true,
3178                    ModificationContext::ApiOnly,
3179                )
3180                .parse("\u{feff}---\ntitle: Doc\n---\n\n= My Title\n\nbody");
3181
3182            assert_eq!(
3183                doc.attribute_value("front-matter"),
3184                InterpretedValue::Value("title: Doc")
3185            );
3186            assert_eq!(doc.header().title(), Some("My Title"));
3187        }
3188    }
3189
3190    mod remap_attr_name {
3191        use super::super::remap_attr_name;
3192
3193        #[test]
3194        fn strips_non_word_and_lower_cases_ascii() {
3195            assert_eq!(remap_attr_name("Foo Bar"), "foobar");
3196            assert_eq!(remap_attr_name("Foo 3^ # - Bar["), "foo3-bar");
3197            assert_eq!(remap_attr_name("My frog"), "myfrog");
3198        }
3199
3200        #[test]
3201        fn remaps_legacy_aliases() {
3202            // `hardbreaks` and `numbered` are legacy aliases remapped to their
3203            // primary names, matching Asciidoctor's `Parser.store_attribute`.
3204            assert_eq!(remap_attr_name("hardbreaks"), "hardbreaks-option");
3205            assert_eq!(remap_attr_name("Hardbreaks"), "hardbreaks-option");
3206            assert_eq!(remap_attr_name("numbered"), "sectnums");
3207        }
3208
3209        #[test]
3210        fn preserves_unicode_word_characters() {
3211            // Unicode letters and digits are word characters, so they survive
3212            // sanitization; the `{café}` / `{سمن}` references then resolve.
3213            assert_eq!(remap_attr_name("café"), "café");
3214            assert_eq!(remap_attr_name("سمن"), "سمن");
3215        }
3216
3217        #[test]
3218        fn preserves_marks_and_join_controls() {
3219            // `\p{Word}` includes combining marks and join controls, so a
3220            // decomposed name and a name embedding a ZWNJ are not mangled.
3221            let decomposed = "cafe\u{301}";
3222            assert_eq!(remap_attr_name(decomposed), decomposed);
3223
3224            let with_zwnj = "\u{645}\u{200c}\u{646}";
3225            assert_eq!(remap_attr_name(with_zwnj), with_zwnj);
3226        }
3227
3228        #[test]
3229        fn folds_case_with_full_unicode() {
3230            // The name is folded with the full Unicode `to_lowercase()`, so a
3231            // reference lookup is case-insensitive. A fold that expands a
3232            // character (`İ` -> `i` + U+0307 combining dot above) is harmless:
3233            // an attribute reference is folded through the same function, so
3234            // definition and reference still land on the identical key.
3235            assert_eq!(remap_attr_name("He-Man"), "he-man");
3236            assert_eq!(remap_attr_name("İstanbul"), "i\u{307}stanbul");
3237            assert_eq!(remap_attr_name("İstanbul"), "İstanbul".to_lowercase());
3238        }
3239    }
3240
3241    #[test]
3242    fn attribute_reference_resolves_case_insensitively() {
3243        // A reference is folded with the same Unicode `to_lowercase()` used to
3244        // store the name, so any casing of the reference resolves the entry.
3245        let doc = Parser::default().parse(":He-Man: the foe\n\n{he-man} / {HE-MAN} / {He-Man}");
3246        assert_eq!(
3247            rendered_paragraphs(&doc),
3248            vec!["the foe / the foe / the foe"]
3249        );
3250    }
3251
3252    #[test]
3253    fn attribute_reference_case_fold_round_trips_when_it_expands() {
3254        // `İ` folds to `i` + U+0307 under `to_lowercase()`. Because both the
3255        // definition and the reference fold through that same function, the
3256        // entry stays reachable by its own spelling despite the expansion.
3257        let doc = Parser::default().parse(":İ: dotted\n\n{İ}");
3258        assert_eq!(rendered_paragraphs(&doc), vec!["dotted"]);
3259    }
3260
3261    #[test]
3262    fn unicode_attribute_reference_resolves_in_preprocessor() {
3263        // The preprocessor (conditional directives, include targets) resolves
3264        // `{name}` references with the same Unicode word-character class as the
3265        // main substitution pass, so a Unicode-named attribute drives an
3266        // `ifeval` condition. See #726.
3267        let doc = Parser::default()
3268            .parse(":café: yes\n\nifeval::[\"{café}\" == \"yes\"]\nShown.\nendif::[]");
3269        assert_eq!(rendered_paragraphs(&doc), vec!["Shown."]);
3270    }
3271
3272    #[test]
3273    fn case_insensitive_attribute_reference_resolves_in_preprocessor() {
3274        // The preprocessor folds a `{name}` reference the same way the main
3275        // substitution pass does, so a mismatched-case reference still drives an
3276        // `ifeval` condition.
3277        let doc = Parser::default()
3278            .parse(":Answer: yes\n\nifeval::[\"{answer}\" == \"yes\"]\nShown.\nendif::[]");
3279        assert_eq!(rendered_paragraphs(&doc), vec!["Shown."]);
3280    }
3281
3282    #[test]
3283    fn owned_cell_warning_is_recorded_only_inside_an_owned_cell_source() {
3284        use std::rc::Rc;
3285
3286        use crate::{
3287            parser::{SourceLine, SourceMap},
3288            warnings::WarningType,
3289        };
3290
3291        let mut p = Parser::default();
3292
3293        // Outside an owned cell source there is no map to resolve against, so a
3294        // recorded warning has no origin and is dropped rather than queued.
3295        assert!(!p.is_in_owned_cell_source());
3296        p.record_owned_cell_warning(
3297            1,
3298            WarningType::IncludeFileNotFound("x.adoc".to_owned()),
3299            None,
3300        );
3301        assert!(p.take_owned_cell_warnings().is_empty());
3302
3303        // An explicit origin override is queued even without a cell source map.
3304        p.record_owned_cell_warning(
3305            1,
3306            WarningType::UnterminatedConditionalDirective("ifdef::foo[]".to_owned()),
3307            Some(SourceLine(Some("inc.adoc".to_owned()), 3)),
3308        );
3309        let overridden = p.take_owned_cell_warnings();
3310        let [overridden] = overridden.as_slice() else {
3311            panic!("expected exactly one recorded warning, got {overridden:?}");
3312        };
3313        assert_eq!(
3314            overridden.origin,
3315            SourceLine(Some("inc.adoc".to_owned()), 3)
3316        );
3317
3318        // Publish a cell source map (output line 1 came from `cell.adoc` line 2,
3319        // the way the preprocessor would record an include-expanded cell).
3320        let mut sm = SourceMap::default();
3321        sm.append(1, Some("cell.adoc"), 2, crate::parser::Fidelity::Verbatim);
3322        p.push_owned_cell_source_map(Rc::new(sm));
3323        assert!(p.is_in_owned_cell_source());
3324
3325        // Now the same call resolves the line to its origin and queues the
3326        // warning with that pre-resolved (file, line).
3327        p.record_owned_cell_warning(
3328            1,
3329            WarningType::IncludeFileNotFound("y.adoc".to_owned()),
3330            None,
3331        );
3332        let recorded = p.take_owned_cell_warnings();
3333        let [recorded] = recorded.as_slice() else {
3334            panic!("expected exactly one recorded warning, got {recorded:?}");
3335        };
3336        assert_eq!(recorded.origin, SourceLine(Some("cell.adoc".to_owned()), 2));
3337        assert_eq!(
3338            recorded.warning,
3339            WarningType::IncludeFileNotFound("y.adoc".to_owned())
3340        );
3341
3342        // Taking drains the buffer, and popping restores the not-in-owned-cell
3343        // state.
3344        assert!(p.take_owned_cell_warnings().is_empty());
3345        p.pop_owned_cell_source_map();
3346        assert!(!p.is_in_owned_cell_source());
3347    }
3348
3349    #[test]
3350    fn creates_catalog_if_needed() {
3351        let mut p = Parser::default();
3352        let doc = p.parse("= Hello, World!\n\n== First Section Title");
3353        let cat = doc.catalog();
3354        assert!(cat.refs.contains_key("_first_section_title"));
3355
3356        let doc = p.parse("= Hello, World!\n\n== Second Section Title");
3357        let cat = doc.catalog();
3358        assert!(!cat.refs.contains_key("_first_section_title"));
3359        assert!(cat.refs.contains_key("_second_section_title"));
3360    }
3361
3362    #[test]
3363    fn with_intrinsic_attribute() {
3364        let p =
3365            Parser::default().with_intrinsic_attribute("foo", "bar", ModificationContext::Anywhere);
3366
3367        assert_eq!(p.attribute_value("foo"), InterpretedValue::Value("bar"));
3368        assert_eq!(p.attribute_value("foo2"), InterpretedValue::Unset);
3369
3370        assert!(p.is_attribute_set("foo"));
3371        assert!(!p.is_attribute_set("foo2"));
3372        assert!(!p.is_attribute_set("xyz"));
3373    }
3374
3375    #[test]
3376    fn with_intrinsic_attribute_strips_soft_set_modifier() {
3377        // A single trailing `@` on an API value is AsciiDoc's soft-set modifier:
3378        // it is stripped from the stored value.
3379        let mut p = Parser::default().with_intrinsic_attribute(
3380            "myattr",
3381            "hello@",
3382            ModificationContext::ApiOnly,
3383        );
3384
3385        assert_eq!(
3386            p.attribute_value("myattr"),
3387            InterpretedValue::Value("hello")
3388        );
3389
3390        // The stored value flows through to an attribute reference: `{myattr}`
3391        // resolves to `hello`, not `hello@`.
3392        let doc = p.parse("{myattr}");
3393        assert_eq!(rendered_paragraphs(&doc), vec!["hello"]);
3394    }
3395
3396    #[test]
3397    fn soft_set_modifier_makes_value_overridable_by_document() {
3398        // The soft-set `@` also relaxes the modification context to `Anywhere`,
3399        // so a document `:name:` entry overrides the API value even though the
3400        // caller passed the locked `ApiOnly` context.
3401        let doc = Parser::default()
3402            .with_intrinsic_attribute("cash", "heroes@", ModificationContext::ApiOnly)
3403            .parse(":cash: money");
3404
3405        assert_eq!(
3406            doc.attribute_value("cash"),
3407            InterpretedValue::Value("money")
3408        );
3409    }
3410
3411    #[test]
3412    fn without_soft_set_modifier_api_value_is_locked() {
3413        // The same value *without* the `@` keeps the caller's `ApiOnly` context,
3414        // so the document assignment is rejected and the API value stands.
3415        let doc = Parser::default()
3416            .with_intrinsic_attribute("cash", "heroes", ModificationContext::ApiOnly)
3417            .parse(":cash: money");
3418
3419        assert_eq!(
3420            doc.attribute_value("cash"),
3421            InterpretedValue::Value("heroes")
3422        );
3423    }
3424
3425    #[test]
3426    fn soft_set_modifier_strips_only_one_trailing_at() {
3427        // Only the final `@` is the modifier, mirroring Ruby's `String#chop`; a
3428        // preceding `@` is retained as part of the value.
3429        let p = Parser::default().with_intrinsic_attribute(
3430            "myattr",
3431            "hello@@",
3432            ModificationContext::ApiOnly,
3433        );
3434
3435        assert_eq!(
3436            p.attribute_value("myattr"),
3437            InterpretedValue::Value("hello@")
3438        );
3439    }
3440
3441    #[test]
3442    fn non_trailing_at_is_not_a_soft_set_modifier() {
3443        // A `@` that is not the final character is an ordinary value character.
3444        let p = Parser::default().with_intrinsic_attribute(
3445            "myattr",
3446            "foo@bar",
3447            ModificationContext::ApiOnly,
3448        );
3449
3450        assert_eq!(
3451            p.attribute_value("myattr"),
3452            InterpretedValue::Value("foo@bar")
3453        );
3454    }
3455
3456    #[test]
3457    fn with_intrinsic_attribute_remaps_legacy_aliases() {
3458        // An API-supplied `hardbreaks` (Asciidoctor's `-a hardbreaks`) is a
3459        // legacy alias remapped to `hardbreaks-option`, exactly as the same
3460        // attribute written as a header entry (`:hardbreaks:`) is. Without the
3461        // remap the API form is stored verbatim as `hardbreaks` and the
3462        // paragraph's post-replacement check (which consults
3463        // `hardbreaks-option`) never sees it.
3464        let mut p = Parser::default().with_intrinsic_attribute(
3465            "hardbreaks",
3466            "",
3467            ModificationContext::Anywhere,
3468        );
3469
3470        assert!(p.is_attribute_set("hardbreaks-option"));
3471
3472        // The end-to-end effect: each unwrapped line gains a hard line break.
3473        let doc = p.parse("First line\nSecond line");
3474        assert_eq!(
3475            rendered_paragraphs(&doc),
3476            vec!["First line<br>\nSecond line"]
3477        );
3478    }
3479
3480    #[test]
3481    fn api_set_flexible_attribute_is_unlocked_after_the_header() {
3482        // An API-*set* `sectnums` (here via the `numbered` alias) is a flexible
3483        // attribute: it seeds numbering on, but is unlocked once the header is
3484        // parsed so a body `:sectnums!:` still takes effect. Modeled as the
3485        // html5 converter applies it: an `ApiOnly` override on `numbered`.
3486        let mut p = Parser::default().with_intrinsic_attribute(
3487            "numbered",
3488            "",
3489            ModificationContext::ApiOnly,
3490        );
3491
3492        // Before any parse the alias is stored, locked, under `sectnums`.
3493        assert!(p.is_attribute_set("sectnums"));
3494
3495        // A body `:sectnums!:` turns numbering back off for the sections that
3496        // follow it: the unlock let the assignment through.
3497        let doc = p.parse("= Title\n\n== On\n\n:sectnums!:\n\n== Off");
3498        let nums: Vec<Option<String>> = crate::tests::prelude::all_sections(&doc)
3499            .iter()
3500            .map(|s| s.section_number().map(|n| n.to_string()))
3501            .collect();
3502
3503        assert_eq!(nums, vec![Some("1".to_string()), None]);
3504    }
3505
3506    #[test]
3507    fn api_unset_flexible_attribute_stays_locked() {
3508        // An API-*unset* `sectnums` (here via `numbered!`, i.e. the alias set to
3509        // `false`) stays locked: a body `:sectnums:` cannot re-enable numbering.
3510        let mut p = Parser::default().with_intrinsic_attribute_bool(
3511            "numbered",
3512            false,
3513            ModificationContext::ApiOnly,
3514        );
3515
3516        assert!(!p.is_attribute_set("sectnums"));
3517
3518        let doc = p.parse("= Title\n\n:sectnums:\n\n== Still Off");
3519        let nums: Vec<Option<String>> = crate::tests::prelude::all_sections(&doc)
3520            .iter()
3521            .map(|s| s.section_number().map(|n| n.to_string()))
3522            .collect();
3523
3524        assert_eq!(nums, vec![None]);
3525    }
3526
3527    // Under `SafeMode::Server` or greater, `docdir` reads as empty and
3528    // `docfile` is relativized against `docdir`; see #735 and the ported
3529    // upstream tests in `tests/asciidoctor_rb/attributes_test.rs`. These cover
3530    // crate-specific edge cases not exercised by the single upstream test.
3531    #[test]
3532    fn masks_docdir_and_docfile_under_secure_mode() {
3533        // Secure (the default) is stricter than Server, so masking also applies.
3534        let p = Parser::default()
3535            .with_intrinsic_attribute("docdir", "/some/dir", ModificationContext::ApiOnly)
3536            .with_intrinsic_attribute(
3537                "docfile",
3538                "/some/dir/sample.adoc",
3539                ModificationContext::ApiOnly,
3540            );
3541        assert_eq!(p.safe_mode(), SafeMode::Secure);
3542        assert_eq!(p.attribute_value("docdir"), InterpretedValue::Value(""));
3543        assert_eq!(
3544            p.attribute_value("docfile"),
3545            InterpretedValue::Value("sample.adoc")
3546        );
3547
3548        // The masked `docdir` is still a *set* (present) attribute.
3549        assert!(p.is_attribute_set("docdir"));
3550        assert!(p.has_attribute("docfile"));
3551    }
3552
3553    #[test]
3554    fn relativizes_docfile_in_a_subdirectory_of_docdir() {
3555        // A `docfile` nested below `docdir` keeps its sub-path relative to
3556        // `docdir` (not merely its base name), matching Asciidoctor's
3557        // `docfile[(docdir.length + 1)..-1]` slice.
3558        let p = Parser::default()
3559            .with_safe_mode(SafeMode::Server)
3560            .with_intrinsic_attribute("docdir", "/some/dir", ModificationContext::ApiOnly)
3561            .with_intrinsic_attribute(
3562                "docfile",
3563                "/some/dir/sub/sample.adoc",
3564                ModificationContext::ApiOnly,
3565            );
3566        assert_eq!(
3567            p.attribute_value("docfile"),
3568            InterpretedValue::Value("sub/sample.adoc")
3569        );
3570    }
3571
3572    #[test]
3573    fn relativizes_docfile_not_under_docdir_to_its_basename() {
3574        // An inconsistent `docdir` / `docfile` pairing (docfile not under
3575        // docdir) must not be truncated at an unrelated byte offset; it
3576        // relativizes to the base name instead (see #735 review feedback).
3577        let p = Parser::default()
3578            .with_safe_mode(SafeMode::Server)
3579            .with_intrinsic_attribute("docdir", "/some/dir", ModificationContext::ApiOnly)
3580            .with_intrinsic_attribute(
3581                "docfile",
3582                "/some/different/file.adoc",
3583                ModificationContext::ApiOnly,
3584            );
3585        assert_eq!(
3586            p.attribute_value("docfile"),
3587            InterpretedValue::Value("file.adoc")
3588        );
3589    }
3590
3591    #[test]
3592    fn docfile_without_docdir_falls_back_to_basename_under_server_mode() {
3593        let p = Parser::default()
3594            .with_safe_mode(SafeMode::Server)
3595            .with_intrinsic_attribute(
3596                "docfile",
3597                "/some/dir/sample.adoc",
3598                ModificationContext::ApiOnly,
3599            );
3600        assert_eq!(
3601            p.attribute_value("docfile"),
3602            InterpretedValue::Value("sample.adoc")
3603        );
3604    }
3605
3606    #[test]
3607    fn does_not_mask_docdir_and_docfile_below_server_mode() {
3608        // Below Server, the API-provided values pass through verbatim.
3609        let p = Parser::default()
3610            .with_safe_mode(SafeMode::Safe)
3611            .with_intrinsic_attribute("docdir", "/some/dir", ModificationContext::ApiOnly)
3612            .with_intrinsic_attribute(
3613                "docfile",
3614                "/some/dir/sample.adoc",
3615                ModificationContext::ApiOnly,
3616            );
3617        assert_eq!(
3618            p.attribute_value("docdir"),
3619            InterpretedValue::Value("/some/dir")
3620        );
3621        assert_eq!(
3622            p.attribute_value("docfile"),
3623            InterpretedValue::Value("/some/dir/sample.adoc")
3624        );
3625    }
3626
3627    #[test]
3628    fn unset_docdir_and_docfile_stay_missing_under_server_mode() {
3629        // Masking never conjures a value for an attribute that was never set, so
3630        // a reference to an unset `docdir` / `docfile` still resolves as missing.
3631        let p = Parser::default().with_safe_mode(SafeMode::Server);
3632        assert_eq!(p.attribute_value("docdir"), InterpretedValue::Unset);
3633        assert_eq!(p.attribute_value("docfile"), InterpretedValue::Unset);
3634        assert!(!p.has_attribute("docdir"));
3635        assert!(!p.has_attribute("docfile"));
3636    }
3637
3638    #[test]
3639    fn leaves_non_string_docdir_and_docfile_untouched_under_server_mode() {
3640        // A `docdir` / `docfile` present as a boolean flag (not a path string)
3641        // carries no host path to leak, so the masking has nothing to blank or
3642        // relativize and leaves the (empty) `Set` value as-is.
3643        let p = Parser::default()
3644            .with_safe_mode(SafeMode::Server)
3645            .with_intrinsic_attribute_bool("docdir", true, ModificationContext::ApiOnly)
3646            .with_intrinsic_attribute_bool("docfile", true, ModificationContext::ApiOnly);
3647        assert_eq!(p.attribute_value("docdir"), InterpretedValue::Set);
3648        assert_eq!(p.attribute_value("docfile"), InterpretedValue::Set);
3649    }
3650
3651    #[test]
3652    fn with_intrinsic_attribute_set() {
3653        let p = Parser::default().with_intrinsic_attribute_bool(
3654            "foo",
3655            true,
3656            ModificationContext::Anywhere,
3657        );
3658
3659        assert_eq!(p.attribute_value("foo"), InterpretedValue::Set);
3660        assert_eq!(p.attribute_value("foo2"), InterpretedValue::Unset);
3661
3662        assert!(p.is_attribute_set("foo"));
3663        assert!(!p.is_attribute_set("foo2"));
3664        assert!(!p.is_attribute_set("xyz"));
3665    }
3666
3667    #[test]
3668    fn with_intrinsic_attribute_unset() {
3669        let p = Parser::default().with_intrinsic_attribute_bool(
3670            "foo",
3671            false,
3672            ModificationContext::Anywhere,
3673        );
3674
3675        assert_eq!(p.attribute_value("foo"), InterpretedValue::Unset);
3676        assert_eq!(p.attribute_value("foo2"), InterpretedValue::Unset);
3677
3678        assert!(!p.is_attribute_set("foo"));
3679        assert!(!p.is_attribute_set("foo2"));
3680        assert!(!p.is_attribute_set("xyz"));
3681    }
3682
3683    #[test]
3684    fn can_not_override_locked_default_value() {
3685        let mut parser = Parser::default();
3686
3687        let doc = parser.parse(":sp: not a space!");
3688
3689        assert_eq!(
3690            doc.warnings().next().unwrap().warning,
3691            WarningType::AttributeValueIsLocked("sp".to_owned())
3692        );
3693
3694        assert_eq!(parser.attribute_value("sp"), InterpretedValue::Value(" "));
3695    }
3696
3697    #[test]
3698    fn asciidoc_parser_version_is_predefined() {
3699        // The crate predefines `asciidoc-parser-version` with its own version
3700        // (the parser-specific counterpart of Ruby Asciidoctor's
3701        // `asciidoctor-version` intrinsic).
3702        let mut parser = Parser::default();
3703
3704        assert_eq!(
3705            parser.attribute_value("asciidoc-parser-version"),
3706            InterpretedValue::Value(env!("CARGO_PKG_VERSION"))
3707        );
3708
3709        // The value is available to attribute references and `ifeval`
3710        // expressions in document content.
3711        let doc = parser.parse(concat!(
3712            "= Title\n",
3713            "\n",
3714            "ifeval::['{asciidoc-parser-version}' >= '0.1.0']\n",
3715            "v{asciidoc-parser-version}\n",
3716            "endif::[]\n",
3717        ));
3718
3719        assert_eq!(
3720            rendered_paragraphs(&doc),
3721            vec![format!("v{}", env!("CARGO_PKG_VERSION"))]
3722        );
3723    }
3724
3725    #[test]
3726    fn asciidoc_parser_version_is_locked() {
3727        // The parser version describes the processor itself, so a document
3728        // assignment is rejected with a warning and the built-in value stays
3729        // in place.
3730        let mut parser = Parser::default();
3731
3732        let doc = parser.parse(":asciidoc-parser-version: 99.99.99");
3733
3734        assert_eq!(
3735            doc.warnings().next().unwrap().warning,
3736            WarningType::AttributeValueIsLocked("asciidoc-parser-version".to_owned())
3737        );
3738
3739        assert_eq!(
3740            parser.attribute_value("asciidoc-parser-version"),
3741            InterpretedValue::Value(env!("CARGO_PKG_VERSION"))
3742        );
3743    }
3744
3745    #[test]
3746    fn asciidoctor_version_is_predefined() {
3747        // The crate predefines `asciidoctor-version` with the Asciidoctor
3748        // release whose behavior it implements, so documents written against
3749        // Asciidoctor's own intrinsic behave the same here.
3750        let mut parser = Parser::default();
3751
3752        assert_eq!(
3753            parser.attribute_value("asciidoctor-version"),
3754            InterpretedValue::Value(crate::ASCIIDOCTOR_VERSION)
3755        );
3756
3757        // The value is available to `ifdef` gating and to attribute references
3758        // and `ifeval` expressions in document content.
3759        let doc = parser.parse(concat!(
3760            "= Title\n",
3761            "\n",
3762            "ifdef::asciidoctor-version[]\n",
3763            "ifeval::['{asciidoctor-version}' >= '0.1.0']\n",
3764            "v{asciidoctor-version}\n",
3765            "endif::[]\n",
3766            "endif::[]\n",
3767        ));
3768
3769        assert_eq!(
3770            rendered_paragraphs(&doc),
3771            vec![format!("v{}", crate::ASCIIDOCTOR_VERSION)]
3772        );
3773    }
3774
3775    #[test]
3776    fn asciidoctor_version_is_locked() {
3777        // Like its `asciidoc-parser-version` companion, this describes the
3778        // processor itself, so a document assignment is rejected with a warning
3779        // and the built-in value stays in place.
3780        let mut parser = Parser::default();
3781
3782        let doc = parser.parse(":asciidoctor-version: 99.99.99");
3783
3784        assert_eq!(
3785            doc.warnings().next().unwrap().warning,
3786            WarningType::AttributeValueIsLocked("asciidoctor-version".to_owned())
3787        );
3788
3789        assert_eq!(
3790            parser.attribute_value("asciidoctor-version"),
3791            InterpretedValue::Value(crate::ASCIIDOCTOR_VERSION)
3792        );
3793    }
3794
3795    #[test]
3796    fn asciidoctor_flag_is_predefined() {
3797        // The crate predefines the always-set `asciidoctor` boolean flag, so a
3798        // document guarding Asciidoctor-only content with `ifdef::asciidoctor[]`
3799        // behaves the same here. A `////` comment block containing a directive
3800        // that would corrupt it once the flag is defined must stay untouched
3801        // (see issue #810).
3802        let mut parser = Parser::default();
3803
3804        assert_eq!(parser.attribute_value("asciidoctor"), InterpretedValue::Set);
3805
3806        let doc = parser.parse(concat!(
3807            "= Title\n",
3808            "\n",
3809            "ifdef::asciidoctor[]\n",
3810            "shown when asciidoctor is set\n",
3811            "endif::[]\n",
3812            "\n",
3813            "////\n",
3814            "ifdef::asciidoctor[////]\n",
3815            "////\n",
3816            "\n",
3817            "line after comment block\n",
3818        ));
3819
3820        assert_eq!(
3821            rendered_paragraphs(&doc),
3822            vec![
3823                "shown when asciidoctor is set".to_owned(),
3824                "line after comment block".to_owned(),
3825            ]
3826        );
3827    }
3828
3829    #[test]
3830    fn asciidoctor_flag_is_locked() {
3831        // Like the version intrinsics, the flag describes the processor itself,
3832        // so a document assignment is rejected with a warning and the built-in
3833        // value stays in place.
3834        let mut parser = Parser::default();
3835
3836        let doc = parser.parse(":asciidoctor: 99.99.99");
3837
3838        assert_eq!(
3839            doc.warnings().next().unwrap().warning,
3840            WarningType::AttributeValueIsLocked("asciidoctor".to_owned())
3841        );
3842
3843        assert_eq!(parser.attribute_value("asciidoctor"), InterpretedValue::Set);
3844    }
3845
3846    #[test]
3847    fn asciidoc_parser_version_distinguishes_the_two_processors() {
3848        // Both version intrinsics are defined, so a document tells the
3849        // processors apart via `asciidoc-parser-version`, which Ruby
3850        // Asciidoctor does not define.
3851        let mut parser = Parser::default();
3852
3853        let doc = parser.parse(concat!(
3854            "= Title\n",
3855            "\n",
3856            "ifdef::asciidoc-parser-version[]\n",
3857            "This is asciidoc-parser.\n",
3858            "endif::[]\n",
3859        ));
3860
3861        assert_eq!(rendered_paragraphs(&doc), vec!["This is asciidoc-parser."]);
3862    }
3863
3864    #[test]
3865    fn silently_locked_intrinsic_rejects_header_and_body_without_warning() {
3866        // A silently-locked `ApiOnly` intrinsic (as a converter would seed a
3867        // safe-mode-restricted attribute) rejects both a header assignment and a
3868        // body assignment of the same name, leaving the value unchanged and
3869        // recording no warning.
3870        let mut parser = Parser::default().with_intrinsic_attribute_silent(
3871            "backend",
3872            "html5",
3873            ModificationContext::ApiOnly,
3874        );
3875
3876        let doc = parser.parse(concat!(
3877            "= Title\n",
3878            ":backend: docbook5\n",
3879            "\n",
3880            "Body paragraph.\n",
3881            "\n",
3882            ":backend: manpage\n",
3883        ));
3884
3885        assert_eq!(doc.warnings().count(), 0);
3886        assert_eq!(
3887            parser.attribute_value("backend"),
3888            InterpretedValue::Value("html5")
3889        );
3890    }
3891
3892    #[test]
3893    fn silently_locked_bool_intrinsic_rejects_without_warning() {
3894        let mut parser = Parser::default().with_intrinsic_attribute_bool_silent(
3895            "sectids",
3896            true,
3897            ModificationContext::ApiOnly,
3898        );
3899
3900        let doc = parser.parse(concat!("= Title\n", ":!sectids:\n"));
3901
3902        assert_eq!(doc.warnings().count(), 0);
3903        assert_eq!(parser.attribute_value("sectids"), InterpretedValue::Set);
3904    }
3905
3906    #[test]
3907    fn silently_locked_bool_intrinsic_false_is_unset() {
3908        // A `false` flag records an `Unset` tombstone, and a locked (`ApiOnly`)
3909        // attribute rejects a document body reassignment without warning.
3910        let mut parser = Parser::default().with_intrinsic_attribute_bool_silent(
3911            "sectids",
3912            false,
3913            ModificationContext::ApiOnly,
3914        );
3915
3916        let doc = parser.parse(concat!("= Title\n", ":sectids:\n"));
3917
3918        assert_eq!(doc.warnings().count(), 0);
3919        assert_eq!(parser.attribute_value("sectids"), InterpretedValue::Unset);
3920    }
3921
3922    #[test]
3923    fn normally_locked_intrinsic_still_warns() {
3924        // Regression: a non-silent `ApiOnly` intrinsic still records
3925        // `AttributeValueIsLocked` when the document tries to reassign it.
3926        let mut parser = Parser::default().with_intrinsic_attribute(
3927            "backend",
3928            "html5",
3929            ModificationContext::ApiOnly,
3930        );
3931
3932        let doc = parser.parse(concat!("= Title\n", ":backend: docbook5\n"));
3933
3934        assert_eq!(
3935            doc.warnings().next().unwrap().warning,
3936            WarningType::AttributeValueIsLocked("backend".to_owned())
3937        );
3938        assert_eq!(
3939            parser.attribute_value("backend"),
3940            InterpretedValue::Value("html5")
3941        );
3942    }
3943
3944    #[test]
3945    fn catalog_transferred_to_document() {
3946        let mut parser = Parser::default();
3947        let doc = parser.parse("= Test Document\n\nSome content");
3948
3949        let catalog = doc.catalog();
3950        assert!(catalog.is_empty());
3951
3952        // The catalog was transferred to the document, leaving the parser with
3953        // an empty catalog.
3954        assert!(parser.catalog.borrow().is_empty());
3955    }
3956
3957    #[test]
3958    fn block_ids_registered_in_catalog() {
3959        let mut parser = Parser::default();
3960        let doc = parser.parse("= Test Document\n\n[#my-block]\nSome content with an ID");
3961
3962        let catalog = doc.catalog();
3963        assert!(!catalog.is_empty());
3964        assert!(catalog.contains_id("my-block"));
3965
3966        let entry = catalog.get_ref("my-block").unwrap();
3967        assert_eq!(entry.id, "my-block");
3968        assert_eq!(entry.ref_type, crate::document::RefType::Anchor);
3969    }
3970
3971    /// A simple test renderer that modifies special characters differently
3972    /// from the default HTML renderer.
3973    #[derive(Debug)]
3974    struct TestRenderer;
3975
3976    impl InlineSubstitutionRenderer for TestRenderer {
3977        fn render_special_character(&self, type_: SpecialCharacter, dest: &mut String) {
3978            // Custom rendering: wrap special characters in brackets.
3979            match type_ {
3980                SpecialCharacter::Lt => dest.push_str("[LT]"),
3981                SpecialCharacter::Gt => dest.push_str("[GT]"),
3982                SpecialCharacter::Ampersand => dest.push_str("[AMP]"),
3983            }
3984        }
3985
3986        fn render_quoted_substitution(
3987            &self,
3988            _type_: QuoteType,
3989            _scope: QuoteScope,
3990            _attrlist: Option<Attrlist<'_>>,
3991            _id: Option<String>,
3992            body: &str,
3993            dest: &mut String,
3994        ) {
3995            dest.push_str(body);
3996        }
3997
3998        fn render_character_replacement(
3999            &self,
4000            _type_: CharacterReplacementType,
4001            dest: &mut String,
4002        ) {
4003            dest.push_str("[CHAR]");
4004        }
4005
4006        fn render_line_break(&self, dest: &mut String) {
4007            dest.push_str("[BR]");
4008        }
4009
4010        fn render_image(&self, _params: &ImageRenderParams, dest: &mut String) {
4011            dest.push_str("[IMAGE]");
4012        }
4013
4014        fn image_uri(
4015            &self,
4016            target_image_path: &str,
4017            _parser: &Parser,
4018            _asset_dir_key: Option<&str>,
4019        ) -> String {
4020            target_image_path.to_string()
4021        }
4022
4023        fn render_icon(&self, _params: &IconRenderParams, dest: &mut String) {
4024            dest.push_str("[ICON]");
4025        }
4026
4027        fn render_link(&self, _params: &LinkRenderParams, dest: &mut String) {
4028            dest.push_str("[LINK]");
4029        }
4030
4031        fn render_anchor(&self, id: &str, _reftext: Option<String>, dest: &mut String) {
4032            dest.push_str(&format!("[ANCHOR:{}]", id));
4033        }
4034
4035        fn render_xref(&self, params: &crate::parser::XrefRenderParams, dest: &mut String) {
4036            dest.push_str(&format!("[XREF:{}]", params.target));
4037        }
4038
4039        fn render_callout(&self, params: &crate::parser::CalloutRenderParams, dest: &mut String) {
4040            dest.push_str(&format!("[CALLOUT:{}]", params.number));
4041        }
4042
4043        fn render_index_term(
4044            &self,
4045            params: &crate::parser::IndexTermRenderParams,
4046            dest: &mut String,
4047        ) {
4048            match params.visible_term {
4049                Some(term) => dest.push_str(&format!("[INDEXTERM:{term}]")),
4050                None => dest.push_str("[INDEXTERM]"),
4051            }
4052        }
4053
4054        fn render_button(&self, text: &str, dest: &mut String) {
4055            dest.push_str(&format!("[BUTTON:{text}]"));
4056        }
4057
4058        fn render_keyboard(&self, keys: &[String], dest: &mut String) {
4059            dest.push_str(&format!("[KBD:{}]", keys.join("+")));
4060        }
4061
4062        fn render_menu(&self, params: &crate::parser::MenuRenderParams, dest: &mut String) {
4063            dest.push_str(&format!("[MENU:{}]", params.menu));
4064        }
4065
4066        fn render_footnote(&self, params: &crate::parser::FootnoteRenderParams, dest: &mut String) {
4067            match params.index {
4068                Some(index) => dest.push_str(&format!("[FOOTNOTE:{index}]")),
4069                None => dest.push_str(&format!("[FOOTNOTE:{}]", params.text)),
4070            }
4071        }
4072    }
4073
4074    #[test]
4075    fn with_inline_substitution_renderer() {
4076        let mut parser = Parser::default().with_inline_substitution_renderer(TestRenderer);
4077
4078        // Parse a simple document with special characters and a footnote.
4079        let doc = parser.parse("Hello & goodbye < world > test footnote:[a note]");
4080
4081        // The document should parse successfully.
4082        assert_eq!(doc.warnings().count(), 0);
4083
4084        // Get the first block from the document.
4085        let block = doc.child_blocks().next().unwrap();
4086
4087        let Block::Simple(simple_block) = block else {
4088            panic!("Expected simple block, got: {block:?}");
4089        };
4090
4091        // Our custom renderer should show [AMP], [LT], and [GT] instead of HTML
4092        // entities, and a resolved footnote as [FOOTNOTE:<index>].
4093        assert_eq!(
4094            simple_block.content().rendered(),
4095            "Hello [AMP] goodbye [LT] world [GT] test [FOOTNOTE:1]"
4096        );
4097    }
4098
4099    #[test]
4100    fn custom_renderer_renders_unresolved_footnote() {
4101        let mut parser = Parser::default().with_inline_substitution_renderer(TestRenderer);
4102
4103        // An unresolved footnote reference exercises the renderer's `None`
4104        // (no index) branch, which our custom renderer shows as
4105        // [FOOTNOTE:<text>].
4106        let doc = parser.parse("test.footnote:missing[]");
4107
4108        let block = doc.child_blocks().next().unwrap();
4109        let Block::Simple(simple_block) = block else {
4110            panic!("Expected simple block, got: {block:?}");
4111        };
4112
4113        assert_eq!(simple_block.content().rendered(), "test.[FOOTNOTE:missing]");
4114    }
4115
4116    /// A custom [`PathResolver`](crate::parser::PathResolver) that rewrites
4117    /// every asset target under a fixed content root, ignoring the start path.
4118    /// Stands in for a host (Antora/Zola-style) that maps targets through a
4119    /// virtual filesystem or URL scheme.
4120    #[derive(Debug)]
4121    struct CdnPathResolver;
4122
4123    impl crate::parser::PathResolver for CdnPathResolver {
4124        fn web_path(&self, target: &str, _start: Option<&str>) -> String {
4125            format!("https://cdn.example.com/{target}")
4126        }
4127    }
4128
4129    #[test]
4130    fn with_path_resolver() {
4131        let mut parser = Parser::default().with_path_resolver(CdnPathResolver);
4132
4133        // An inline image's `src` is resolved through the path resolver, so the
4134        // custom resolver should rewrite it under the content root.
4135        let doc = parser.parse("image:tiger.png[tiger]");
4136
4137        let block = doc.child_blocks().next().unwrap();
4138        let Block::Simple(simple_block) = block else {
4139            panic!("Expected simple block, got: {block:?}");
4140        };
4141
4142        assert_eq!(
4143            simple_block.content().rendered(),
4144            r#"<span class="image"><img src="https://cdn.example.com/tiger.png" alt="tiger"></span>"#
4145        );
4146    }
4147
4148    mod resolve_show_title {
4149        use crate::parser::{ModificationContext, Parser};
4150
4151        fn with(name: &str, set: bool) -> Parser {
4152            Parser::default().with_intrinsic_attribute_bool(
4153                name,
4154                set,
4155                ModificationContext::Anywhere,
4156            )
4157        }
4158
4159        #[test]
4160        fn neither_present_uses_default() {
4161            assert!(Parser::default().resolve_show_title(true));
4162            assert!(!Parser::default().resolve_show_title(false));
4163        }
4164
4165        #[test]
4166        fn showtitle_takes_precedence_and_decides() {
4167            // Present and set -> shown; present and unset -> hidden, regardless
4168            // of the default.
4169            assert!(with("showtitle", true).resolve_show_title(false));
4170            assert!(!with("showtitle", false).resolve_show_title(true));
4171        }
4172
4173        #[test]
4174        fn notitle_is_the_complement_when_showtitle_absent() {
4175            // notitle set -> hidden; notitle unset -> shown.
4176            assert!(!with("notitle", true).resolve_show_title(true));
4177            assert!(with("notitle", false).resolve_show_title(false));
4178        }
4179    }
4180
4181    mod notitle_showtitle_linkage {
4182        use crate::{
4183            blocks::{Block, FindBlocks},
4184            document::InterpretedValue,
4185            parser::{ModificationContext, Parser},
4186        };
4187
4188        // Asciidoctor asciidoctor/asciidoctor#3804: `notitle` and `showtitle`
4189        // are two spellings of one title-visibility toggle, wired as inverses.
4190        // Assigning either updates the partner so the resolved document carries
4191        // one consistent signal – following Asciidoctor's hash semantics, where
4192        // turning the toggle *on* sets one spelling and *removes* the other.
4193
4194        fn parse_header(entries: &str) -> Parser {
4195            let mut parser = Parser::default();
4196            let _ = parser.parse(&format!("= Title\n{entries}\n\nbody"));
4197            parser
4198        }
4199
4200        #[test]
4201        fn header_showtitle_set_unsets_notitle() {
4202            // `:showtitle:` => notitle removed (absent).
4203            let parser = parse_header(":showtitle:");
4204            assert_eq!(parser.attribute_value("showtitle"), InterpretedValue::Set);
4205            assert!(!parser.has_attribute("notitle"));
4206        }
4207
4208        #[test]
4209        fn header_showtitle_unset_sets_notitle() {
4210            // `:!showtitle:` => notitle set.
4211            let parser = parse_header(":!showtitle:");
4212            assert!(!parser.is_attribute_set("showtitle"));
4213            assert_eq!(parser.attribute_value("notitle"), InterpretedValue::Set);
4214            assert!(parser.is_attribute_set("notitle"));
4215        }
4216
4217        #[test]
4218        fn header_notitle_set_unsets_showtitle() {
4219            // `:notitle:` => showtitle removed (absent).
4220            let parser = parse_header(":notitle:");
4221            assert_eq!(parser.attribute_value("notitle"), InterpretedValue::Set);
4222            assert!(!parser.has_attribute("showtitle"));
4223        }
4224
4225        #[test]
4226        fn header_notitle_unset_sets_showtitle() {
4227            // `:!notitle:` => showtitle set. This is the case called out in the
4228            // issue: a consumer keying off `showtitle` now sees a signal.
4229            let parser = parse_header(":!notitle:");
4230            assert!(!parser.is_attribute_set("notitle"));
4231            assert_eq!(parser.attribute_value("showtitle"), InterpretedValue::Set);
4232            assert!(parser.is_attribute_set("showtitle"));
4233        }
4234
4235        #[test]
4236        fn last_assignment_wins() {
4237            // Each assignment rewrites the partner, so whichever is assigned
4238            // last decides the resolved toggle.
4239            let parser = parse_header(":notitle:\n:showtitle:");
4240            assert_eq!(parser.attribute_value("showtitle"), InterpretedValue::Set);
4241            assert!(!parser.has_attribute("notitle"));
4242
4243            let parser = parse_header(":showtitle:\n:notitle:");
4244            assert_eq!(parser.attribute_value("notitle"), InterpretedValue::Set);
4245            assert!(!parser.has_attribute("showtitle"));
4246        }
4247
4248        #[test]
4249        fn body_assignment_is_linked() {
4250            // A body attribute entry links the partner just as a header entry
4251            // does.
4252            let mut parser = Parser::default();
4253            let _ = parser.parse("= Title\n\nintro\n\n:notitle:\n\nmore");
4254            assert_eq!(parser.attribute_value("notitle"), InterpretedValue::Set);
4255            assert!(!parser.has_attribute("showtitle"));
4256        }
4257
4258        #[test]
4259        fn api_assignment_is_linked() {
4260            // Setting either attribute via the API links the partner, matching
4261            // Asciidoctor's `attributes: { 'notitle!' => '' }` etc.
4262            let parser = Parser::default().with_intrinsic_attribute_bool(
4263                "notitle",
4264                true,
4265                ModificationContext::Anywhere,
4266            );
4267            assert_eq!(parser.attribute_value("notitle"), InterpretedValue::Set);
4268            assert!(!parser.has_attribute("showtitle"));
4269
4270            let parser = Parser::default().with_intrinsic_attribute_bool(
4271                "notitle",
4272                false,
4273                ModificationContext::Anywhere,
4274            );
4275            assert!(!parser.is_attribute_set("notitle"));
4276            assert_eq!(parser.attribute_value("showtitle"), InterpretedValue::Set);
4277        }
4278
4279        #[test]
4280        fn turning_the_toggle_on_leaves_no_partner_tombstone() {
4281            // `:notitle:` removes `showtitle` outright rather than leaving an
4282            // unset tombstone, so a `{showtitle}` reference stays literal (as it
4283            // would with the attribute absent) instead of resolving to an empty
4284            // string. This guards the interaction flagged in review.
4285            let parser = parse_header(":notitle:");
4286            assert!(!parser.has_attribute("showtitle"));
4287
4288            let mut parser = Parser::default();
4289            let doc = parser.parse("= Title\n:notitle:\n\n{showtitle}");
4290            let block = doc.child_blocks().next().unwrap();
4291            let Block::Simple(simple_block) = block else {
4292                panic!("expected a simple block");
4293            };
4294            assert_eq!(simple_block.content().rendered(), "{showtitle}");
4295        }
4296
4297        #[test]
4298        fn unrelated_attributes_are_untouched() {
4299            // A document that never assigns either spelling leaves both absent –
4300            // the linkage is a no-op for every other attribute.
4301            let parser = parse_header(":sectnums:");
4302            assert!(!parser.has_attribute("notitle"));
4303            assert!(!parser.has_attribute("showtitle"));
4304        }
4305    }
4306
4307    mod derived_backend_family_attrs {
4308        use crate::{
4309            document::InterpretedValue,
4310            parser::{AllowableValue, AttributeValue, ModificationContext, Parser},
4311        };
4312
4313        #[test]
4314        fn tracks_the_active_doctype() {
4315            let mut parser = Parser::default();
4316
4317            // The default doctype is `article`, so only its derived attribute is
4318            // defined (to an empty value).
4319            assert_eq!(
4320                parser.attribute_value("backend-html5-doctype-article"),
4321                InterpretedValue::Value(String::new())
4322            );
4323            assert_eq!(
4324                parser.attribute_value("backend-html5-doctype-book"),
4325                InterpretedValue::Unset
4326            );
4327
4328            // Forcing a new doctype moves the derived attribute with it.
4329            parser.force_doctype("book");
4330            assert_eq!(
4331                parser.attribute_value("backend-html5-doctype-book"),
4332                InterpretedValue::Value(String::new())
4333            );
4334            assert_eq!(
4335                parser.attribute_value("backend-html5-doctype-article"),
4336                InterpretedValue::Unset
4337            );
4338        }
4339
4340        #[test]
4341        fn defines_no_derived_attr_when_doctype_is_not_a_value() {
4342            let mut parser = Parser::default();
4343
4344            // The default article derived attribute starts out defined.
4345            assert_eq!(
4346                parser.attribute_value("backend-html5-doctype-article"),
4347                InterpretedValue::Value(String::new())
4348            );
4349
4350            // Shadow the built-in `doctype` default with an explicit unset
4351            // tombstone. With `doctype` no longer resolving to a `Value`, no
4352            // derived attribute is synthesized for any doctype.
4353            std::sync::Arc::make_mut(&mut parser.attribute_values).insert(
4354                "doctype".to_string(),
4355                AttributeValue {
4356                    allowable_value: AllowableValue::Any,
4357                    modification_context: ModificationContext::Anywhere,
4358                    silent_when_locked: false,
4359                    value: InterpretedValue::Unset,
4360                },
4361            );
4362
4363            assert_eq!(parser.attribute_value("doctype"), InterpretedValue::Unset);
4364            assert_eq!(
4365                parser.attribute_value("backend-html5-doctype-article"),
4366                InterpretedValue::Unset
4367            );
4368        }
4369
4370        #[test]
4371        fn document_header_cannot_assign_a_derived_doctype_flag() {
4372            // The `backend-html5-doctype-*` namespace is a read-only intrinsic,
4373            // so a document header assignment to it is ignored: the flag for the
4374            // (inactive) `book` doctype stays undefined rather than taking the
4375            // assigned value, so it cannot later shadow the intrinsic.
4376            let mut parser = Parser::default();
4377            let _doc = parser.parse("= Title\n:backend-html5-doctype-book: custom\n\nbody");
4378
4379            assert_eq!(
4380                parser.attribute_value("backend-html5-doctype-book"),
4381                InterpretedValue::Unset
4382            );
4383        }
4384
4385        #[test]
4386        fn default_backend_family_is_materialized() {
4387            let parser = Parser::default();
4388
4389            // The default backend is `html5`; its whole derived family resolves
4390            // to queryable document attributes (empty-valued flags plus the
4391            // `backend` / `basebackend` / `filetype` values).
4392            for (name, value) in [
4393                ("backend", "html5"),
4394                ("backend-html5", ""),
4395                ("basebackend", "html"),
4396                ("basebackend-html", ""),
4397                ("filetype", "html"),
4398                ("filetype-html", ""),
4399                ("doctype-article", ""),
4400                ("backend-html5-doctype-article", ""),
4401                ("basebackend-html-doctype-article", ""),
4402            ] {
4403                assert!(parser.has_attribute(name), "missing {name:?}");
4404                assert!(parser.is_attribute_set(name), "not set: {name:?}");
4405                assert_eq!(
4406                    parser.attribute_value(name),
4407                    InterpretedValue::Value(value.to_string()),
4408                    "unexpected value for {name:?}"
4409                );
4410            }
4411        }
4412
4413        #[test]
4414        fn family_tracks_a_non_html_backend() {
4415            // Setting a different backend re-derives the whole family from it
4416            // (basebackend strips the trailing digits, filetype maps through the
4417            // Asciidoctor extension table), and the inactive `html5` flags fall
4418            // away.
4419            let doc = Parser::default().parse(":backend: docbook5\n\nbody");
4420
4421            assert_eq!(
4422                doc.attribute_value("backend"),
4423                InterpretedValue::Value("docbook5".to_string())
4424            );
4425            assert_eq!(
4426                doc.attribute_value("basebackend"),
4427                InterpretedValue::Value("docbook".to_string())
4428            );
4429            assert_eq!(
4430                doc.attribute_value("filetype"),
4431                InterpretedValue::Value("xml".to_string())
4432            );
4433            assert!(doc.has_attribute("backend-docbook5"));
4434            assert!(doc.has_attribute("basebackend-docbook"));
4435            assert!(doc.has_attribute("backend-docbook5-doctype-article"));
4436
4437            // The derived values report as set through the post-parse
4438            // `Document` (snapshot) reader, not just the live parser.
4439            assert!(doc.is_attribute_set("basebackend"));
4440            assert!(doc.is_attribute_set("filetype"));
4441
4442            // The html5 flags are no longer active.
4443            assert!(!doc.has_attribute("backend-html5"));
4444            assert!(!doc.has_attribute("basebackend-html"));
4445            assert!(!doc.has_attribute("backend-html5-doctype-article"));
4446        }
4447
4448        #[test]
4449        fn derived_value_and_flag_attributes_are_read_only() {
4450            // `basebackend` / `filetype` and the derived flag namespace are
4451            // read-only intrinsics; a document assignment is silently ignored and
4452            // the synthesized value stands.
4453            let doc = Parser::default().parse(
4454                ":basebackend: custom\n:filetype: custom\n:backend-html5: custom\n:doctype-article: custom\n\nbody",
4455            );
4456
4457            assert_eq!(
4458                doc.attribute_value("basebackend"),
4459                InterpretedValue::Value("html".to_string())
4460            );
4461            assert_eq!(
4462                doc.attribute_value("filetype"),
4463                InterpretedValue::Value("html".to_string())
4464            );
4465            assert_eq!(
4466                doc.attribute_value("backend-html5"),
4467                InterpretedValue::Value(String::new())
4468            );
4469            assert_eq!(
4470                doc.attribute_value("doctype-article"),
4471                InterpretedValue::Value(String::new())
4472            );
4473        }
4474
4475        #[test]
4476        fn custom_prefixed_flags_stay_assignable() {
4477            // Author-defined attributes that share a derived-family prefix but
4478            // name no active flag (and are not the doctype-keyed namespace) are
4479            // kept, not swallowed by the read-only reservation, so they stay
4480            // visible to `ifdef` / attribute references – matching Asciidoctor.
4481            let doc = Parser::default().parse(
4482                ":backend-custom: enabled\n:basebackend-custom: on\n:filetype-custom: yes\n:doctype-draft: 1\n\nbody",
4483            );
4484
4485            for (name, value) in [
4486                ("backend-custom", "enabled"),
4487                ("basebackend-custom", "on"),
4488                ("filetype-custom", "yes"),
4489                ("doctype-draft", "1"),
4490            ] {
4491                assert!(doc.has_attribute(name), "missing {name:?}");
4492                assert_eq!(
4493                    doc.attribute_value(name),
4494                    InterpretedValue::Value(value.to_string()),
4495                    "unexpected value for {name:?}"
4496                );
4497            }
4498        }
4499
4500        #[test]
4501        fn unset_backend_makes_the_family_absent() {
4502            // Explicitly unsetting `backend` leaves nothing to derive from, so
4503            // `basebackend` / `filetype` and the backend-keyed flags are absent
4504            // rather than resolving to empty traits or degenerate `backend-` /
4505            // `filetype-` names.
4506            let doc = Parser::default().parse(":backend!:\n\nbody");
4507
4508            assert_eq!(doc.attribute_value("backend"), InterpretedValue::Unset);
4509            for name in ["basebackend", "filetype"] {
4510                assert!(!doc.has_attribute(name), "unexpectedly present: {name:?}");
4511                assert!(!doc.is_attribute_set(name), "unexpectedly set: {name:?}");
4512                assert_eq!(doc.attribute_value(name), InterpretedValue::Unset);
4513            }
4514
4515            // No degenerate empty-suffix flags, and the html5 flags are gone.
4516            for name in [
4517                "backend-",
4518                "basebackend-",
4519                "filetype-",
4520                "backend-html5",
4521                "basebackend-html",
4522            ] {
4523                assert!(!doc.has_attribute(name), "unexpectedly present: {name:?}");
4524            }
4525
4526            // The doctype-only flag does not depend on `backend`, so it remains.
4527            assert!(doc.has_attribute("doctype-article"));
4528        }
4529    }
4530
4531    mod docname {
4532        use crate::Parser;
4533
4534        #[test]
4535        fn none_without_primary_file_name() {
4536            assert_eq!(Parser::default().docname(), None);
4537        }
4538
4539        #[test]
4540        fn strips_directory_and_extension() {
4541            assert_eq!(
4542                Parser::default()
4543                    .with_primary_file_name("mydoc.adoc")
4544                    .docname()
4545                    .as_deref(),
4546                Some("mydoc")
4547            );
4548            assert_eq!(
4549                Parser::default()
4550                    .with_primary_file_name("docs/guide/mydoc.adoc")
4551                    .docname()
4552                    .as_deref(),
4553                Some("mydoc")
4554            );
4555
4556            // A Windows-style separator is handled too, since the primary file
4557            // name may be supplied on either platform.
4558            assert_eq!(
4559                Parser::default()
4560                    .with_primary_file_name(r"docs\guide\mydoc.adoc")
4561                    .docname()
4562                    .as_deref(),
4563                Some("mydoc")
4564            );
4565        }
4566
4567        #[test]
4568        fn keeps_name_with_no_extension() {
4569            assert_eq!(
4570                Parser::default()
4571                    .with_primary_file_name("README")
4572                    .docname()
4573                    .as_deref(),
4574                Some("README")
4575            );
4576        }
4577
4578        #[test]
4579        fn none_when_path_has_no_file_component() {
4580            // A primary file name that ends in a separator has an empty base
4581            // name, which yields no document name.
4582            assert_eq!(
4583                Parser::default()
4584                    .with_primary_file_name("docs/guide/")
4585                    .docname(),
4586                None
4587            );
4588        }
4589
4590        #[test]
4591        fn leading_dot_name_is_kept_whole() {
4592            // A leading-dot name (e.g. `.adoc`) is treated as a dotfile with no
4593            // extension and kept whole, matching Ruby's
4594            // `File.basename(".adoc", ".*")`.
4595            assert_eq!(
4596                Parser::default()
4597                    .with_primary_file_name(".adoc")
4598                    .docname()
4599                    .as_deref(),
4600                Some(".adoc")
4601            );
4602        }
4603    }
4604
4605    mod counter {
4606        use super::super::next_counter_value;
4607        use crate::{document::InterpretedValue, tests::prelude::*};
4608
4609        #[test]
4610        fn next_counter_value_integer() {
4611            assert_eq!(next_counter_value("1"), "2");
4612            assert_eq!(next_counter_value("9"), "10");
4613            assert_eq!(next_counter_value("0"), "1");
4614            assert_eq!(next_counter_value("-1"), "0");
4615        }
4616
4617        #[test]
4618        fn next_counter_value_non_canonical_integer_is_advanced_as_a_string() {
4619            // A leading zero (or sign) does not round-trip through integer
4620            // parsing, so it is advanced like a string instead.
4621            assert_eq!(next_counter_value("07"), "08");
4622            assert_eq!(next_counter_value("+5"), "+6");
4623
4624            // A leading-zero value still carries digit-to-digit like a string.
4625            assert_eq!(next_counter_value("09"), "10");
4626            assert_eq!(next_counter_value("099"), "100");
4627        }
4628
4629        #[test]
4630        fn next_counter_value_saturates_at_i64_max() {
4631            // A counter pinned at `i64::MAX` stays there rather than panicking
4632            // (debug) or wrapping (release).
4633            let max = i64::MAX.to_string();
4634            assert_eq!(next_counter_value(&max), max);
4635        }
4636
4637        #[test]
4638        fn next_counter_value_characters() {
4639            assert_eq!(next_counter_value("a"), "b");
4640            assert_eq!(next_counter_value("A"), "B");
4641            assert_eq!(next_counter_value("z"), "aa");
4642            assert_eq!(next_counter_value("Z"), "AA");
4643            assert_eq!(next_counter_value("az"), "ba");
4644            assert_eq!(next_counter_value("zz"), "aaa");
4645            assert_eq!(next_counter_value("Zz"), "AAa");
4646        }
4647
4648        #[test]
4649        fn next_counter_value_trailing_non_alphanumeric() {
4650            // The right-most alphanumeric is incremented; trailing punctuation is
4651            // left in place.
4652            assert_eq!(next_counter_value("a)"), "b)");
4653        }
4654
4655        #[test]
4656        fn next_counter_value_no_alphanumeric() {
4657            // With nothing alphanumeric to carry, the final code point advances.
4658            assert_eq!(next_counter_value("{"), "|");
4659        }
4660
4661        #[test]
4662        fn counter_defaults_to_one() {
4663            let p = Parser::default();
4664            assert_eq!(p.counter("x", None), "1");
4665            assert_eq!(p.counter("x", None), "2");
4666            assert_eq!(
4667                p.attribute_value("x"),
4668                InterpretedValue::Value("2".to_string())
4669            );
4670            assert!(p.has_attribute("x"));
4671            assert!(p.is_attribute_set("x"));
4672        }
4673
4674        #[test]
4675        fn counter_seed_used_only_while_unset() {
4676            let p = Parser::default();
4677            assert_eq!(p.counter("c", Some("A")), "A");
4678
4679            // Once set, a later seed is ignored.
4680            assert_eq!(p.counter("c", Some("Q")), "B");
4681        }
4682
4683        #[test]
4684        fn counter_empty_seed_falls_back_to_one() {
4685            let p = Parser::default();
4686            assert_eq!(p.counter("c", Some("")), "1");
4687        }
4688    }
4689
4690    /// Coverage for the time-dependent document attributes (`docdate`,
4691    /// `doctime`, `docdatetime`, `docyear`, and their `local*` siblings) that
4692    /// is *not* a direct port of Asciidoctor's Ruby tests: the injectable
4693    /// clock ([`Parser::with_reference_time`] /
4694    /// [`Parser::with_input_mtime`]), and resolution *during* a parse (a
4695    /// `{docdate}` reference or an `ifdef::docdate[]` directive) rather
4696    /// than off the finished document.
4697    ///
4698    /// The direct Ruby ports live alongside the vendored suite in
4699    /// `tests/asciidoctor_rb/document_test.rs`.
4700    mod datetime_attributes {
4701        use crate::{parser::ReferenceTime, tests::prelude::*};
4702
4703        #[test]
4704        fn pins_local_attributes_with_reference_time() {
4705            // The injectable clock (this crate's stable-output mechanism) pins
4706            // the `local*` attributes, which Asciidoctor derives from
4707            // `::Time.now`.
4708            let doc = Parser::default()
4709                .with_reference_time(ReferenceTime::from_local(2019, 1, 2, 3, 4, 5, 6 * 3600))
4710                .parse("");
4711
4712            assert_eq!(
4713                doc.attribute_value("localdate"),
4714                InterpretedValue::Value("2019-01-02")
4715            );
4716            assert_eq!(
4717                doc.attribute_value("localyear"),
4718                InterpretedValue::Value("2019")
4719            );
4720            assert_eq!(
4721                doc.attribute_value("localtime"),
4722                InterpretedValue::Value("03:04:05 +0600")
4723            );
4724            assert_eq!(
4725                doc.attribute_value("localdatetime"),
4726                InterpretedValue::Value("2019-01-02 03:04:05 +0600")
4727            );
4728        }
4729
4730        #[test]
4731        fn resolves_date_attributes_referenced_in_the_document_body() {
4732            // A `{docdate}` reference resolves the attribute on demand through
4733            // the parser (during substitution), not off the finished document
4734            // snapshot.
4735            let doc = Parser::default()
4736                .with_reference_time(ReferenceTime::from_unix_timestamp(1_420_106_400))
4737                .parse("docdate={docdate} docyear={docyear} docdatetime={docdatetime}");
4738
4739            assert_eq!(
4740                rendered_paragraphs(&doc),
4741                vec![
4742                    "docdate=2015-01-01 docyear=2015 docdatetime=2015-01-01 10:00:00 UTC"
4743                        .to_string()
4744                ]
4745            );
4746        }
4747
4748        #[test]
4749        fn conditional_directive_sees_a_computed_date_attribute() {
4750            // `ifdef` queries `is_attribute_set`, which must report the computed
4751            // `docdate` as set.
4752            let doc = Parser::default()
4753                .with_reference_time(ReferenceTime::from_unix_timestamp(1_420_106_400))
4754                .parse("ifdef::docdate[present]");
4755
4756            assert_eq!(rendered_paragraphs(&doc), vec!["present".to_string()]);
4757        }
4758
4759        #[test]
4760        fn an_explicit_doctime_feeds_the_computed_docdatetime() {
4761            // An explicit `doctime` (a stored value) supplies the time portion
4762            // of the computed `docdatetime`, both when referenced in the body
4763            // and when read off the document.
4764            let mut parser = Parser::default()
4765                .with_reference_time(ReferenceTime::from_unix_timestamp(1_420_106_400))
4766                .with_intrinsic_attribute(
4767                    "doctime",
4768                    "09:09:09-0500",
4769                    ModificationContext::ApiOrHeader,
4770                );
4771            let doc = parser.parse("at {docdatetime}");
4772
4773            assert_eq!(
4774                rendered_paragraphs(&doc),
4775                vec!["at 2015-01-01 09:09:09-0500".to_string()]
4776            );
4777            assert_eq!(
4778                doc.attribute_value("docdatetime"),
4779                InterpretedValue::Value("2015-01-01 09:09:09-0500")
4780            );
4781        }
4782
4783        #[test]
4784        fn an_unset_doctime_falls_back_to_the_reference_time() {
4785            // An explicitly unset `doctime` is treated as absent, so
4786            // `docdatetime` falls back to the reference instant's time.
4787            let mut parser = Parser::default()
4788                .with_reference_time(ReferenceTime::from_unix_timestamp(1_420_106_400))
4789                .with_intrinsic_attribute_bool("doctime", false, ModificationContext::ApiOrHeader);
4790            let doc = parser.parse("at {docdatetime}");
4791
4792            assert_eq!(
4793                rendered_paragraphs(&doc),
4794                vec!["at 2015-01-01 10:00:00 UTC".to_string()]
4795            );
4796            assert_eq!(
4797                doc.attribute_value("docdatetime"),
4798                InterpretedValue::Value("2015-01-01 10:00:00 UTC")
4799            );
4800        }
4801
4802        #[test]
4803        fn a_value_less_doctime_reads_as_an_empty_time() {
4804            // A value-less `doctime` (set, but with no value) contributes an
4805            // empty time, leaving a trailing space in the computed
4806            // `docdatetime`.
4807            let mut parser = Parser::default()
4808                .with_reference_time(ReferenceTime::from_unix_timestamp(1_420_106_400))
4809                .with_intrinsic_attribute_bool("doctime", true, ModificationContext::ApiOrHeader);
4810            let doc = parser.parse("x{docdatetime}x");
4811
4812            assert_eq!(rendered_paragraphs(&doc), vec!["x2015-01-01 x".to_string()]);
4813            assert_eq!(
4814                doc.attribute_value("docdatetime"),
4815                InterpretedValue::Value("2015-01-01 ")
4816            );
4817        }
4818    }
4819
4820    // Crate-native `skip-front-matter` cases (no Asciidoctor analog) covering
4821    // edge conditions beyond the reader-suite ports in
4822    // `tests::asciidoctor_rb::reader_test`. See [`Parser::skip_front_matter`].
4823    mod skip_front_matter {
4824        use crate::tests::prelude::*;
4825
4826        #[test]
4827        fn crlf_line_endings() {
4828            // The front-matter delimiters are matched after a CRLF line ending
4829            // is stripped, and the captured `front-matter` value is likewise
4830            // chomped, so a document with `\r\n` line endings is handled the
4831            // same as one with bare `\n`.
4832            let doc = Parser::default()
4833                .with_intrinsic_attribute_bool(
4834                    "skip-front-matter",
4835                    true,
4836                    ModificationContext::ApiOnly,
4837                )
4838                .parse("---\r\nlayout: post\r\ntitle: Document Title\r\n---\r\n= Document Title\r\nAuthor Name\r\n\r\npreamble\r\n");
4839
4840            assert_eq!(
4841                doc.attribute_value("front-matter"),
4842                InterpretedValue::Value("layout: post\ntitle: Document Title")
4843            );
4844            assert_eq!(doc.header().title(), Some("Document Title"));
4845            assert_eq!(doc.header().title_source().unwrap().line(), 5);
4846        }
4847
4848        #[test]
4849        fn first_line_is_not_a_delimiter() {
4850            // With `skip-front-matter` set but no opening `---` on the first
4851            // line, there is nothing to skip: the document parses normally and
4852            // no `front-matter` attribute is recorded.
4853            let doc = Parser::default()
4854                .with_intrinsic_attribute_bool(
4855                    "skip-front-matter",
4856                    true,
4857                    ModificationContext::ApiOnly,
4858                )
4859                .parse("= Document Title\nAuthor Name\n\npreamble\n");
4860
4861            assert_eq!(doc.attribute_value("front-matter"), InterpretedValue::Unset);
4862            assert_eq!(doc.header().title(), Some("Document Title"));
4863            assert_eq!(doc.header().title_source().unwrap().line(), 1);
4864        }
4865    }
4866}